Skip to content

FastAPI sync endpoints + SQLAlchemy QueuePool deadlock for pool_timeout once in-flight requests exceed threads + pool

FastAPI 0.135.1 / Starlette 0.52.1 / anyio 4.12.1 / SQLAlchemy 2.0.48, gunicorn + uvicorn workers. Sync (def) endpoints get a request-scoped Session from a dependency; an ASGI middleware commits and closes it with anyio.to_thread.run_sync(session.commit) when the response starts. Engine is QueuePool(pool_size=5, max_overflow=10), default pool_timeout=30. Under a short burst of cheap read requests (about 8ms each, under 1ms in the database, no N+1), the service returns clumps of 500s exactly 30s after arrival with sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30.00, and successful responses also arrive in clumps separated by silent gaps. Pool gauges sampled before and after read 0 checked out. Assumed slow queries or a missing index first; EXPLAIN and timing showed nothing. Then tried the commonly recommended fix of capping the anyio default thread limiter to the pool size (15 tokens), which made it worse.

1 solution
ranked by outcome — not votes
Accepted

Root cause: the connection is held across threadpool hops, so the threadpool and the pool deadlock each other. For a sync endpoint with a response_model:

  1. the handler runs in an anyio default-limiter thread (40 tokens) and checks out a connection on first query;
  2. the handler returns but the Session keeps the connection;
  3. FastAPI validates the response in another default-limiter thread (serialize_response -> run_in_threadpool(field.validate, ...) for non-coroutine endpoints);
  4. the middleware's commit (what actually returns the connection) needs another default-limiter thread.

The limiter is FIFO. Once more than threads + pool requests are in flight in one worker (40 + 15 = 55 here), freed threads go to queued handler starts, which block in pool checkout. End state: all 40 threads are handlers waiting for a connection, and the 15 connection holders are queued for a thread. Nothing moves until pool_timeout fires, then it can repeat for the backlog.

Reproduction (real middleware, 20ms handler, pool_timeout=3, N concurrent requests via httpx.ASGITransport):

default (40 threads, pool 15) 40 40 0 0.08s
default 55 43 12 3.07s
default 100 32 68 6.10s
threads capped to 15 100 25 75 15.09s
threads raised to 600 500 500 0 1.09s
async gate of 15 2000 2000 0 3.60s

Note the failure count just over the threshold is small (12 at N=55), so a round with only ~11 timeouts in one worker is still this deadlock.

Why capping threads to the pool size does not help: connections are held by requests, not threads. 15 requests can hold connections while owning no thread, while 15 new handlers take the threads and block on checkout.

Fix: admission control sized to the pool, taken on the event loop. Make the session dependency async and have it acquire an asyncio.Semaphore(pool_size + max_overflow) before returning the session; release it in the middleware's finally after close.

async def get_session(request: Request):
    state = request.scope.setdefault("state", {})
    gate = state.get("db_gate")
    if gate is not None and not state.get("db_gate_held"):
        try:
            await asyncio.wait_for(gate.acquire(), 10)
        except asyncio.TimeoutError:
            raise HTTPException(503, headers={"Retry-After": "1"})
        state["db_gate_held"] = True
    return request.state.session

Now at most pool-capacity requests are in the DB section, so a handler thread never blocks on checkout; waiters hold neither a thread nor a connection, and overload becomes a bounded queue plus a fast 503 instead of a 500 after 30s. An async dependency also removes one threadpool hop per request. asyncio.Semaphore (3.10+) binds its loop lazily, so it is safe to construct before gunicorn --preload forks. Raising the thread limit above the maximum possible in-flight count also avoids the deadlock but only moves the threshold.