SQLAlchemy 2.0 Async in Production: Resolving MissingGreenlet, Connection Pool Leaks, N+1 Queries & Transaction Deadlocks

SQLAlchemy 2.0 async production failure modes: MissingGreenlet on expired attributes, N+1 query counts, connection pool exhaustion and lock retry measurements

Production Executive Summary: An async SQLAlchemy service fails in four reproducible ways, and none of them raises a database error you can route around. A lazy attribute touched after commit() raises MissingGreenlet inside your own serializer. A relationship loaded per row turns one page render into a hundred and twenty round trips. A session that is not closed on an exception takes a connection out of the pool until the process restarts. A retry that replays every database error amplifies the deadlock it was supposed to survive. Each one is cheap to prevent and expensive to diagnose, because the traceback points at the ORM while the damage lands on the event loop, the pool, and the database’s lock table.

This runbook reproduces all four in a sandbox, measures them, and then fixes them with code that was executed in that same sandbox. Every number below comes from the verification section: SQLAlchemy 2.0.57, aiosqlite 0.22.1, asyncpg 0.32.0, greenlet 3.5.6, Python 3.12.16, two vCPUs, 1,486 MB of RAM. Where a conclusion needs PostgreSQL itself – row-lock deadlock detection, statement_timeout, idle_in_transaction_session_timeout – the article says so and separates the measured result from the documented server behaviour.

The One Rule Behind All Four Failures: The async ORM is a synchronous ORM running inside a greenlet. Every attribute access that needs IO is a synchronous call that the greenlet bridge turns into an await, and that bridge only exists while you are inside an awaited ORM call. Read a lazy attribute anywhere else – after commit(), in a Pydantic validator, in a background callback – and there is no greenlet to await on. MissingGreenlet is not a bug in your query; it is the ORM telling you that you attempted IO outside the one place IO is allowed.

1. What the Async Session Actually Is

SQLAlchemy 2.0 did not rewrite the ORM for async. It kept the synchronous ORM and wrapped it in a greenlet: AsyncSession hands the synchronous unit of work to greenlet_spawn(), which starts a second stack, lets the sync code run as far as it can, and switches back to the event loop whenever the sync code calls await_only(). That is how await session.execute(select(...)) can run code written for a blocking driver. The bridge is per-call, and it is invisible from the outside.

Everything that follows is a consequence of that design. Because the bridge exists only while a call is being awaited, IO outside such a call has nowhere to suspend. Because the ORM was written for a world where implicit IO was acceptable, commit() expires attributes and relationship access loads lazily – both of which are implicit IO. The async layer does not remove those behaviours; it converts them into runtime errors and hidden round trips.

The three errors below are easy to confuse because two of them share a base class, and only one of them is actually a MissingGreenlet. The measured column comes from probe 1 in this article’s verification suite.

ExceptionRaised whenMeasured in sandboxWhat it means for the design
MissingGreenletIO is attempted while no greenlet bridge is active: an expired attribute, a lazy relationship, a refresh() outside an awaited callgreenlet_spawn has not been called; can't call await_only() here in 1.07 ms after commit(), at _concurrency_py3k.py:123You are reading data you did not load. Fix the loading strategy, not the exception
DetachedInstanceErrorAn unloaded attribute is touched after the session closed; the instance no longer has a connection to load from0.04 ms when article.author was read after the async with block endedYou are serializing ORM objects past the session boundary. Build the response inside it
InvalidRequestError from lazy='raise'A relationship configured or queried with raiseload() is accessed without being eagerly loaded'Article.comments' is not available due to lazy='raise' in 0.03 msThe guard fired exactly as intended: this is the error you want in CI, not in production
Table 1: Three failures that look alike. Only the first is a greenlet problem; all three are loading-strategy problems, and the third is the one you can test for.

MissingGreenlet subclasses InvalidRequestError, so a broad except InvalidRequestError catches both it and the raiseload guard. DetachedInstanceError sits somewhere else entirely: in SQLAlchemy 2.0.57 its direct base is SQLAlchemyError, and ORMException – the name some guides still use for it – cannot be imported from sqlalchemy.orm.exc at all (the 1.4 ORM exception list has no such name either). The probe below reads both facts from the interpreter that produced every other number in this article:

from sqlalchemy.exc import InvalidRequestError, MissingGreenlet, SQLAlchemyError
from sqlalchemy.orm.exc import DetachedInstanceError


async def case_exception_hierarchy(engine) -> dict:
    """The bases you have to catch, read from the classes themselves."""
    detached = DetachedInstanceError("unloaded attribute after close")
    try:
        from sqlalchemy.orm.exc import ORMException  # noqa: F401  - not importable on 2.x, checked not assumed
        orm_exception = "importable"
    except ImportError as exc:
        orm_exception = f"ImportError: {exc}"
    return {
        "mro": [cls.__name__ for cls in DetachedInstanceError.__mro__],
        "orm_exception_name": orm_exception,
        "caught_by_InvalidRequestError": isinstance(detached, InvalidRequestError),
        "caught_by_MissingGreenlet": isinstance(detached, MissingGreenlet),
        "caught_by_SQLAlchemyError": isinstance(detached, SQLAlchemyError),
    }

Exception hierarchy reality check: Catch SQLAlchemyError when you mean “any database-layer failure” and InvalidRequestError when you mean “ORM misuse”; neither covers the other, and a handler written for ORMException cannot even be imported on 2.x. The practical consequence is that DetachedInstanceError needs its own branch, placed where the response is built rather than where the query runs – it is the failure of a read that happened after the session closed.

2. Failure Mode 1: MissingGreenlet on an Expired Attribute

The most common production MissingGreenlet has a dull origin: sessionmaker defaults to expire_on_commit=True, so a successful commit() expires every attribute of every object in the session. The next read of author.name – a plain column, already fetched once – triggers a refresh, the refresh needs IO, and with no greenlet bridge active the ORM raises. The error names a concurrency helper, which is why teams spend an afternoon reading about greenlets when the fix is a session option.

import time
from sqlalchemy.exc import MissingGreenlet
from harness import session_factory
from models import Author


async def case_expired_after_commit(engine) -> dict:
    """expire_on_commit=True: every attribute of a loaded object is expired by commit."""
    maker = session_factory(engine, expire_on_commit=True)
    detail: dict = {}
    async with maker() as session:
        author = Author(name="Grace Hopper", handle="grace")
        session.add(author)
        await session.commit()
        start = time.perf_counter()
        try:
            _ = author.name
            detail["outcome"] = "attribute readable"
        except MissingGreenlet as exc:
            detail["outcome"] = "MissingGreenlet"
            detail["error_message"] = str(exc).strip().splitlines()[0]
            detail["error_class"] = type(exc).__name__
            detail["is_missing_greenlet"] = isinstance(exc, MissingGreenlet)
            detail["elapsed_ms"] = round((time.perf_counter() - start) * 1000.0, 2)
    return detail

The measured failure is 1.07 ms of work followed by an exception, and the important detail is that nothing about the query was wrong. The insert committed. The object existed. Only the read-back did not have anywhere to suspend. The same shape appears when a lazy many-to-one is touched inside the session after a load: 1.57 ms, raised from _concurrency_py3k.py:123, with the message that has become a genre of its own.

import pathlib
import time
import traceback
from sqlalchemy import select
from sqlalchemy.exc import MissingGreenlet
from harness import session_factory
from models import Article


async def case_default_session(engine) -> dict:
    """Default async_sessionmaker: expire_on_commit=True."""
    maker = session_factory(engine)
    detail: dict = {}
    async with maker() as session:
        article = (await session.execute(select(Article).limit(1))).scalar_one()
        start = time.perf_counter()
        try:
            _ = article.title
            _ = article.views
            detail["plain_columns_after_load"] = "ok"
            _ = article.author.name  # lazy many-to-one after commit-expiry
            detail["lazy_access"] = "returned without error"
        except MissingGreenlet as exc:
            detail["error_type"] = type(exc).__name__
            detail["error_message"] = str(exc).strip().splitlines()[0]
            detail["elapsed_ms"] = round((time.perf_counter() - start) * 1000.0, 2)
            frame = traceback.extract_tb(exc.__traceback__)[-1]
            detail["raised_at"] = f"{pathlib.Path(frame.filename).name}:{frame.lineno}"
    return detail

Rung 1: stop expiring what you already have

For a request-scoped session, expire_on_commit=False is the correct default. The values were just written by this transaction; re-reading them from the server is a round trip that buys nothing and costs a potential exception. The sandbox reads the committed name and id back with zero extra statements.

from harness import QueryCounter, session_factory
from models import Author


async def case_fix_expire_off(engine) -> dict:
    """Fix rung 1: expire_on_commit=False keeps committed values usable."""
    maker = session_factory(engine, expire_on_commit=False)
    detail: dict = {}
    async with maker() as session:
        author = Author(name="Katherine Johnson", handle="katherine")
        session.add(author)
        await session.commit()
        with QueryCounter(engine) as counter:
            name = author.name
            identifier = author.id
        detail["values_read"] = {"name": name, "id": identifier}
        detail["extra_queries"] = counter.count
    return detail

Where this option is wrong: Do not reach for expire_on_commit=False as a global truth serum. It is right for a request session that commits and returns its own data. It is wrong for a long-lived session in a worker that must see other transactions’ writes; there you want an explicit refresh() or a fresh query, not a cached object pretending to be current.

Rung 2: load the graph you are going to serialize

The durable fix is to know, at query time, what the response needs. A page of article cards needs each article’s author name and comment count; that is two batched statements, not a per-row walk. Loading them explicitly also documents the cost next to the query, where a reviewer will see it.

from sqlalchemy import select
from sqlalchemy.orm import selectinload
from harness import QueryCounter, session_factory
from models import Article


async def case_fix_eager_load(engine) -> dict:
    """Fix rung 2: load the graph you know you need, then serialize inside the session."""
    maker = session_factory(engine, expire_on_commit=False)
    async with maker() as session:
        with QueryCounter(engine) as counter:
            rows = (
                await session.execute(
                    select(Article)
                    .options(selectinload(Article.author), selectinload(Article.comments))
                    .order_by(Article.id)
                )
            ).scalars().all()
            payload = [
                {"slug": a.slug, "author": a.author.name, "comments": len(a.comments)}
                for a in rows
            ]
        return {"articles": len(payload), "queries": counter.count, "payload": payload}

Two articles, three statements: the articles, one batched SELECT ... IN () for authors, and one for comments. The payload was built inside the session, which is the second half of the rule.

Rung 3: serialize inside the session, not after it

Returning ORM objects from a repository and letting the route serialize them is how the session boundary gets crossed. After the session closes, the same attribute access that raised MissingGreenlet inside now raises DetachedInstanceError – a different class, the same root cause, and a much less obvious message. Build a plain dataclass or dict while the session is open, as ArticleCard.from_row() does later in this article.

import time
from sqlalchemy import select
from harness import session_factory
from models import Article


async def case_detached(engine) -> dict:
    """After the session closes, an unloaded lazy attribute fails differently again."""
    maker = session_factory(engine, expire_on_commit=False)
    async with maker() as session:
        article = (await session.execute(select(Article).limit(1))).scalar_one()
        slug = article.slug
    detail = {"slug_inside_session": slug}
    start = time.perf_counter()
    try:
        _ = article.author.name
        detail["outcome"] = "loaded"
    except Exception as exc:  # noqa: BLE001 - the probe classifies the failure
        detail["outcome"] = type(exc).__name__
        detail["error_message"] = str(exc).strip().splitlines()[0]
        detail["elapsed_ms"] = round((time.perf_counter() - start) * 1000.0, 3)
    return detail

Rung 4: make the mistake fail in CI, not in production

Eager loading is a discipline, and disciplines decay. raiseload() converts a forgotten loader into a deterministic InvalidRequestError with the attribute name in the message – the cheapest regression test the ORM offers. Apply it per query while a codebase is being converted, and at model level (lazy="raise") once the repositories are the only place that loads relationships.

import time
from sqlalchemy import select
from sqlalchemy.exc import InvalidRequestError, MissingGreenlet
from sqlalchemy.orm import raiseload
from harness import session_factory
from models import Article


async def case_raiseload(engine) -> dict:
    """Guard: raiseload turns an accidental implicit IO into a deterministic error."""
    maker = session_factory(engine, expire_on_commit=False)
    async with maker() as session:
        stmt = select(Article).options(raiseload(Article.comments)).order_by(Article.id).limit(1)
        article = (await session.execute(stmt)).scalar_one()
        start = time.perf_counter()
        try:
            _ = len(article.comments)
            return {"outcome": "no error"}
        except InvalidRequestError as exc:
            return {
                "outcome": "InvalidRequestError",
                "error_message": str(exc).strip().splitlines()[0],
                "elapsed_ms": round((time.perf_counter() - start) * 1000.0, 3),
                "is_missing_greenlet": isinstance(exc, MissingGreenlet),
            }

The explicit alternative to raising: If a route legitimately cannot know in advance what it will touch – a generic serializer, an audit hook – use AsyncAttrs from sqlalchemy.ext.asyncio and access relationships through await obj.awaitable_attrs.articles. That trades the crash for an explicit await that a reviewer can see, which is the whole point of the async layer.

3. Failure Mode 2: N+1 That Survives the Async Rewrite

The classic N+1 story is about a lazy relationship loaded in a loop. In async SQLAlchemy that particular code cannot even run – it raises MissingGreenlet on the first access. So teams conclude the problem is gone, and then ship two shapes that are the same problem with a different disguise: an awaited query inside a for loop in the serializer, and a lazy load driven through AsyncSession.run_sync(), where a synchronous ORM call is inside the greenlet and implicit IO is allowed again.

Both were measured on identical data: 120 authors, 960 articles, 1,920 comments, five repetitions per strategy, median wall-clock and statement count taken from an before_cursor_execute listener that counts what the driver actually received.

StrategyStatementsMedian wallDriver rowsVerdict
Lazy load via run_sync()12181.97 ms1,080The N+1 you think you removed
Awaited query inside a loop12166.78 ms240Same cost, now visible in the code
selectinload() for the collection211.02 ms120 + 960Default choice for one-to-many
joinedload() for the collection19.20 ms960Fastest here, but the join duplicates rows
Chained selectinload(), three levels443.74 ms120 + 960 + 1,920Two comment batches: the 500-parameter batch limit
raiseload() guard11.51 ms120Fails in 0.03 ms with the attribute named
Table 2: The same page, six loading strategies. 121 statements versus 2 is a 60x reduction in round trips and a 7.4x reduction in wall-clock time on a local database.

Why the ratio matters more than the milliseconds: The distance between 60x fewer statements and 7.4x less time is the honest part of this table. On a local SQLite file a statement costs tens of microseconds, so the ORM overhead dominates. On a managed PostgreSQL reachable in 0.5 ms the same 121 statements add roughly 60 ms of pure network time per request, and at 40 requests per second that is 4,840 statements per second against a database whose connection budget you are already rationing.

Chained loaders are not one statement per level

The three-level case needs a note, because the obvious mental model is wrong. Loading authors with their articles and then each article’s comments emits four statements, not three: selectinload() batches the IN list at 500 parameters, and 960 article ids do not fit in one batch. The parameter sizes recorded by the listener were 500 and 460. Any page whose collection crosses a batch boundary pays an extra round trip per multiple of 500, and PostgreSQL’s own bind-parameter ceiling (32,767 in a prepared statement) is the wall you hit if you try to defeat batching by hand.

Deciding the loader, once, in the repository

A loader decision per route is a loader decision that will eventually be wrong, because routes get reused. Put the decision next to the query, return a plain object, and let the route stay ignorant of the ORM. The repository below is the one executed in probe 6; the statement counts in its docstrings are measured output, not expectations.

from dataclasses import dataclass
from typing import Any
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload, selectinload
from models import Article, Author


@dataclass(frozen=True, slots=True)
class ArticleCard:
    slug: str
    title: str
    author: str
    comments: int

    @classmethod
    def from_row(cls, article: Article) -> "ArticleCard":
        """Build the response object while the session is still open."""
        return cls(
            slug=article.slug,
            title=article.title,
            author=article.author.name,
            comments=len(article.comments),
        )


async def list_article_cards(session: AsyncSession, limit: int = 20) -> list[ArticleCard]:
    """Two batched SELECTs for the whole page: one for articles, one for comments.

    The author is fetched with joinedload because it is a many-to-one, so it can
    ride on the same statement without duplicating the article rows.
    """
    stmt = (
        select(Article)
        .options(joinedload(Article.author), selectinload(Article.comments))
        .order_by(Article.published_at.desc(), Article.id.desc())
        .limit(limit)
    )
    rows = (await session.execute(stmt)).unique().scalars().all()
    return [ArticleCard.from_row(article) for article in rows]


async def author_overview(session: AsyncSession, limit: int = 50) -> list[dict[str, Any]]:
    """Aggregate in SQL when the response only needs counts, never load the rows."""
    stmt = (
        select(
            Author.handle,
            func.count(Article.id).label("articles"),
            func.coalesce(func.sum(Article.views), 0).label("views"),
        )
        .join(Article, Article.author_id == Author.id)
        .group_by(Author.handle)
        .order_by(func.count(Article.id).desc())
        .limit(limit)
    )
    return [
        {"handle": handle, "articles": articles, "views": int(views)}
        for handle, articles, views in (await session.execute(stmt)).all()
    ]


async def article_detail(session: AsyncSession, slug: str) -> dict[str, Any] | None:
    """Detailed view: one article, its author and its comments in two statements."""
    stmt = (
        select(Article)
        .options(joinedload(Article.author), selectinload(Article.comments))
        .where(Article.slug == slug)
    )
    article = (await session.execute(stmt)).unique().scalar_one_or_none()
    if article is None:
        return None
    return {
        "slug": article.slug,
        "title": article.title,
        "views": article.views,
        "author": article.author.name,
        "comments": [comment.body for comment in article.comments],
    }

Measured in the integration probe: list_article_cards(40) returns 40 cards in 2 statements (one for articles with the author joined on, one batched for comments), author_overview() returns 40 rows in 1 statement because the counts are aggregated in SQL, article_detail() is 2, and a missing slug is 1.

When the response only needs a number, do not load the rows

The most common remaining N+1 is not a relationship at all: it is len(obj.children) in a template. If the response prints a count, ask the database for a count. comment_counts() below replaces N counts with one grouped aggregate keyed by article id, and it composes with the card query because both are just statements in the same session.

from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from models import Comment


async def comment_counts(session: AsyncSession, article_ids: list[int]) -> dict[int, int]:
    """Grouped aggregate instead of one COUNT per parent."""
    if not article_ids:
        return {}
    stmt = (
        select(Comment.article_id, func.count(Comment.id))
        .where(Comment.article_id.in_(article_ids))
        .group_by(Comment.article_id)
    )
    return {article_id: count for article_id, count in (await session.execute(stmt)).all()}

The unique() requirement: joinedload() plus selectinload() in the same query is fine, but joinedload() against a collection requires .unique() on the result before .scalars(). Forgetting it raises InvalidRequestError: The unique() method must be invoked – a confusing error for a correct-looking query, and the reason the repository above calls .unique() even when the collection is batched.

4. Failure Mode 3: Pool Exhaustion and Sessions That Never Return

A connection pool is a semaphore with a queue in front of it, and every async service has two of them: the pool inside each process, and the database’s own max_connections. The defaults (5 + 10 overflow, 30 s timeout, per process) are designed to be helpful in development and are actively dangerous in a fleet, because the ceiling is multiplied twice before the server sees it: once by the workers inside each pod, and again by the replicas the autoscaler adds without asking anyone.

QuantityFormulaExample fleetWhy it bites
Per-process ceilingpool_size + max_overflow10 + 20 = 30Overflow is the knob that hides a bad pool_size
Pod countminReplicas .. maxReplicas (the autoscaler)2 .. 6 podsValidate against maxReplicas, not against today’s replica count
Fleet demandpods x workers x (pool_size + max_overflow)2 x 4 x (10 + 20) = 240Silently exceeds a default 100-connection server long before the HPA reaches six pods
Server budgetmax_connections - reserved100 – 15 = 85Reserve for migrations, cron, PgBouncer admin, monitoring probes
Verdict at bootfleet_demand <= budget240 > 85 – refuse to startA boot failure is cheaper than a 3 a.m. connection storm
Table 3: The pool budget worksheet. The only number the server sees is the product of all three factors, so the product is what the configuration must validate.

Validating that arithmetic at boot is not decorative. The settings module in section 6 rejects the example fleet with the message below, and rejects a zero pool timeout with a second message, before the process opens a single socket:

pool budget exceeded: 2 pods x 4 workers x 30 = 240 connections, but only 85 are
available after reserving 15

pool_timeout must be positive: a zero timeout turns backpressure into errors

Saturation is a latency problem before it is an error

With a pool of two connections, eight concurrent handlers that hold their connection for 300 ms do not fail – they queue. All eight completed, median request 756.9 ms, slowest 1,209.3 ms, which is four waves of 300 ms plus ORM overhead. Nothing in the logs looks broken. The p99 chart does.

Raise the concurrency to 24 against the same pool and the queue becomes a cliff: eight requests completed and sixteen failed with the pool’s own timeout after 1.0 s, because the fifth wave could not begin before the timeout expired. The same workload, one configuration value apart, is either slow or partially down.

ScenarioConcurrencyPoolCompletedFailedMedianSlowest
Queue, no errors82 + 0, timeout 1.0 s80756.9 ms1,209.3 ms
Saturation cliff242 + 0, timeout 1.0 s8161,001.5 ms1,211.5 ms
Leaked slots12 + 0, all leaked01 (after 1,001.7 ms)––
Scope with try/finally6 failing handlers2 + 00 slots leaked0––
Table 4: Pool behaviour with 300 ms hold time. Timeouts are the pool’s own TimeoutError, not a database error.

The leak that never recovers

A handler that acquires a connection, raises, and never closes its session leaks the slot permanently. Two such failures on a pool of two leave the pool reporting Connections in pool: 0 Current Checked out connections: 2, and every subsequent checkout waits the full timeout and then fails – 1,001.7 ms per request, forever, on a database that is perfectly healthy. The garbage collector eventually prints The garbage collector is trying to clean up non-checked-in connection ... Please ensure that SQLAlchemy pooled connections are returned to the pool explicitly, which is the only warning the process will give you.

import time
from sqlalchemy import select
from harness import session_factory
POOL_SIZE = 2
POOL_TIMEOUT = 1.0


async def case_leak(engine) -> dict:
    """A failing handler that never closes its session permanently loses a slot."""
    log: list[str] = []
    for n in range(POOL_SIZE):
        session = session_factory(engine, expire_on_commit=False)()
        try:
            await session.execute(select(1))
            raise RuntimeError(f"handler failure {n}")
        except RuntimeError as exc:
            log.append(f"{exc} -> checked_out={engine.pool.checkedout()} (slot never returned)")
    start = time.perf_counter()
    blocked = "acquired"
    try:
        async with session_factory(engine, expire_on_commit=False)() as session:
            await session.execute(select(1))
    except Exception as exc:  # noqa: BLE001
        blocked = f"{type(exc).__name__}: {str(exc).splitlines()[0][:80]}"
    blocked_wait = (time.perf_counter() - start) * 1000.0
    pool_status = str(engine.pool.status())
    start = time.perf_counter()
    await engine.dispose()
    recovered = "acquired"
    try:
        async with session_factory(engine, expire_on_commit=False)() as session:
            await session.execute(select(1))
    except Exception as exc:  # noqa: BLE001
        recovered = type(exc).__name__
    return {
        "leak_log": log,
        "pool_status_while_leaked": pool_status,
        "next_checkout": blocked,
        "next_checkout_wait_ms": round(blocked_wait, 1),
        "after_engine_dispose": recovered,
        "after_dispose_checkout_ms": round((time.perf_counter() - start) * 1000.0, 1),
    }

Two facts from that measurement deserve to be in a runbook. First, the failure is not self-healing: the pool had to be disposed before a checkout succeeded again, and after engine.dispose() the next checkout took 3.9 ms. Second, the leak is not caused by an await that was forgotten – the transaction is open because the SELECT ran inside an implicit transaction that was never ended. A read-only query holds a connection until commit(), rollback() or close(); the probe measured checkedout=1 while the session was open and 0 immediately after rollback().

from sqlalchemy import select
from harness import session_factory
POOL_SIZE = 2
POOL_TIMEOUT = 1.0


async def case_implicit_transaction(engine) -> dict:
    """A read-only query still holds a connection until its transaction ends."""
    session = session_factory(engine, expire_on_commit=False)()
    await session.execute(select(1))
    during = engine.pool.checkedout()
    await session.rollback()
    after_rollback = engine.pool.checkedout()
    await session.close()
    return {
        "checkedout_while_session_open": during,
        "checkedout_after_rollback": after_rollback,
        "checkedout_after_close": engine.pool.checkedout(),
    }

The fix is a scope, not a convention

A single context manager that owns the exit path makes the leak unreachable. It commits on success, rolls back on any exception – including CancelledError, which is a BaseException and therefore not caught by except Exception – and closes in finally. With it, six consecutive handler failures left checked_out=0 every time.

import time
from sqlalchemy import select
from harness import session_factory
POOL_SIZE = 2
POOL_TIMEOUT = 1.0


async def case_leak_fixed(engine) -> dict:
    """The same failing handler with try/finally: the slot comes back every time."""
    checked_out: list[int] = []
    for n in range(POOL_SIZE * 3):
        session = session_factory(engine, expire_on_commit=False)()
        try:
            await session.execute(select(1))
            raise RuntimeError(f"handler failure {n}")
        except RuntimeError:
            pass
        finally:
            await session.close()
        checked_out.append(engine.pool.checkedout())
    return {"checked_out_after_each_failure": checked_out, "status": str(engine.pool.status())}

The application version of the same idea, executed in probe 6, is deliberately small enough to audit: the pool is built in one function, validated before use, and every caller receives a session that is closed on every path.

Deadlines and rechecks: what they do and do not buy

Two pool settings get recommended without their costs. pool_pre_ping=True issues a lightweight round trip when a connection is taken from the pool, which protects against a server or proxy that killed idle connections. Measured on a local SQLite checkout, it cost 0.27 ms median (0.572 to 0.843 ms) and 0.47 ms at p95; on PostgreSQL that number is one network round trip per checkout, which is real money on a latency-sensitive endpoint. pool_recycle closes connections that are older than the limit instead of handing them out, which is how you survive a 5-minute idle timeout at a load balancer; it does not verify liveness, so it is a complement to pre-ping, not a replacement.

Client deadline is not a server cancel: An asyncio.timeout() around a session bounds how long the caller waits. It does not cancel the statement already running on the server, and it does not return the connection at the deadline: in the sandbox a 50 ms deadline on a long CTE returned control at 776.8 ms, because the driver call was not at an await boundary until the server finished. Use a server-side statement_timeout for the work, and the client timeout for the caller.

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine
from config import DatabaseSettings


def build_engine(settings: DatabaseSettings) -> AsyncEngine:
    """Create the only pool the process owns.

    The pool ceiling is validated before the first connection is opened, so a
    misconfigured fleet fails at boot instead of failing at 3 a.m.
    """
    settings.validate()
    connect_args: dict[str, object] = {}
    if settings.url.startswith("postgresql+asyncpg"):
        connect_args = {
            "server_settings": {
                "application_name": "techbobby-api",
                "statement_timeout": str(settings.statement_timeout_ms),
                "idle_in_transaction_session_timeout": "30000",
            },
            "timeout": settings.pool_timeout,
            "command_timeout": settings.statement_timeout_ms / 1000,
        }
    return create_async_engine(
        settings.url,
        pool_size=settings.pool_size,
        max_overflow=settings.max_overflow,
        pool_timeout=settings.pool_timeout,
        pool_recycle=settings.pool_recycle,
        pool_pre_ping=settings.pool_pre_ping,
        pool_use_lifo=settings.pool_use_lifo,
        connect_args=connect_args,
        echo=False,
    )


def build_sessionmaker(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
    """expire_on_commit=False: committed attributes stay readable without implicit IO."""
    return async_sessionmaker(
        engine,
        expire_on_commit=False,
        autoflush=False,
        autobegin=True,
    )


@asynccontextmanager
async def session_scope(
    maker: async_sessionmaker[AsyncSession],
    *,
    readonly: bool = False,
) -> AsyncIterator[AsyncSession]:
    """Guarantee that the connection returns to the pool on every exit path."""
    session = maker()
    try:
        yield session
        if not readonly:
            await session.commit()
        else:
            await session.rollback()
    except BaseException:
        await session.rollback()
        raise
    finally:
        await session.close()

Note the asymmetric discipline in build_engine(): pool geometry is validated before creation, and the PostgreSQL-only arguments – statement_timeout, idle_in_transaction_session_timeout, command_timeout – are attached only for the asyncpg URL. On any other dialect those keys would be passed to a driver that does not understand them.

5. Failure Mode 4: Lock Waits, Deadlocks and Retries That Make It Worse

A deadlock in PostgreSQL is a cycle in the row-lock wait graph. After deadlock_timeout (1 s by default) the server detects the cycle, aborts one participant with SQLSTATE 40P01, and lets the others proceed. The aborted transaction is gone: its statements are rolled back and its application code is holding an exception. That is the whole mechanism, and it has two consequences that decide the design. First, the database resolves deadlocks for you – what it cannot do is decide whether the aborted unit of work is safe to replay. Second, the detection is a timeout, so a deadlock costs at least a second of wall clock before anyone sees the error.

This sandbox has no PostgreSQL server, so the contention measurements below are SQLite in WAL mode with real files and real lock waits. busy_timeout plays exactly the role lock_timeout plays in PostgreSQL: it is the deadline for acquiring a write lock before the statement fails. What SQLite cannot exhibit is a lock-order cycle, because it has a single writer – so the ordering advice in this section is stated as PostgreSQL semantics, while the waiting and retrying it produces are measured.

busy_timeoutHolder keeps the write lock 250 msContender outcomeContender wait
0 ms250 msOperationalError: database is locked9.4 ms
100 ms250 msOperationalError: database is locked110.9 ms
2,000 ms250 mscommitted243.8 ms
Table 5: The lock deadline is a trade, not a setting. Too short fails healthy requests; long enough to succeed turns a lock wait into 244 ms of held request time.

The middle row is the trap. A 100 ms deadline does not protect anything: it fails after waiting 110.9 ms, which is almost as long as waiting for success. If a lock wait is acceptable, make the deadline long enough to win; if it is not, fail in single-digit milliseconds and let the caller decide. Anything in between burns the budget twice.

Retrying is not free, and not always an improvement

Eight writers, six transactions each, 48 write transactions against two hot rows, pool of 8 connections, no lock deadline. Three policies, three runs each, median reported:

PolicyCommittedFailedMedian wallWhat it teaches
No retry9 / 483986.2 msContention at this level is a request failure, not a slow request
Fixed 50 ms backoff, 6 attempts45 / 483591.1 msRetries convert failures into seconds of latency
Full-jitter backoff, 6 attempts44 / 484554.3 msSimilar success rate, 37 ms less wall time, no lockstep herds
Table 6: 48 contended transactions. Retrying took the failure rate from 81% to 6-8% and made the median request roughly seven times slower – the numbers a capacity plan needs.

Read Table 6 honestly: Jitter did not win on success rate here, and pretending otherwise would be a lie. It won on wall time by spreading wakes that a fixed delay synchronises. The real lesson is the row above it: retries are a latency budget, not a fix. If two thirds of your write traffic needs a retry, the transaction is too long, the rows are too hot, or you are not using SKIP LOCKED where the work is queue-like.

Retry only what the database says is retryable

A retry wrapper that catches DBAPIError and replays it will replay a unique violation until the attempt limit, adding load to a database that is telling you the answer is no. PostgreSQL puts the answer in the SQLSTATE, which asyncpg surfaces as exc.orig.sqlstate on the wrapped driver exception. Two values mean an entire transaction may be replayed: 40001 (serialization failure) and 40P01 (deadlock detected). Everything else is a decision.

import asyncio
import random
from collections.abc import Awaitable, Callable
from typing import TypeVar
from sqlalchemy.exc import DBAPIError
T = TypeVar("T")
RETRYABLE_SQLSTATES = frozenset({"40001", "40P01"})
RANDOM = random.Random()


def sqlstate_of(exc: BaseException) -> str | None:
    """PostgreSQL puts the SQLSTATE on the driver exception, not on the wrapper."""
    return getattr(getattr(exc, "orig", None), "sqlstate", None)


def is_retryable(exc: BaseException) -> bool:
    """40001 serialization_failure and 40P01 deadlock_detected are safe to replay."""
    return sqlstate_of(exc) in RETRYABLE_SQLSTATES


def jittered_delay(attempt: int, base: float = 0.05, cap: float = 0.8) -> float:
    """Full jitter: uniform(0, min(cap, base * 2**attempt)) breaks retry lockstep."""
    return RANDOM.uniform(0.0, min(cap, base * (2**attempt)))


async def with_retry(
    operation: Callable[[], Awaitable[T]],
    attempts: int = 5,
    base: float = 0.05,
    cap: float = 0.8,
) -> T:
    """Replay a whole unit of work; the unit must be idempotent by construction."""
    for attempt in range(attempts):
        try:
            return await operation()
        except DBAPIError as exc:
            if not is_retryable(exc) or attempt == attempts - 1:
                raise
            await asyncio.sleep(jittered_delay(attempt, base, cap))
    raise RuntimeError("unreachable")

The classifier was exercised against asyncpg exceptions carrying their real SQLSTATE codes. The matrix below is measured output from running it, not a claim about the documentation:

SQLSTATEMeaningRetryable by this policyWhy
40P01deadlock_detectedyesThe server already rolled the transaction back; replay is safe if the unit is idempotent
40001serialization_failureyesREPEATABLE READ or SERIALIZABLE lost the race; replay with fresh reads
23505unique_violationnoA constraint decided; replaying produces the same violation and more load
57014query_cancelednoStatement timeout or an explicit cancel: the query is too expensive, not unlucky
08006connection_failurenoThe connection is gone and the transaction state is unknown; this needs its own policy
Table 7: Classification measured by feeding constructed driver exceptions through is_retryable(). Executing the deadlock itself requires a PostgreSQL server, which this sandbox did not have.

The retry loop itself was measured with a synthetic deadlock sequence: four calls, three rejections, delays of 7.03, 34.19 and 14.63 ms, success 58.7 ms after the first attempt. A unique violation, by contrast, left the wrapper after exactly one call – DBAPIError(sqlstate=23505) after 1 call.

Preventing the cycle instead of surviving it

In PostgreSQL a lock-order cycle needs two transactions that acquire the same two rows in opposite order. The fix is not clever, it is boring: acquire in a deterministic order (ORDER BY id) and keep the transaction short. Everything else in this list is supporting cast.

from __future__ import annotations

from collections.abc import Callable

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker

from models import Account
from retryable import with_retry


async def transfer(session: AsyncSession, source_id: int, target_id: int, amount: int) -> None:
    """Lock both rows in ascending id order so no lock cycle can form.

    The unit is idempotent when the caller inserts its transfer row under a
    client-generated idempotency key and the unique index rejects a replay.
    """
    first, second = sorted((source_id, target_id))
    rows = {
        account.id: account
        for account in (
            await session.execute(
                select(Account)
                .where(Account.id.in_([first, second]))
                .order_by(Account.id)
                .with_for_update()
            )
        ).scalars()
    }
    if len(rows) != 2:
        raise ValueError("both accounts must exist before a transfer can lock them")
    rows[source_id].balance -= amount
    rows[target_id].balance += amount


async def transfer_with_retry(
    maker: async_sessionmaker[AsyncSession],
    source_id: int,
    target_id: int,
    amount: int,
) -> None:
    """One transaction per attempt: a retry must not reuse a poisoned session."""

    async def unit_of_work() -> None:
        async with maker() as session:
            async with session.begin():
                await transfer(session, source_id, target_id, amount)

    await with_retry(unit_of_work)


async def instrumented(
    maker: async_sessionmaker[AsyncSession],
    hook: Callable[[int], None],
    source_id: int,
    target_id: int,
    amount: int,
) -> None:
    """Same unit of work, with a hook that lets the probe inject a failure."""

    async def unit_of_work() -> None:
        async with maker() as session:
            async with session.begin():
                hook(1)
                await transfer(session, source_id, target_id, amount)

    await with_retry(unit_of_work, attempts=4, base=0.01, cap=0.05)

The transfer unit of work at the end of section 5 was executed too, not just parsed: a plain transfer took 2 statements, moved the balance once, and a replayed 40P01 on the first attempt completed on the second attempt in 29.5 ms with the balance still moved exactly once – because the retry re-ran the transaction rather than the statement.

The retry boundary is the transaction: A retry must replay the transaction, not the statement. Replaying a single UPDATE after 40P01 runs it on a transaction the server already aborted, and every later statement fails with 25P02 (current transaction is aborted). That is why the unit of work above creates its own session and its own begin() inside the retried callable.

Three more habits prevent most of these incidents without any retry code. Keep user-interaction time out of transactions – a handler that waits for an external HTTP call while holding row locks is a deadlock generator. Bound lock waits with lock_timeout below statement_timeout, so a lock wait fails with a clear error instead of consuming the statement budget. And for queue-like tables, take work with SELECT ... FOR UPDATE SKIP LOCKED so that workers never wait on each other at all.

6. The Production Program, Module by Module

The rest of this article is one small, auditable program: seven modules that make the four failure modes either impossible or obvious. They are shown as they were executed, with the measured statement counts stated next to the queries that produced them.

Module 1: the baseline models, and the hardening they invite

Every probe in this article ran against these models, and they are deliberately the baseline: each relationship is lazy="select", the library default, so the failures in sections 2 and 3 reproduce exactly as they do in an untouched service. The hardening from rung 4 is a one-word change per relationship – lazy="raise" – and it belongs in the same commit as the repository functions that load those relationships eagerly. Ship the baseline first; flip the default once the repositories are the only code that touches a relationship. The guard itself costs 0.03 ms and names the attribute it caught.

from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, Index, String, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship


class Base(DeclarativeBase):
    pass


class Author(Base):
    __tablename__ = "authors"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(120), nullable=False)
    handle: Mapped[str] = mapped_column(String(60), nullable=False, unique=True)

    articles: Mapped[list["Article"]] = relationship(
        back_populates="author",
        cascade="save-update, merge",
        lazy="select",
    )


class Article(Base):
    __tablename__ = "articles"

    id: Mapped[int] = mapped_column(primary_key=True)
    author_id: Mapped[int] = mapped_column(
        ForeignKey("authors.id", ondelete="CASCADE"), index=True, nullable=False
    )
    title: Mapped[str] = mapped_column(String(200), nullable=False)
    slug: Mapped[str] = mapped_column(String(200), nullable=False, unique=True)
    views: Mapped[int] = mapped_column(default=0, nullable=False)
    published_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), nullable=False
    )

    author: Mapped[Author] = relationship(back_populates="articles", lazy="select")
    comments: Mapped[list["Comment"]] = relationship(
        back_populates="article",
        cascade="all, delete-orphan",
        lazy="select",
    )

    __table_args__ = (Index("ix_articles_published_views", "published_at", "views"),)


class Comment(Base):
    __tablename__ = "comments"

    id: Mapped[int] = mapped_column(primary_key=True)
    article_id: Mapped[int] = mapped_column(
        ForeignKey("articles.id", ondelete="CASCADE"), index=True, nullable=False
    )
    body: Mapped[str] = mapped_column(String(500), nullable=False)

    article: Mapped[Article] = relationship(back_populates="comments", lazy="select")


class Account(Base):
    __tablename__ = "accounts"

    id: Mapped[int] = mapped_column(primary_key=True)
    code: Mapped[str] = mapped_column(String(40), nullable=False, unique=True)
    balance: Mapped[int] = mapped_column(default=0, nullable=False)

Module 2: settings that refuse impossible arithmetic

from __future__ import annotations

import os
from dataclasses import dataclass, field


def _int(name: str, default: int) -> int:
    return int(os.environ.get(name, default))


@dataclass(frozen=True, slots=True)
class DatabaseSettings:
    url: str
    pool_size: int = 10
    max_overflow: int = 0
    pool_timeout: float = 3.0
    pool_recycle: int = 900
    pool_pre_ping: bool = True
    pool_use_lifo: bool = True
    statement_timeout_ms: int = 5_000
    pods: int = 1                          # the HPA ceiling, not today's replica count
    workers: int = 1
    server_max_connections: int = 100
    reserved_connections: int = 10

    @property
    def per_process_ceiling(self) -> int:
        return self.pool_size + self.max_overflow

    @property
    def fleet_demand(self) -> int:
        """Every process of every replica opens its own ceiling: pods x workers x ceiling."""
        return self.pods * self.workers * self.per_process_ceiling

    def validate(self) -> None:
        if self.pods < 1:
            raise ValueError("pods must be at least 1 (use the autoscaler's ceiling, not today's count)")
        if self.pool_size < 1:
            raise ValueError("pool_size must be at least 1")
        if self.max_overflow < 0:
            raise ValueError("max_overflow must not be negative")
        if self.pool_timeout <= 0:
            raise ValueError("pool_timeout must be positive: a zero timeout turns backpressure into errors")
        if self.pool_timeout > 10:
            raise ValueError("pool_timeout above 10s hides saturation until request deadlines fire")
        if self.statement_timeout_ms < 100:
            raise ValueError("statement_timeout_ms below 100ms cancels healthy queries")
        budget = self.server_max_connections - self.reserved_connections
        if self.fleet_demand > budget:
            raise ValueError(
                f"pool budget exceeded: {self.pods} pods x {self.workers} workers x "
                f"{self.per_process_ceiling} = {self.fleet_demand} connections, but only "
                f"{budget} are available after reserving {self.reserved_connections}"
            )
        if self.pool_recycle * 2 < self.statement_timeout_ms / 1000:
            raise ValueError("pool_recycle is far shorter than the statement timeout")

    @classmethod
    def from_env(cls) -> "DatabaseSettings":
        settings = cls(
            url=os.environ.get("DATABASE_URL", "sqlite+aiosqlite:///./app.db"),
            pool_size=_int("DB_POOL_SIZE", 10),
            max_overflow=_int("DB_MAX_OVERFLOW", 0),
            pool_timeout=float(os.environ.get("DB_POOL_TIMEOUT", "3.0")),
            pool_recycle=_int("DB_POOL_RECYCLE", 900),
            pool_pre_ping=os.environ.get("DB_POOL_PRE_PING", "1") == "1",
            pool_use_lifo=os.environ.get("DB_POOL_USE_LIFO", "1") == "1",
            statement_timeout_ms=_int("DB_STATEMENT_TIMEOUT_MS", 5_000),
            pods=_int("POD_REPLICAS", 1),
            workers=_int("WEB_CONCURRENCY", 1),
            server_max_connections=_int("DB_SERVER_MAX_CONNECTIONS", 100),
            reserved_connections=_int("DB_RESERVED_CONNECTIONS", 10),
        )
        settings.validate()
        return settings

Measured: two pods of four workers with a ceiling of 8 per process (2 x 4 x 8 = 64 against a budget of 85) validates. The same fleet with 20 + 10 per process is rejected before boot with pool budget exceeded: 2 pods x 4 workers x 30 = 240 connections, but only 85 are available after reserving 15; the hard part is the third case – the same 8-per-process configuration, accepted at two pods, is rejected at the autoscaler’s ceiling of six (6 pods x 4 workers x 8 = 192), which is the failure a per-process check never sees. A zero pool timeout is rejected with a message that explains the consequence rather than the constraint.

Module 3: statement telemetry you can read from a health endpoint

from __future__ import annotations

import statistics
import time
from collections import deque
from typing import Any

from sqlalchemy import event
from sqlalchemy.ext.asyncio import AsyncEngine


class StatementTelemetry:
    """Attach to an engine once; read it from a health endpoint or a log line."""

    def __init__(self, engine: AsyncEngine, window: int = 512, slow_ms: float = 50.0) -> None:
        self._engine = engine
        self._window = window
        self._slow_ms = slow_ms
        self._latencies: deque[float] = deque(maxlen=window)
        self._slow: deque[tuple[str, float]] = deque(maxlen=20)
        self._count = 0
        self._started: dict[int, float] = {}
        self._listener_start = self._before
        self._listener_end = self._after
        event.listen(engine.sync_engine, "before_cursor_execute", self._listener_start)
        event.listen(engine.sync_engine, "after_cursor_execute", self._listener_end)

    def detach(self) -> None:
        event.remove(self._engine.sync_engine, "before_cursor_execute", self._listener_start)
        event.remove(self._engine.sync_engine, "after_cursor_execute", self._listener_end)

    def _before(self, conn: Any, cursor: Any, statement: str, parameters: Any, context: Any, executemany: bool) -> None:
        self._started[id(cursor)] = time.perf_counter()

    def _after(self, conn: Any, cursor: Any, statement: str, parameters: Any, context: Any, executemany: bool) -> None:
        started = self._started.pop(id(cursor), None)
        if started is None:
            return
        elapsed = (time.perf_counter() - started) * 1000.0
        self._count += 1
        self._latencies.append(elapsed)
        if elapsed >= self._slow_ms:
            self._slow.append((" ".join(statement.split())[:160], round(elapsed, 1)))

    def snapshot(self) -> dict[str, Any]:
        latencies = sorted(self._latencies)
        if not latencies:
            return {"statements": 0, "p50_ms": 0.0, "p95_ms": 0.0, "max_ms": 0.0, "slow": []}
        p95 = latencies[min(len(latencies) - 1, int(0.95 * (len(latencies) - 1)))]
        return {
            "statements": self._count,
            "p50_ms": round(statistics.median(latencies), 2),
            "p95_ms": round(p95, 2),
            "max_ms": round(latencies[-1], 2),
            "slow": list(self._slow),
        }

The listener records every statement, the p50/p95/max latency in a rolling window, and the twenty slowest statements with their first 160 characters. In the integration run it counted 6 statements across the repository calls, p50 0.6 ms, p95 0.71 ms, max 3.29 ms. On a real service the same numbers, exported per route, are the difference between “the API is slow” and “this endpoint runs 121 statements”.

Module 4: one engine, one pool, one deadline policy

Section 4 already showed build_engine(), build_sessionmaker() and session_scope(); the important line is that the pool would not exist at all if the arithmetic did not validate. The engine is created once per process, in the lifespan handler, and stored on app.state – not per request, and never per call.

Module 5: two request dependencies, one per intent, and a deadline the handler owns

A single session dependency cannot serve a read route and a write route honestly. The read path rolls back on the way out, the write path commits exactly once, and naming each after its intent makes a route that writes through the read path a visible mistake in review. The measured caveat matters more than the naming: the read path is a rollback, not a permission check. A write issued on it returned 200 and was never committed – the next request counted 0 rows, and nothing raised. If the endpoint must be unable to write, the guarantee has to come from the database: a role without write grants, a read replica, or postgresql_readonly=True in the execution options, which makes the server reject the statement instead of the scope discarding it.

import asyncio
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import Depends, Request
from sqlalchemy.ext.asyncio import AsyncSession
from db import session_scope
REQUEST_DEADLINE_SECONDS = 2.5


async def get_read_session(request: Request) -> AsyncIterator[AsyncSession]:
    """Read intent: the scope rolls back instead of committing on the way out.

    The flag names the exit path; it does not forbid writes. A write issued on
    this session is discarded by the rollback rather than rejected, so a
    read-only guarantee has to come from the database: a role without write
    grants, a replica, or ``postgresql_readonly=True`` in the execution options.
    """
    async with session_scope(request.app.state.sessionmaker, readonly=True) as session:
        yield session


async def get_write_session(request: Request) -> AsyncIterator[AsyncSession]:
    """Write intent: exactly one commit on success, rollback on every other path."""
    async with session_scope(request.app.state.sessionmaker, readonly=False) as session:
        yield session


@asynccontextmanager
async def request_deadline(seconds: float = REQUEST_DEADLINE_SECONDS) -> AsyncIterator[None]:
    """Bound how long the caller waits for one unit of work.

    Used inside the handler, around the repository call, so the timeout can only
    reach code it was meant to bound and its expiry is an ordinary exception the
    handler can translate. It still does not cancel a statement the server is
    already executing - statement_timeout does that.
    """
    async with asyncio.timeout(seconds):
        yield


ReadSessionDep = Depends(get_read_session)
WriteSessionDep = Depends(get_write_session)

The deadline is not inside the dependencies, and that is a deliberate retreat from a common pattern. Wrapping the yield in asyncio.timeout() looks tidier, but the timeout is then armed for the whole request and its expiry is raised from the dependency’s exit code, which FastAPI’s exception handlers never see. Measured on the same 0.2 s handler with a 50 ms deadline: a deadline around the call site returned a 504 with a JSON body at 51.7 ms; the same deadline around the yield returned a bare 500 at 51.7 ms, and with application exceptions surfaced the raw TimeoutError came out of the ASGI stack. The difference is not the deadline, it is who catches the expiry.

The exit path is worse than the error path. In the sandbox’s write route, the commit had already returned and only the exit outlived the deadline: the client received 200 at 51.7 ms, the row was committed, and the TimeoutError landed in code no handler owns – visible only in server logs. A deadline that cannot be mapped to a response is a log line, not a policy. Keep it where it can be translated, and keep the server-side statement_timeout as the only thing that stops the database from working after the client left.

Two deadlines, two owners: request_deadline() bounds how long the handler waits for a unit of work, and its TimeoutError is the route’s to translate. The server-side statement_timeout set in build_engine() is what actually interrupts a running query – the sandbox measured a 50 ms client deadline returning after 776.8 ms because the driver was not at an await boundary. Ship both, and know which one the pager is about.

Module 6: readiness that exposes pool arithmetic

from typing import Any
from fastapi import APIRouter, Request
from sqlalchemy import text
from db import session_scope
router = APIRouter()


@router.get("/healthz")
async def healthz(request: Request) -> dict[str, Any]:
    """Liveness: the process can answer, no database round trip."""
    return {"status": "ok"}


@router.get("/readyz")
async def readyz(request: Request) -> dict[str, Any]:
    """Readiness: the pool has a free slot, and one cheap query succeeds."""
    engine = request.app.state.engine
    pool = engine.pool
    snapshot = {
        "pool_size": pool.size(),
        "checked_out": pool.checkedout(),
        "overflow": pool.overflow(),
        "status": pool.status(),
    }
    async with session_scope(request.app.state.sessionmaker, readonly=True) as session:
        await session.execute(text("SELECT 1"))
    snapshot["database"] = "reachable"
    snapshot["telemetry"] = request.app.state.telemetry.snapshot()
    return snapshot

Liveness has no database round trip, so a database incident does not restart every pod. Readiness reports the pool’s own counters – size, checkedout, overflow – and the telemetry snapshot, which is what an operator actually needs when requests start timing out: is the pool exhausted, or is the database slow? In the sandbox run the readiness view reported checked_out: 0 and the telemetry block above after the repository calls, which is the shape of a healthy service right before a load test.

Module 7: the repository is the only place that knows about loading

Section 3 showed the repository in full. Keeping loader choices there has a second benefit beyond N+1: the query count of a page becomes a code review artefact. A route that adds a relationship to a response has to change a repository function, where a reviewer sees selectinload, joinedload or an aggregate and can ask which one it should be.

7. Verification: Environment, Method and Raw Measurements

ComponentVersion / specification
Python3.12.16
SQLAlchemy2.0.57 (async ORM, AsyncSession, async_sessionmaker)
Driver (measurements)aiosqlite 0.22.1 over SQLite 3.46.1, WAL journal mode
Driver (imported, not connected)asyncpg 0.32.0 – SQLSTATE objects used for the classifier
ASGI stack (probe 8)FastAPI 0.162.7, Starlette 1.10.0, httpx 0.28.1 ASGITransport – the request runs in the client’s task, so an exception in a dependency’s exit code is what the caller sees
greenlet3.5.6
HostLinux 6.12.8, 2 vCPU, 1,486 MB RAM, no PostgreSQL server available
MethodEach probe builds its own database file and engine, executes the scenario, and prints JSON; statement counts come from a before_cursor_execute listener on the engine, not from log parsing
RepetitionLatency figures are medians of 5 runs (retry ladders: medians of 3), single host, no warm-up discarded
Table 8: The verification environment. Everything in this article’s tables was produced here.

Eight probes were run, all from the same sandbox: probe_missing_greenlet.py (seven cases, including the exception hierarchy), probe_n_plus_one.py (six strategies over 120 / 960 / 1,920 rows), probe_pool.py (saturation, leak, implicit transaction, pre-ping), probe_locks.py (three lock deadlines, three retry policies, SQLSTATE matrix), probe_deadline.py (query cost and client-cancel behaviour), probe_app.py (the application modules themselves), probe_transfer.py (the lock-ordered transfer with a replayed deadlock) and probe_deps.py (the request dependencies, the read/write split and two placements of the same deadline, driven through an ASGI transport).

What was measured, and what was not

Honesty about scope is part of the method. These results are measured: the MissingGreenlet and DetachedInstanceError behaviour, statement counts per loading strategy, pool queueing and timeout behaviour, the permanence of a leaked slot, the cost of pool_pre_ping, lock waits under three deadlines, retry policy outcomes, client-side deadline behaviour, and the difference between a deadline around a dependency’s yield and one around the call it was meant to bound. These are documented PostgreSQL semantics rather than measurements, because the sandbox had no server: deadlock detection at deadlock_timeout, the 40P01 victim selection, statement_timeout, lock_timeout and idle_in_transaction_session_timeout. The SQLSTATE classifier and the retry loop were executed against asyncpg exception objects carrying real SQLSTATE values, which tests the code path but not the server’s behaviour.

Two numbers in this article are deliberately not single-run impressions. The retry ladder is a median of three runs of 48 transactions, because a single run varied between 43 and 46 commits. The pre-ping overhead is quoted as both median and p95, because a single median hides the checkout that pays a full round trip after an idle period. The sub-millisecond exception timings are single-shot and move by about +/-0.1 ms between runs; they are quoted to show that the failure costs no query at all, not to rank one exception against another.

The whole picture in one table

Failure modeSymptom in productionMeasured costFirst fix
Expired attribute readMissingGreenlet in a serializer1.07 ms, no queryexpire_on_commit=False, build the DTO inside the session
Lazy relationshipMissingGreenlet, or 121 statements81.97 ms for a pageselectinload() / joinedload() in the repository
Leaked sessionpool TimeoutError, then everything fails1,001.7 ms per requestsession_scope() with commit/rollback/close in finally
Hot-row contentiondeadlock aborts, retries, 5xx9 of 48 committed with no retryDeterministic lock order, short transactions, retry only 40001/40P01
Table 9: The four failures, their measured cost, and the one change that removes each.

8. Diagnosis Playbook for the Four Symptoms

The value of measuring all four failures in one place is that they can be told apart from the outside. Each row below is a symptom an operator can see, the evidence that separates it from its lookalikes, and the change that resolves it.

SymptomEvidence to collect before changing codeAction
MissingGreenlet on a readThe traceback’s last frame is _concurrency_py3k.py; the statement log shows no SELECT for that attribute at the moment of failure; the object was committed or the session was closedSet expire_on_commit=False for the request session, load the attribute explicitly, and build the response object inside the session
p95 rises with page size, statement count per request rises with row countStatements per request in telemetry; requests with 40 rows emitting 41 statements; run_sync() or an awaited query inside a loop in the serializerReplace with selectinload() (collection) or joinedload() (many-to-one), aggregate counts in SQL, add raiseload() to catch regressions
Pool TimeoutError, then requests fail even though the database is healthypool.status() showing every slot checked out while the server shows idle connections; a handler that can raise between checkout and closeRoute every session through session_scope(); check that no exception path skips it; verify with a fault-injection run that checkedout returns to 0
Deadlock aborts or repeated lock waits during traffic spikes40P01 in the logs with the statement that lost; the two statements touching the same rows in different orders; transaction duration including external callsOrder the locks, shorten the transaction, set lock_timeout below statement_timeout, and retry the whole transaction with jitter
Requests that time out on the client but complete on the serverServer logs showing the query finishing after the client deadline; no error on the database sideSet statement_timeout (and command_timeout for asyncpg); a client deadline alone does not cancel work
Table 10: Symptom, evidence, action. The middle column is the one teams skip.

The first measurement to take: Before touching the ORM, count statements. Almost every one of these incidents is decided by a single question that the before_cursor_execute listener from Module 3 answers in one line: how many statements did this request send? A page that sends 121 has an N+1; a page that sends 2 and is still slow has a database problem, and no amount of selectinload will help.

9. Production FAQ

Q: Why does MissingGreenlet appear only in production and never in tests?

Because the failing path needs a commit, an expiry, and a read in that order, and tests rarely reproduce all three against the same object. A unit test that builds an object and serializes it in memory never expires an attribute; a test with expire_on_commit=False configured globally, or with the session still open, hides the read. The sandbox reproduces it in 1.07 ms with three lines – create, commit, read – and that reproduction is worth keeping as a regression test, because the fix is one session option away from being undone by a well-meaning change to session defaults.

Q: Should every relationship use selectinload?

No. Use selectinload() for one-to-many collections that you will actually consume: it emits one batched IN statement per 500 identifiers and keeps the parent rows clean. Use joinedload() for many-to-one, where the join cannot duplicate parent rows and one statement is strictly better. Avoid joinedload() on collections that feed a LIMIT or a paginated page, because the join multiplies rows before the limit applies; in the sandbox the joined collection produced 960 driver rows for 120 objects. And do not eager load a relationship the response never reads – the query cost is real even when the payload does not change.

Q: How do I choose pool_size and pool_timeout?

From arithmetic, not from intuition. Start from the server’s max_connections, subtract what migrations, cron jobs, monitoring and a pooler need, then divide by the number of processes the fleet will run – replicas times workers per pod, counted at the autoscaler’s maximum rather than at today’s replica count. That quotient is the ceiling per process. Keep max_overflow at zero for a service that owns its database, because overflow is only a way to hide a pool that is too small. Then set pool_timeout so that queueing is visible: in the sandbox, a pool of 2 with a 1 s timeout turned 8 concurrent 300 ms requests into a 756.9 ms median, and 24 concurrent requests into 16 failures – information a 30 s default would have hidden inside the request deadlines.

Q: Is it safe to retry every database error?

It is not, and the distinction is cheap to implement. Retry only 40001 and 40P01, and only when the whole unit of work is idempotent – a retried unique violation (23505) is a decision, not bad luck, and a retried statement-timeout (57014) makes an expensive query expensive twice. In the sandbox, the classifier left a 23505 after exactly one call while replaying a 40P01 on the second attempt. Cap attempts, use full jitter, and remember that the retry boundary is the transaction: replaying an individual statement against an aborted transaction produces 25P02.

Q: Why did logging in a finally block raise MissingGreenlet?

Because the log line read an ORM attribute – an id, a name, a relationship – that was expired or unloaded, and the session was already closing, so there was no greenlet bridge and no connection. The exception then replaced the exception you were trying to handle, which is why these incidents look like a logging bug. Capture the values you need as plain Python objects when the session is open, and never touch an ORM attribute in cleanup code. The same rule applies to exception handlers, __del__, and background callbacks scheduled from inside a request.

10. Conclusion: Loading Is a Design Decision, Not an Implementation Detail

All four failures come from the same misplaced assumption: that the ORM will fetch what is needed when it is needed. In a synchronous application that assumption costs a query. In an asynchronous one it either raises MissingGreenlet or silently multiplies round trips, and in both cases the bill arrives somewhere else – an error in a serializer, a p95 chart, an exhausted pool, a database whose lock table is full at 3 a.m.

The program in this article is small: typed settings that refuse impossible pool arithmetic, an engine built once with server-side timeouts, a session scope that cannot leak, a repository that declares its loading, a retry policy that reads SQLSTATE, and two health endpoints that report the pool and the statement latency. None of it is clever. All of it is testable, and every number in this article is the output of running it.

To go deeper on the layers around this one, read the companion runbooks: asyncio concurrency in Python for the event-loop mechanics behind the greenlet bridge, PostgreSQL slow query optimization for what to do once a connection is checked out and the query is the problem, Redis caching and distributed locks for the contention that does not live in the database, and Celery production architecture for moving long transactions out of the request path entirely.

Related production runbooks: FastAPI on Gunicorn and UvicornWorker for the process model that hosts this session factory, Docker multi-stage builds for Python for the image that ships it, and Kubernetes pod tuning and OOMKilled defense for the cluster that restarts it.

Download the AI Prompt Master Pack for Engineers ($0+ Pay What You Want), with curated prompts for loader reviews, pool budget calculations and incident postmortems: Get the AI Prompt Master Pack on Gumroad →

Subscribe to the TechBobby Substack for one measured production runbook a week: runtime internals, database scaling, and the deployment mechanics that decide whether your p99 survives a Tuesday.

Written by TechBobby Engineering – an independent engineer publishing measured Python production runbooks. Every figure in this article came from a probe executed in the same sandbox: Python 3.12.16, SQLAlchemy 2.0.57, aiosqlite 0.22.1 over SQLite 3.46.1, greenlet 3.5.6, two vCPUs and 1,486 MB of RAM. The conclusions that need PostgreSQL itself – row-lock deadlock detection, statement_timeout, idle_in_transaction_session_timeout – were checked against the server’s documentation rather than measured here, and section 7 lists the environment and the eight probes so the numbers can be re-run.


Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.