When building high-throughput APIs in FastAPI, database connection exhaustion is one of the most common production failure modes. Under a sudden traffic surge, incoming asynchronous requests can spawn hundreds of database sessions simultaneously, quickly overwhelming connection pools like PostgreSQL or PgBouncer.
To address this, modern versions of FastAPI introduced a first-class concurrency limiter directly into Depends(): the max_concurrency parameter. On the surface, it seems as simple as adding Depends(get_session, max_concurrency=10) to protect your database.
However, when dependencies rely on multiple resources or execute nested sub-dependencies, subtle timing issues emerge. A single misconfiguration can cause your application to silently hang forever—deadlocking worker processes without throwing an error or logging a stack trace.
In this deep dive, we examine how FastAPI resolves dependency concurrency limits under the hood, how multi-resource dependencies trigger deadlocks, and the exact architectural patterns required to keep complex dependency graphs safe, resilient, and fast.
Key Definition (AI Extractable Summary):
In FastAPI,max_concurrencyonDepends()controls concurrent executions using an internal semaphore bound to the dependency instance. When a request requires multiple constrained resources, FastAPI executes sub-dependencies before acquiring the parent dependency’s limit. If resources are requested in inconsistent orders across endpoints, or if a single-concurrency dependency is invoked twice withuse_cache=False, circular wait conditions occur, causing complete request deadlocks.
Table of Contents
- Understanding
max_concurrencyinDepends() - How FastAPI Resolves Dependency Limits Under the Hood
- The Sub-Dependency Resolution Hazard
- Deadlock Mode 1: The Single-Request Self-Deadlock (Re-entrancy)
- Deadlock Mode 2: Cross-Resource Circular Wait (Dining Philosophers)
- Dependency Lifecycles:
scope="function"vsscope="request" - Worker Process Math: Sizing Concurrency for Production
- The 5 Architectural Rules to Avoid Deadlocks
- Full Production Example: Multi-Resource Pipeline Without Deadlocks
Understanding max_concurrency in Depends()
Every backend engineer has seen connection pool exhaustion errors like QueuePool limit of size 5 overflow 10 reached, connection timed out. Typically, engineers solve this by tuning SQLAlchemy pool sizes or deploying PgBouncer. But pool sizing only protects the database; it doesn’t protect the FastAPI application from saturating its own memory and event loop queue with unserviced sessions.
With max_concurrency, FastAPI lets you throttle access at the dependency level:
from typing import Annotated
from fastapi import Depends, FastAPI
from sqlmodel import Session
# Define a shared database session dependency with a concurrency limit of 5
SessionDep = Annotated[
Session,
Depends(get_session, max_concurrency=5)
]
app = FastAPI()
@app.get("/items")
async def read_items(session: SessionDep):
# Only 5 requests can execute with an active session simultaneously
return session.query(Item).all()
When 5 requests are currently using get_session, a 6th request arriving at /items is placed in a non-blocking wait queue. Crucially, because FastAPI handles this asynchronously, waiting requests do not block the event loop or consume OS threads.
How FastAPI Resolves Dependency Limits Under the Hood
To avoid bugs, you must understand the two core implementation rules of max_concurrency:
1. Limits Are Bound to the Depends Object Instance, Not the Function
FastAPI creates an internal asyncio.BoundedSemaphore tied to the specific Depends(...) instance. If you want routes to share the same concurrency budget, you must reuse the exact same dependency declaration—typically via Python’s Annotated type alias:
# ✅ SHARED LIMIT: Both routes share the same pool of 5 permits
SharedDBSession = Annotated[Session, Depends(get_session, max_concurrency=5)]
@app.get("/users")
async def list_users(db: SharedDBSession): ...
@app.get("/orders")
async def list_orders(db: SharedDBSession): ...
If you instantiate Depends separately inline on each route, each route gets its own distinct semaphore:
# ⚠️ SEPARATE LIMITS: Each route allows 5 concurrent sessions (10 total sessions possible)
@app.get("/users")
async def list_users(db: Session = Depends(get_session, max_concurrency=5)): ...
@app.get("/orders")
async def list_orders(db: Session = Depends(get_session, max_concurrency=5)): ...
2. Limits Are Isolated per Worker Process and Event Loop
FastAPI’s semaphores reside in memory within a single Python process. If you run Uvicorn with --workers 4, each worker process maintains its own independent semaphore. If max_concurrency=5, your application as a whole can hold up to $4 \times 5 = 20$ concurrent sessions across all workers.
The Sub-Dependency Resolution Hazard
Here is where complexity arises. According to the official FastAPI documentation:
“FastAPI runs a dependency’s sub-dependencies before applying that dependency’s limit.”
Consider an analytics dependency AnalyticsLogger that needs a database session:
async def get_analytics_service(
session: Annotated[Session, Depends(get_session, max_concurrency=5)]
):
return AnalyticsService(session=session)
# Parent dependency with its own limit
AnalyticsDep = Annotated[
AnalyticsService,
Depends(get_analytics_service, max_concurrency=2)
]
When a request reaches a route using AnalyticsDep:
- FastAPI resolves the sub-dependency
get_sessionfirst, acquiring one of the 5 database session permits. - Only after the sub-dependency is ready does FastAPI attempt to acquire the permit for
get_analytics_service(limited to 2).
If all 2 permits for get_analytics_service are busy, the request sits waiting—while already holding a database session permit!
If you place max_concurrency on a high-level composite dependency rather than on the low-level resource creator (get_session), waiting requests hold scarce underlying resources idle while blocked at the outer gate.
Request arrives ──> Acquires get_session permit (1/5)
└──> Tries to acquire Analytics permit (Full: 0/2)
└──> ⏳ WAITING (Holding DB session idle!)
Rule: Always place max_concurrency on the lowest-level dependency that directly instantiates or opens the scarce resource.
Deadlock Mode 1: The Single-Request Self-Deadlock (Re-entrancy)
A classic deadlock happens inside a single HTTP request when a dependency is invoked more than once with caching disabled (use_cache=False).
Consider an application where a session dependency has max_concurrency=1:
# Single concurrency limit for serialized transactions
StrictSession = Annotated[
Session,
Depends(get_session, max_concurrency=1, use_cache=False)
]
async def verify_user(session: StrictSession):
return session.get(User, 1)
@app.post("/transfer")
async def execute_transfer(
user: Annotated[User, Depends(verify_user)],
session: StrictSession
):
...
Here is the sequence of events during a single request:
- FastAPI resolves
verify_user. verify_userneedsStrictSession. The semaphore has 1 permit. It successfully acquires the permit and opens session #1.- Next, FastAPI moves to the route parameter
session: StrictSession. - Because
use_cache=Falseis set, FastAPI callsget_sessionagain instead of reusing session #1. - The semaphore limit is 1, and the permit is currently held by session #1.
- The second call pauses, waiting for session #1 to release its permit.
- But session #1 uses
yield, which only executes its teardown after the request completes. - The request cannot finish because it is waiting for session #2. Session #2 cannot start because session #1 won’t close.
The request freezes permanently until the client or load balancer times out.
The Fix
Never set use_cache=False on dependencies guarded by low max_concurrency limits unless you are certain the dependency is never evaluated multiple times in the same dependency tree. By default (use_cache=True), FastAPI reuses the already-resolved object without re-entering the semaphore.
Deadlock Mode 2: Cross-Resource Circular Wait (Dining Philosophers)
When an endpoint needs more than one limited resource—for example, a database session and a rate-limited external billing client—deadlocks can occur across concurrent requests.
FastAPI acquires dependency limits independently as it resolves parameters; it does not pre-reserve all required resources atomically.
Imagine two endpoints that require a Database Session (max_concurrency=2) and a Payment Gateway Client (max_concurrency=2):
# Resource A: Database Session
DbDep = Annotated[Session, Depends(get_db_session, max_concurrency=2)]
# Resource B: External Payment Lock
PaymentDep = Annotated[PaymentClient, Depends(get_payment_client, max_concurrency=2)]
Suppose Developer A writes Route 1:
@app.post("/checkout")
async def checkout(
db: DbDep, # 1. Acquires DB first
payment: PaymentDep # 2. Acquires Payment second
):
...
While Developer B writes Route 2:
@app.post("/refund")
async def refund(
payment: PaymentDep, # 1. Acquires Payment first
db: DbDep # 2. Acquires DB second
):
...
Under heavy concurrent load, the following race condition happens:
- Two requests hit
/checkout. Both acquire permits forDbDep. All 2 DB permits are now exhausted. - Simultaneously, two requests hit
/refund. Both acquire permits forPaymentDep. All 2 Payment permits are now exhausted. - The
/checkoutrequests now try to acquirePaymentDep. But all Payment permits are taken, so they wait. - The
/refundrequests now try to acquireDbDep. But all DB permits are taken, so they wait.
[Route 1 (/checkout)] holds DB ──────────> waiting for Payment (held by Route 2)
▲
│
[Route 2 (/refund)] holds Payment ─────> waiting for DB (held by Route 1)
This is the textbook circular wait condition. Both routes are stuck indefinitely. No errors are raised, CPU usage drops to near-zero, and the entire API stops responding to database and payment traffic.
Dependency Lifecycles: scope="function" vs scope="request"
In FastAPI, when a dependency uses yield, when does its cleanup code run?
By default (scope="request"), cleanup code executes after the response has been serialized and sent across the network socket.
async def get_db():
db = SessionLocal()
try:
yield db
finally:
# Runs AFTER the client has fully received the HTTP response!
db.close()
If your route streams a large response (e.g., streaming a file, server-sent events, or large JSON payloads), the database session—and its max_concurrency permit—remains locked for the entire duration of the transfer.
In FastAPI 0.115+, you can use scope="function" (when applicable) or explicitly close connections early so permits return to the pool the instant the route handler finishes, rather than waiting for client network I/O:
from fastapi import Request
async def get_fast_session():
session = SessionLocal()
try:
yield session
finally:
session.close()
Worker Process Math: Sizing Concurrency for Production
A frequent mistake is matching max_concurrency 1:1 with your database connection pool size without factoring in worker processes.
Suppose your PostgreSQL instance allows 20 connections, and you configure:
SessionDep = Annotated[Session, Depends(get_session, max_concurrency=20)]
If you deploy your container with Uvicorn configured for 4 workers:
$$\text{Total Max Concurrent Sessions} = 4 \text{ workers} \times 20 \text{ limit} = 80 \text{ sessions}$$
During a traffic burst, the workers will attempt to check out up to 80 connections from a database that only allows 20, causing immediate pool timeouts!
The Formula for Worker Concurrency Limits
$$\text{max_concurrency per worker} = \left\lfloor \frac{\text{DB Pool Size} - \text{Headroom}}{\text{Number of Workers}} \right\rfloor$$
For example, with a pool size of 20, 4 headroom reserved for migrations and background workers, and 4 Uvicorn workers:
$$\text{max_concurrency} = \left\lfloor \frac{20 - 4}{4} \right\rfloor = 4$$
Setting max_concurrency=4 ensures your worker cluster can never overwhelm the database, regardless of traffic spikes.
The 5 Architectural Rules to Avoid Deadlocks
To safely use max_concurrency across multi-resource applications, enforce these five architectural rules across your engineering team:
1. Global Deterministic Acquisition Order
Establish a strict, documented resource hierarchy and never deviate from it across any route: $$\text{Authentication} \longrightarrow \text{Cache/Redis} \longrightarrow \text{Primary Database} \longrightarrow \text{External Third-Party APIs}$$ If every endpoint acquires Resource A before Resource B, a circular wait deadlock is mathematically impossible.
2. Put Limits on Creators, Not Consumers
Always place max_concurrency on the lowest-level dependency where the socket or resource is instantiated, not on intermediate service classes.
3. Keep Dependency Caching Enabled
Do not pass use_cache=False to Depends() on rate-limited dependencies unless strictly necessary for multi-tenant isolation. Caching ensures multiple references within a single request share one permit.
4. Acquire Late, Release Early
If an endpoint only needs a database connection for a single query at the beginning of a long calculation, do not inject the session into the route header where it stays locked for the entire execution. Use an explicit asynchronous context manager inside the function body.
5. Add Fail-Safe Timeouts
Wrap external dependencies or acquisition locks with asyncio.wait_for so that if a deadlock condition ever occurs, requests fail fast with an HTTP 504 or 503 instead of hanging forever.
Full Production Example: Multi-Resource Pipeline Without Deadlocks
Here is a complete, production-ready implementation demonstrating clean dependency composition, shared limits, and ordered acquisition:
from typing import Annotated
from contextlib import asynccontextmanager
import asyncio
from fastapi import FastAPI, Depends, HTTPException, status
# 1. Define shared resources with explicit concurrency limits
async def get_db_session():
"""Simulates acquiring a database connection from a limited pool."""
print("Acquiring DB session")
yield {"db": "postgres_active_session"}
print("Releasing DB session")
async def get_redis_client():
"""Simulates acquiring a Redis client connection."""
print("Acquiring Redis client")
yield {"redis": "redis_active_connection"}
print("Releasing Redis client")
# Sized safely for our process model
DatabaseSession = Annotated[
dict,
Depends(get_db_session, max_concurrency=10, use_cache=True)
]
RedisClient = Annotated[
dict,
Depends(get_redis_client, max_concurrency=25, use_cache=True)
]
app = FastAPI(title="Resilient Multi-Resource API")
# 2. Strict hierarchical composite dependency
# ORDER: Redis (Cache) -> Database (Storage)
async def get_authenticated_context(
cache: RedisClient,
db: DatabaseSession
) -> dict:
"""Enforces consistent acquisition order across all routes."""
return {"cache": cache, "db": db}
RequestContext = Annotated[dict, Depends(get_authenticated_context)]
# 3. Routes always acquire via the standardized composite context
@app.get("/users/{user_id}")
async def get_user_profile(user_id: int, ctx: RequestContext):
# Safe from circular wait deadlocks:
# 1. Redis is always acquired first
# 2. Database is always acquired second
return {
"user_id": user_id,
"cache_status": ctx["cache"]["redis"],
"db_status": ctx["db"]["db"]
}
@app.post("/users/{user_id}/sync")
async def sync_user_data(user_id: int, ctx: RequestContext):
# Uses the exact same acquisition hierarchy
return {
"status": "synced",
"user_id": user_id
}
Summary Checklist for Code Reviews
Before shipping FastAPI endpoints with max_concurrency to production, verify:
- Are all
max_concurrencylimits placed on the underlying resource creator, rather than composite services? - Is
use_cache=Truepreserved on dependencies that appear multiple times in the same request graph? - Do all endpoints that require multiple resources acquire them in the exact same chronological sequence?
- Is
max_concurrencymultiplied by the number of Uvicorn worker processes to ensure total connections remain within database pool limits? - Do long streaming responses release constrained dependencies before data transfer begins?
By following these patterns, you can take full advantage of FastAPI’s dependency concurrency control to protect your databases and microservices without introducing silent deadlocks.



