What is FastAPI dependency injection, and how does Depends resolve a request?

Depends is often described as a way to pass arguments into a route. A more useful view is that it is a per-request lifecycle manager. A dependency declares what a request needs, such as a database session, a token or a user. FastAPI creates that resource, hands it to every consumer that asks for it, and tears it down when the request finishes.

When a request arrives, FastAPI walks the route's signature and each dependency's signature recursively. This builds a graph and resolves it leaves-first. Dependencies that use yield are cleaned up in reverse order of setup.

Within a single request, each dependency callable is cached by default. If get_current_user and the route handler both declare Depends(get_db), they receive the same session object:

route
  └── require_role
        └── get_current_user
              ├── get_token
              └── get_db ◄──────┐
  └── get_db ───────────────────┘  (resolved once, shared)

That sharing matters for correctness, not only for efficiency. The user row loaded during auth and the writes made by the handler belong to one session and one transaction.

Depends(get_db, use_cache=False) turns caching off for that one declaration. With a yield dependency, this runs the generator a second time and opens a second session. This usually means a second connection and transaction as well. The symptoms rarely look like a dependency problem:

  • Rows written through one session are invisible to the other until commit.
  • A row lock held by one session can block the other within the same request, which can stall the request until a timeout.

Reserve use_cache=False for values that must genuinely be fresh on each call.

  ┌─────────────────────────────────────┐
  │            route handler            │
  └───────┬───────────────────────┬─────┘
          │                       │  Depends(get_db)
          ▼                       │
  ┌───────────────┐               │
  │ require_role  │               │
  └───────┬───────┘               │
          ▼                       │
  ┌──────────────────┐            │
  │ get_current_user │            │
  └───┬─────────┬────┘            │
      │         │                 │
      ▼         ▼                 ▼
 ┌───────────┐ ┌────────────────────────────┐
 │ get_token │ │   get_db  (resolved once)  │
 └───────────┘ │ one Session, one txn       │
               │ closed once, after response│
               └────────────────────────────┘

  Depends(get_db, use_cache=False): generator runs a second time
  ┌──────────────────────┐   ┌──────────────────────┐
  │ session A / conn A   │   │ session B / conn B   │
  │ txn A: holds lock    │──▶│ txn B: waits on lock │
  └──────────────────────┘   └──────────────────────┘
     uncommitted writes in A are invisible to B

FastAPI resolves get_db once per request and shares that session between get_current_user and the route, while use_cache=False creates a second session and transaction that cannot see the first one's uncommitted writes and can block on its locks.

How do you write a yield dependency that owns the db session?

Create the engine and sessionmaker once, in the app's lifespan handler, and store them on app.state. The engine owns the connection pool, so building one per request would open fresh connections each time and discard the pool's purpose. The dependency should only check a session out of that factory and hand it to the route. Everything expensive lives for the process lifetime. Everything request-scoped lives inside get_db.

Commit, rollback, close

Inside get_db, open a session and yield it inside a try block. After the yield, call commit(). In an except branch, call rollback() and then re-raise. In finally, call close() so the connection returns to the pool on every path, including cancellation.

Re-raising matters because this is not an ordinary try/except around a function call. The route body runs while the generator is suspended at yield. If the route raises, FastAPI throws that exception into the generator at the yield point. If you catch it and don't re-raise it, the exception is swallowed, or it surfaces as a confusing secondary error.

When teardown runs

Code after yield does not run on a fixed schedule relative to the response. Across FastAPI releases, it has run both before and after the response was sent. If teardown runs after the response, two things follow:

  • A commit failure can leave the client with a 200 for data that was never written.
  • An HTTPException raised during teardown may never reach the client.

Pin your FastAPI version. Write tests that force failures in the route and in the commit itself, and assert what the client actually receives. Don't depend on cleanup timing for correctness.

from contextlib import asynccontextmanager
from typing import Annotated

from fastapi import Depends, FastAPI, Request
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session, sessionmaker


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Built once per process: the engine owns the connection pool.
    engine = create_engine(
        "postgresql+psycopg://app_user:change-me@db.internal:5432/appdb",
        pool_pre_ping=True,
    )
    app.state.SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
    yield
    engine.dispose()  # Close pooled connections on shutdown.


app = FastAPI(lifespan=lifespan)


def get_db(request: Request):
    # Request-scoped: only check a session out of the shared factory.
    db = request.app.state.SessionLocal()
    try:
        yield db  # The route runs while the generator is suspended here.
        db.commit()  # Reached only if the route returned without raising.
    except Exception:
        db.rollback()
        raise  # Re-raise so FastAPI still sees the original error.
    finally:
        db.close()  # Returns the connection to the pool on every path.


@app.post("/items")
def create_item(name: str, db: Annotated[Session, Depends(get_db)]):
    db.execute(text("INSERT INTO items (name) VALUES (:n)"), {"n": name})
    return {"name": name}  # The commit happens after this, in get_db.

A yield dependency that checks a session out of a lifespan-created sessionmaker, commits on success, rolls back and re-raises on error, and always closes the session in finally.

Should dependencies be sync def or async def?

FastAPI decides how to run each dependency from how it is declared. A plain def dependency, including a generator with yield, runs in a worker threadpool, so a blocking call inside it ties up one thread and leaves the event loop free. An async def dependency runs directly on the event loop. Any blocking call inside it, such as a synchronous driver's execute, a blocking HTTP client or time.sleep, freezes the loop. While that call waits on the network, every other in-flight request on that worker process waits with it.

This failure rarely appears as an error. In local tests you send one request at a time, so a blocked loop looks like a normal query. Under concurrency it shows up as rising tail latency, request times that track the slowest query, and health checks timing out.

The reverse mismatch is also quiet. Suppose a sync def dependency yields a blocking ORM session into an async def route. The dependency's setup runs off the loop, but the queries the route runs on that session execute on the loop. Mixed setups also have a cost of their own. Sync dependencies share a bounded threadpool, so slow queries can exhaust it and requests queue for a free thread.

Driver / ORM style Dependency Route Why
Blocking driver, sync session def with yield def Session setup, queries and cleanup all run in the threadpool
Async driver, async session async def with yield async def All I/O is awaited, so the loop is never blocked
Blocking driver, async route required def with yield async def, with DB calls moved to a thread explicitly Every blocking call has to leave the loop
No I/O (header parsing, claim checks) async def Either Skips an unnecessary hop to a thread
import asyncio
import time
from typing import Annotated

from fastapi import Depends, FastAPI

app = FastAPI()


def blocking_query() -> dict:
    # Stands in for a synchronous driver's execute(): holds the calling thread ~1s
    time.sleep(1)
    return {"user_id": 42}


# BAD: async def runs on the event loop, so this call freezes every request on the worker
async def user_on_loop() -> dict:
    return blocking_query()


# OK: plain def is run in the threadpool, so the loop stays free
def user_in_threadpool() -> dict:
    return blocking_query()


# OK: async dependency that moves the blocking call off the loop explicitly
async def user_offloaded() -> dict:
    return await asyncio.to_thread(blocking_query)


@app.get("/blocked")
async def blocked(user: Annotated[dict, Depends(user_on_loop)]):
    return user


@app.get("/threadpool")
async def threadpool(user: Annotated[dict, Depends(user_in_threadpool)]):
    return user


@app.get("/offloaded")
async def offloaded(user: Annotated[dict, Depends(user_offloaded)]):
    return user

# One request at a time, all three endpoints take ~1s, so local tests look fine.
# Send 10 concurrent requests to one worker: /blocked serializes them (~10s for the last),
# while /threadpool and /offloaded overlap and finish in roughly 1s each.

The same simulated blocking query behaves identically under a single request but serializes all concurrent requests when called directly inside an async def dependency, while a sync def dependency or an explicit asyncio.to_thread keeps the event loop free.

How do you build authentication as layered dependencies?

Split the chain into four dependencies, each with one job, so any layer can be reused, overridden in tests, or swapped without touching the others.

  1. Extract credentials. OAuth2PasswordBearer returns the raw token string from the Authorization: Bearer header and adds the security scheme to the OpenAPI docs. HTTPBearer returns an HTTPAuthorizationCredentials object instead. Both reply with an error on their own when the header is missing, so later layers never see an empty value.
  2. Validate the token. get_token_claims depends on the extractor. It checks the signature, expiry and audience, then returns the claims. It does no I/O, so it can be a plain async def.
  3. Load the user. get_current_user depends on both the claims and the shared get_db. FastAPI caches each dependency within a single request, so this lookup uses the same session as the endpoint and does not open a second one.
  4. Check permissions. This layer sits on top of get_current_user. Use a factory such as require_role("admin") that returns an inner dependency function. Alternatively, use a RoleChecker class: its __init__ stores the allowed roles, and its __call__ receives the user through Depends and raises 403 when the role is missing. Either way, the check logic lives in one place, and each route only declares which roles it needs.

Loading the user costs one primary-key query per authenticated request. This is usually cheap, and it means a revoked role or a disabled account takes effect on the very next call. If you cache users or permissions in memory or Redis, you remove that query. In exchange, a revoked role stays effective until the cache entry expires. Putting roles inside the token has the same problem, except the window lasts until the token expires.

from typing import Annotated
import jwt  # PyJWT
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import get_db  # shared per-request session dependency
from app.models import User

SECRET_KEY = "placeholder-not-a-real-secret"
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token")  # layer 1: extract
router = APIRouter()

async def get_token_claims(token: Annotated[str, Depends(oauth2_scheme)]) -> dict:
    try:  # layer 2: verify signature, exp and aud, with no I/O
        return jwt.decode(token, SECRET_KEY, algorithms=["HS256"], audience="my-api")
    except jwt.InvalidTokenError:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token", headers={"WWW-Authenticate": "Bearer"})

async def get_current_user(claims: Annotated[dict, Depends(get_token_claims)],
                           db: Annotated[AsyncSession, Depends(get_db)]) -> User:
    # Layer 3: one PK query per request, using the same cached session as the endpoint
    user = await db.get(User, int(claims["sub"]))
    if user is None or not user.is_active:  # revocations take effect on the next call
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Unknown or inactive user")
    return user

def require_role(*roles: str):  # layer 4, factory style: returns a dependency
    async def checker(user: Annotated[User, Depends(get_current_user)]) -> User:
        if user.role not in roles:
            raise HTTPException(status.HTTP_403_FORBIDDEN, "Insufficient role")
        return user
    return checker

class RoleChecker:  # layer 4, class style: __init__ stores config, __call__ is the dependency
    def __init__(self, *roles: str): self.roles = set(roles)
    async def __call__(self, user: Annotated[User, Depends(get_current_user)]) -> User:
        if user.role not in self.roles:
            raise HTTPException(status.HTTP_403_FORBIDDEN, "Insufficient role")
        return user

@router.delete("/users/{user_id}", dependencies=[Depends(require_role("admin"))])
async def delete_user(user_id: int, auditor: Annotated[User, Depends(RoleChecker("admin", "auditor"))]): ...

A four-layer FastAPI auth chain (token extraction, claim validation, a user lookup through the shared get_db session, and a role check) with the role check written both as a parameterized factory and as a callable class.

When should you apply dependencies at router or app level, and when should you avoid it?

When every route in a group needs the same check, attach it once. Passing dependencies=[Depends(require_user)] to an APIRouter, to include_router, or to the FastAPI app itself runs that dependency for every route it covers. Their return values are discarded, so this suits checks whose only job is to raise, such as rejecting unauthenticated callers on an /admin router. If an endpoint also declares the same dependency as a parameter to get the user object, FastAPI caches the result per request, so the check does not run twice.

The cost is that the requirement is no longer visible where you read the route. Someone reviewing a single handler sees no auth parameter and may assume the route is public. A deeper risk is moving a handler to another router during a refactor, which silently drops the check. Deep chains cause a similar problem. When a sub-dependency pulls a session, which feeds the user lookup, which feeds the permission check, it becomes hard to tell what a route needs and in what order queries run. Keep router-level dependencies for broad, stable policies. Declare anything route-specific in the signature.

Session lifetime is the other limit. A yield-dependency session stays checked out of the pool for the whole request. Depending on your FastAPI version, that can include the time spent streaming the response body. If a handler waits several seconds on an external API, or streams a large export, each concurrent request holds a connection while doing no database work. Under load, the pool runs out of connections. For these endpoints, skip the injected session. Open a short, explicitly scoped session around each piece of database work, and release it before the slow call starts.

How do you test FastAPI dependencies with dependency_overrides?

Tests replace dependencies through app.dependency_overrides, a dictionary on the application. Each key is the original dependency callable and each value is the callable to run in its place. FastAPI looks up overrides when it resolves a request, so an override applies wherever get_db appears, including inside nested dependencies.

For the database, the override opens a connection, begins a transaction, and binds a session to that connection. It yields the session and rolls back when the request finishes. Each test then starts from the same database state, and you don't need truncation scripts. If your endpoints call commit(), configure the test session to use savepoints. Otherwise the endpoint's commit ends the outer transaction and the rollback has nothing to undo.

For auth, override the dependency that returns the current user, not the one that parses the token. The override returns a fixed user object. Permission dependencies layered on top still run against that user, so authorization logic stays under test.

Clear the overrides in fixture teardown with app.dependency_overrides.clear(). The dictionary is global mutable state. If a test fails before cleanup, its override persists, and later tests silently run against a fake user or a stale session. If tests run concurrently in the same process against one app instance, they share the dictionary and can overwrite each other's overrides. In that case, give each test its own app instance from an app factory.

This approach saves time in two ways:

  • No patching of internals. Patching module internals breaks whenever someone moves an import. Overrides are keyed by the dependency function itself, so they keep working when modules change.
  • No real auth stack in tests. Running real auth would mean minting tokens, managing signing keys, and sometimes running an identity provider. With overrides, the suite needs only a database.

What are the alternatives to committing inside a yield dependency, and what do they cost?

Where the commit lives determines where a failed commit shows up. A teardown commit runs after the handler returns, so a constraint violation or serialization failure at commit time can reach the client as an error even though the handler's logic finished cleanly. Depending on when teardown runs relative to sending the response, the client may instead see a success status for work that was rolled back. The other placements move that failure to a different point.

Placement Where commit errors surface Ease of reasoning Spread of transaction code Dev and maintenance cost
Commit in dependency teardown After the handler returns, outside its error handling Simple until a commit fails late One place Low to start. Late failures are hard to debug
Explicit commit in handler Inside the handler, before the response is built Very clear per endpoint Every write endpoint Grows with endpoint count. A forgotten commit fails silently
Service or unit-of-work layer Inside the business operation, mapped to domain errors Clear once the pattern is learned Concentrated in services More upfront structure. Cheaper as the domain grows
Middleware-managed session After routing, far from the code that caused it Hardest. The session is implicit Hidden in middleware Low to write. Fragile with streaming and background work

Small services with a handful of write endpoints can live with a teardown commit, or commit explicitly in each handler so failures stay visible. Teams with growing domains and several engineers touching the same models benefit from a unit-of-work layer. The cost of introducing it is paid once, while scattered commits cost more with every new endpoint. Middleware-managed sessions rarely justify the implicitness, because dependencies already give per-request scope with clearer ownership.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to fastapi dependency injection, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.