Mental model
FastAPI's dependency injection engine compiles declared route requirements (Depends(...) and Security(...)) into a per-request Directed Acyclic Graph (DAG) executed automatically by the framework before and after your path operation runs. Each dependency node can recursively depend on sub-dependencies—such as decoding bearer headers, fetching a database session, or checking RBAC scopes—while sharing computed results within the same request tick (use_cache=True by default) and running post-yield resource cleanup deterministically even when an endpoint raises an exception. Paired with @asynccontextmanager app lifespan hooks for process-wide connection pools, this model eliminates global mutable state and makes swapping live integrations with deterministic fakes trivial via app.dependency_overrides.
Theory
Dependency injection in FastAPI cleanly separates process-scoped infrastructure from request-scoped resources:
| Scope Level | Mechanism | Allocation Timing | Cleanup Boundary | Canonical Examples |
|---|---|---|---|---|
| Process Lifespan | @asynccontextmanager def lifespan(app) | Once at ASGI worker startup | Once at graceful worker shutdown | SQLAlchemy AsyncEngine, Redis client pool, httpx.AsyncClient, ML tokenizers |
Per-Request (return) | Depends(fn) or Annotated[..., Depends(fn)] | Once per DAG key per request (use_cache=True) | Garbage collection after response | Parsed auth claims, tenant context, query pagination DTOs |
Per-Request (yield) | async def get_db(): try: yield s finally: ... | Before route body executes | Immediately after response generation completes | AsyncSession transaction commit/rollback, temp directory lock release |
| Uncached Fresh Instance | Depends(fn, use_cache=False) | Every call site inside the same request | End of dependency stack | Fresh UUID nonce generator, independent sub-transaction handles |
Execution Order, Exception Propagation, and Modern Annotated Composition
When a route declares multiple overlapping sub-dependencies (for instance, both get_current_user and get_audit_logger depend on get_db), FastAPI solves the DAG topologically and executes get_db only once per request (use_cache=True), caching its yielded value across both downstream consumers. Crucially, the post-yield teardown block executes inside a coroutine finally wrapper after FastAPI finishes serializing the HTTP response (or handling an HTTP error) and receives any unhandled route exception via generator.throw(...), making it safe to rollback dirty database transactions on errors and commit cleanly on success. Note, however, that any HTTPException raised inside post-yield cleanup after headers are already sent cannot rewrite the status code—always perform commit/validation checks inside the route or an explicit dependency boundary before response serialization starts.
pythonfrom collections.abc import AsyncIteratorfrom contextlib import asynccontextmanagerfrom typing import Annotatedfrom fastapi import Depends, FastAPI, Header, HTTPException, Request, statusclass TelemetryPool:async def close(self) -> None: ...@asynccontextmanagerasync def lifespan(app: FastAPI) -> AsyncIterator[None]:# Process-level singletons initialized once per ASGI workerapp.state.pool = TelemetryPool()yieldawait app.state.pool.close()app = FastAPI(lifespan=lifespan)async def get_db_session(request: Request) -> AsyncIterator[dict]:session = {"pool": request.app.state.pool, "committed": False}try:yield sessionsession["committed"] = Trueexcept Exception:# Roll back partial transaction writes on application errorssession["committed"] = FalseraiseDbSessionDep = Annotated[dict, Depends(get_db_session)]def get_tenant_id(session: DbSessionDep,x_tenant_id: Annotated[str | None, Header()] = None,) -> str:if not x_tenant_id:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Missing X-Tenant-ID")return x_tenant_idTenantDep = Annotated[str, Depends(get_tenant_id)]@app.post("/v1/events")async def ingest_event(tenant: TenantDep, session: DbSessionDep) -> dict[str, object]:# get_db_session executes once per request even though both route and get_tenant_id depend on itreturn {"tenant": tenant, "reused_session": id(session)}
Using Python typing.Annotated (DbSessionDep = Annotated[dict, Depends(get_db_session)]) decouples endpoint signatures from concrete wiring while preserving full static type inference in Pyright/mypy and reusing the same dependency signature across multiple routers cleanly.
Alternatives and trade-offs
- FastAPI Built-In
DependsDAG: Zero extra packages, native OpenAPI schema generation for headers/query/security parameters, automatic async/sync threadpool dispatch, and built-inapp.dependency_overridestesting hooks; bound strictly to HTTP/WebSocket request lifecycles (not standalone CLI scripts or Celery tasks). - Explicit Service Constructor Injection / Containers (
dishka,dependency-injector): Useful when clean-architecture business services span FastAPI HTTP handlers, Kafka workers, and CLI commands outside ASGI request scopes, at the expense of boilerplate container bindings and maintaining bridge adapters into FastAPI routes. - Global Module Singletons (
db = Database()): Fast to prototype, but fragile under pytest parallel workers, ASGI lifespan reloaders, and multi-event-loop test runners (Event loop is closederrors when globalAsyncEngineobjects bind to stale loops).
Failure modes and misconceptions
- Swallowing Exceptions in
yieldDependencies Without Re-Raising: Writingtry: yield db except Exception: await db.rollback()withoutraisecauses FastAPI to treat the error as handled while simultaneously leaving the route's HTTP exception ambiguous or returning a broken500. Always clean up insideexcept/finallyand re-raise or raise a specificHTTPException. - Blocking Sync Generators in High-Throughput Routes: FastAPI silently runs regular
defdependencies (includingdef get_sync_db()) in an AnyIO worker threadpool (40default threads). Running slow external I/O inside synchronous dependencies starves FastAPI's threadpool across concurrent requests; preferasync defdependencies paired with non-blocking drivers. - Leaving Test
app.dependency_overridesMutated Across Tests: Mutatingapp.dependency_overrides[get_current_user] = mock_userwithout clearingapp.dependency_overrides.clear()in a pytest fixturefinallyblock leaks mocked auth bypasses into subsequent integration tests. - Streaming Response Timing Mismatch with
yieldTeardown: Starting aStreamingResponsethat reads lazily from an injected database cursor fails if FastAPI completes the dependency context in Starlette/FastAPI versions or scopes before the stream exhausts—verify generator ownership (AsyncExitStackor explicit stream cleanup) whenever streaming database results.
Decision scenario
Your team runs multi-tenant AI API endpoints requiring request authentication, per-tenant database session scoping, OpenTelemetry trace tagging, and reliable pytest isolation without hitting live PostgreSQL or OAuth JWKS servers in CI. Define process-wide AsyncEngine and httpx.AsyncClient pools inside an @asynccontextmanager def lifespan(app) hook attached to app.state, compose reusable Annotated[..., Depends(...)] aliases (DbDep, CurrentUserDep) using yield teardown for transactional rollback safety, and install an autouse pytest fixture that swaps app.dependency_overrides cleanly per test and invokes app.dependency_overrides.clear() on teardown.
Learning outcomes
- Trace topological resolution and per-request caching (
use_cache=True) across nestedDependsDAGs. - Separate process-wide singletons (
lifespan+app.state) from request-scopedyielddependencies to avoid stale event-loop leaks. - Author reusable
Annotateddependency aliases that preserve static type safety and OpenAPI documentation. - Isolate integration tests cleanly via
app.dependency_overrideswithout leaking overrides across test modules.
Trade-offs
FastAPI's declarative Depends graph removes manual boilerplate for request validation, OpenAPI security docs, and deterministic cleanup while supporting zero-friction test mocks, though non-HTTP background workers must resolve dependencies separately outside ASGI lifecycles.