← Back to FastAPI, page 5

fastapi-0094 · Hard senior

How do you size database connection pools for a FastAPI deployment with several workers, and how does dependency scope affect connection hold time?

Each worker process has its own pool, so total possible connections are workers x replicas x (pool_size + max_overflow) and must stay below the database's max_connections with room for admin and migration sessions. Keep pool_size modest, set pool_timeout so overload fails fast, use pool_pre_ping and pool_recycle, and release connections early: FastAPI dependencies with yield can use scope="function" so the session closes before the response is sent instead of after it.

Full answer

Capacity formula:

max connections used = replicas x workers per replica x (pool_size + max_overflow)

Example: 4 pods x 4 workers x (5 + 5) = 160 possible connections. PostgreSQL's default max_connections is 100, and each connection costs memory (several MB), so this would fail under load. Options: smaller pools, fewer workers, a pooler such as PgBouncer (transaction pooling) between app and database, or a bigger database.

Sizing guidance:

  • Async apps need fewer connections than you think: concurrency is high but most time is spent waiting on I/O in other places. A pool of 5 to 20 per process serves hundreds of concurrent requests if each holds a connection briefly.
  • pool_size: steady connections kept open. max_overflow: temporary extras closed when returned. pool_timeout: how long a request waits for a connection before raising TimeoutError (set it low, e.g. 5 s, so overload becomes fast 503s rather than a pile-up). pool_recycle: replace connections older than N seconds (below firewall or server idle timeouts). pool_pre_ping=True: test connections on checkout to survive restarts and failovers.
  • Little's law: needed connections is about requests per second x average connection hold time. Halving hold time halves the need.
  • Reduce hold time: do not call slow external APIs while holding a session, keep transactions short, avoid lazy N+1 loops, and release early.

Dependency scope (FastAPI 0.121+): by default a yield dependency's exit code runs after the response is sent (scope="request"). A session dependency declared with Depends(get_db, scope="function") exits right after the path function returns, before the response is serialised and sent, so the connection returns to the pool sooner. Use scope="function" for sessions when the response body does not need an open session (all data loaded), and keep the default if streaming responses read from the session.

Monitor: pool checked-out gauge, wait time, pg_stat_activity counts by application name, and errors from pool timeouts. Load test with realistic concurrency before choosing numbers.

python
import asyncio
import sqlite3
import tempfile
from pathlib import Path
from typing import Annotated

from fastapi import Depends, FastAPI
from sqlalchemy import create_engine
from sqlalchemy.exc import TimeoutError as PoolTimeout
from sqlalchemy.pool import QueuePool

path = Path(tempfile.mkdtemp()) / "pool.db"
sqlite3.connect(path).close()
engine = create_engine(f"sqlite:///{path}", poolclass=QueuePool, pool_size=2, max_overflow=1, pool_timeout=0.2, pool_pre_ping=True)

held = [engine.connect() for _ in range(3)]            # 2 pooled + 1 overflow
print("checked out:", engine.pool.checkedout(), "of", engine.pool.size() + 1)
try:
    engine.connect()
except PoolTimeout as exc:
    print("fourth caller:", type(exc).__name__, str(exc).split(" (")[0])
for conn in held:
    conn.close()
print("after release:", engine.pool.checkedout())
print("worst case for 4 pods x 4 workers:", 4 * 4 * (2 + 1), "connections")

events = []


def get_session():
    events.append("session opened")
    yield "session"
    events.append("session closed")


app = FastAPI()


@app.get("/default")
async def default(s: Annotated[str, Depends(get_session)]):
    events.append("handler done")
    return {"ok": True}


@app.get("/early")
async def early(s: Annotated[str, Depends(get_session, scope="function")]):
    events.append("handler done")
    return {"ok": True}


async def call(path):
    scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http",
             "path": path, "raw_path": path.encode(), "query_string": b"", "headers": [], "server": ("t", 80),
             "client": ("127.0.0.1", 1), "root_path": ""}

    async def receive():
        return {"type": "http.request", "body": b"", "more_body": False}

    async def send(message):
        if message["type"] == "http.response.body":
            events.append("response sent")

    await app(scope, receive, send)


for p in ("/default", "/early"):
    events.clear()
    asyncio.run(call(p))
    print(p, events)

Standalone script. Run it with `python file.py`; it uses a temporary SQLite file for the pool and drives the ASGI app directly. The scope option on Depends needs a recent FastAPI (0.121 or later). Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): checked out: 3 of 3 fourth caller: TimeoutError QueuePool limit of size 2 overflow 1 reached, connection timed out, timeout 0.20 after release: 0 worst case for 4 pods x 4 workers: 48 connections /default ['session opened', 'handler done', 'response sent', 'session closed'] /early ['session opened', 'handler done', 'session closed', 'response sent']

Key points

  • Total connections = replicas x workers x (pool_size + max_overflow)
  • Stay below max_connections or add PgBouncer
  • Low pool_timeout turns overload into fast failures
  • Hold time drives need: keep transactions short and avoid external calls
  • scope='function' releases the session before the response is sent

Common mistakes

  • Setting pool sizes per process without multiplying by workers and replicas
  • Holding a session open while calling external APIs
  • Very large pools that overload the database
  • No pool_timeout, so overload turns into long hangs
  • Not using pre_ping or recycle behind load balancers that drop idle connections

Follow-ups

  • When would you add PgBouncer, and which pooling mode?
  • How do you detect connection leaks?
  • How does async change pool sizing?

Tips

  • State the formula
  • Mention pool_timeout and pre_ping
  • Mention early release