What is FastAPI dependency injection when you treat it as a resource lifecycle tool?
Most tutorials present FastAPI dependency injection as a way to pass arguments into path operations. For database work, it is more useful to treat it as a lifecycle tool: a dependency acquires a resource when the request starts and releases it when the request ends. This matters most to backend and platform engineers running async SQLAlchemy behind FastAPI, because each database object has a scope, and every object needs a defined place where it is created and closed.
Three layers, three scopes
- Process scope: one
AsyncEngineand its connection pool. The lifespan handler creates it at startup and callsdispose()on shutdown.- Factory scope: one
async_sessionmaker, built once from that engine. It holds configuration only, not connections.- Request scope: one
AsyncSessionper request. A dependency opens it from the factory and closes it after the response.
- Request scope: one
- Factory scope: one
Why the wrong scopes break
An engine per request creates a new pool for every request. Connections are never reused, so each request pays the full cost of connecting and authenticating. Under load, the open connections pile up until you hit the database's connection limit.
One session shared across requests causes two problems. First, its identity map and transaction state carry over from one request to the next, so one user's pending changes or stale objects can show up in another user's request. Second, concurrent requests will use the same AsyncSession at the same time. SQLAlchemy does not support that, and it fails with errors that are hard to reproduce.
from contextlib import asynccontextmanager
from typing import AsyncIterator
from fastapi import Depends, FastAPI, Request
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
DATABASE_URL = "postgresql+asyncpg://app_user:change-me@db.internal:5432/appdb"
@asynccontextmanager
async def lifespan(app: FastAPI):
# Process scope: one engine (and one connection pool) per worker process.
engine = create_async_engine(DATABASE_URL, pool_size=10, max_overflow=5)
# Factory scope: built once, holds configuration only, no connections.
app.state.session_factory = async_sessionmaker(engine, expire_on_commit=False)
yield
# Shutdown: close pooled connections before the process exits.
await engine.dispose()
app = FastAPI(lifespan=lifespan)
async def get_session(request: Request) -> AsyncIterator[AsyncSession]:
# Request scope: a fresh AsyncSession for each request, never shared.
factory: async_sessionmaker[AsyncSession] = request.app.state.session_factory
async with factory() as session:
yield session
# Leaving the block closes the session and returns its connection to the pool.
@app.get("/health/db")
async def db_health(session: AsyncSession = Depends(get_session)) -> dict:
result = await session.execute(text("SELECT 1"))
return {"db": result.scalar_one()}
The engine is created and disposed in the lifespan handler at process scope, the async_sessionmaker is built once from it, and a yield dependency opens and closes one AsyncSession per request.
How do yield dependencies manage an SQLAlchemy async session?
A dependency written as an async generator gives FastAPI a setup phase, a value, and a teardown phase. Code before yield runs before the endpoint. The yielded object is what gets injected. Code after yield runs once the endpoint has finished. If the endpoint raises, FastAPI throws that exception into the generator at the yield line, so the dependency sees the failure and can react to it.
For sessions, wrap the yield in async with sessionmaker() as session:. The context manager closes the session and returns its connection to the pool on every exit path, including an exception partway through a query.
Closing alone does not decide what happens to pending work, so put an explicit try around the yield:
- On success,
await session.commit(). - In
except Exception,await session.rollback()and then a bareraise.
The re-raise is required. If you catch the exception and don't re-raise it, the error is swallowed. The client can receive a generic 500 or a response that doesn't match what happened, and the original traceback may never reach your logs. The rolled-back transaction gives no outside sign that anything failed.
An HTTPException raised in the endpoint, such as a 404 after a failed lookup, also reaches the except branch. Any partial writes are rolled back, and the re-raised exception still becomes the 404 the client expects.
To keep this wiring in one place, define SessionDep = Annotated[AsyncSession, Depends(get_session)]. Endpoints then declare session: SessionDep. If the session factory or the lifecycle changes, you edit one definition and leave every handler signature alone.
from typing import Annotated, AsyncIterator
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
engine = create_async_engine("postgresql+asyncpg://app:change-me@db.internal:5432/appdb")
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
class Base(DeclarativeBase):
pass
class Item(Base):
__tablename__ = "items"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
async def get_session() -> AsyncIterator[AsyncSession]:
# async with closes the session and returns its connection on every exit path
async with SessionLocal() as session:
try:
yield session # code above is setup; code below is teardown
await session.commit() # endpoint returned without raising
except Exception:
await session.rollback() # discard any partial writes
raise # if you drop this, the error is swallowed and the client gets a misleading response
# The wiring lives here; handlers just declare `session: SessionDep`
SessionDep = Annotated[AsyncSession, Depends(get_session)]
app = FastAPI()
@app.patch("/items/{item_id}")
async def rename_item(item_id: int, name: str, session: SessionDep):
item = await session.get(Item, item_id)
if item is None:
# Thrown into get_session at the yield: rollback runs, then the re-raise becomes the 404
raise HTTPException(status_code=404, detail="Item not found")
item.name = name
return {"id": item.id, "name": item.name}
A yield dependency that commits on success, rolls back and re-raises on any exception (including HTTPException), and is exposed through a SessionDep Annotated alias.
Where should commits live: in the dependency or in service code?
Once every endpoint receives its session from one dependency, you need to decide who ends the transaction. There are two workable answers.
Option one: the dependency commits. After the yield, the dependency commits if the endpoint returned normally and rolls back if an exception escaped. Each request becomes one unit of work, and handlers never call commit(). This is convenient, but it hides the moment data becomes durable. It also handles intermediate commits and savepoints poorly, because a service that commits halfway through conflicts with a dependency that assumes it owns the whole transaction.
Option two: the dependency only provides and closes. Service functions call commit() explicitly when their work is complete. This adds a line or two per write path. In exchange, transaction boundaries are visible where the business logic lives, and nested or staged transactions remain straightforward.
| Concern | Commit in dependency | Commit in service code |
|---|---|---|
| Boilerplate | Minimal | One commit per write path |
| Visibility of durability | Implicit, at teardown | Explicit, at the call site |
| Savepoints and intermediate commits | Awkward | Natural |
| Risk of reporting success for a rolled-back write | Depends on teardown timing | Low if you commit before returning |
Teardown timing matters here. The point at which code after yield runs, relative to sending the response, has changed across FastAPI releases. Check the documentation for your version before assuming that a failed commit in teardown can still change the HTTP status. If it can't, the client may receive a 200 for a write that was rolled back. Committing before the handler returns avoids this problem.
Pick one approach and apply it across the whole codebase. Mixing the two is how double commits and silently dropped writes get in.
from typing import Annotated, AsyncIterator
from fastapi import Depends, FastAPI
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.models import User # placeholder ORM model with an `email` column
engine = create_async_engine("postgresql+asyncpg://app:change-me@localhost:5432/appdb")
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
app = FastAPI()
# Option one: the dependency owns the transaction (unit of work per request).
# The commit runs in teardown, so whether a failure here can still change the
# HTTP response depends on your FastAPI version.
async def get_session_uow() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
# Option two: the dependency only provides and closes the session.
async def get_session() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session: # closes the session on exit
yield session
# The service decides when data becomes durable, and commits before returning.
async def create_user(session: AsyncSession, email: str) -> User:
user = User(email=email)
session.add(user)
await session.commit() # a failure raises here, before any response is sent
return user
@app.post("/users")
async def post_user(email: str, session: Annotated[AsyncSession, Depends(get_session)]):
user = await create_user(session, email)
return {"id": user.id, "email": user.email}
Two session dependencies side by side: one that commits or rolls back in teardown, and one that only opens and closes the session so a service function can commit explicitly before the handler returns.
How does dependency caching share one session across a request?
Within a single request, FastAPI resolves each dependency once and reuses the result wherever the same callable appears in the graph. If get_user_repository, require_active_user, and the endpoint all declare Depends(get_session), FastAPI runs the generator once and passes all three the same AsyncSession. The repository's reads, the auth check's lookup, and the handler's writes then run in one transaction. They see the same identity map and are committed or rolled back together.
Sharing one session also means that state changes made by one participant affect all of them. If the auth dependency calls commit() to record a last-seen timestamp, it also commits whatever the repository has already flushed. If it rolls back after a failed check, it discards that work too. Treat the shared session as owned by whichever layer you chose for commits in the previous section, and keep every other dependency read-only with respect to transaction control.
Depends(get_session, use_cache=False) gives that one parameter its own session. Use it when you deliberately want independence, for example writing an audit record that must persist even if the main transaction fails. Using it out of habit is a mistake. It splits one unit of work into several transactions that can partially succeed, and nothing in the handler's signature makes the split obvious.
For cross-cutting concerns that return no value, such as rate limiting or tenant checks, attach dependencies at the router or app level with dependencies=[...]. Keep the graph shallow, though. When dependencies nest several levels deep and some have side effects, a handler's signature no longer tells you which sessions, connections, or locks a request acquires, or in what order.
from fastapi import APIRouter, Depends, Header, HTTPException
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
engine = create_async_engine("postgresql+asyncpg://app:change_me@localhost/appdb")
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session():
async with SessionLocal() as session:
yield session # Runs once per request; cached for every Depends(get_session)
class OrderRepository:
def __init__(self, session: AsyncSession):
self.session = session
async def add(self, user_id: int, sku: str) -> None:
await self.session.execute(text("INSERT INTO orders (user_id, sku) VALUES (:u, :s)"), {"u": user_id, "s": sku})
def get_order_repo(session: AsyncSession = Depends(get_session)) -> OrderRepository:
return OrderRepository(session) # Same session object the handler receives
async def require_active_user(x_user_id: int = Header(), session: AsyncSession = Depends(get_session)) -> int:
result = await session.execute(text("SELECT active FROM users WHERE id = :id"), {"id": x_user_id})
if not result.scalar():
raise HTTPException(status_code=403) # Read-only: never commit or roll back the shared session here
return x_user_id
async def check_rate_limit() -> None: ... # Returns nothing, so attach it at router level
router = APIRouter(dependencies=[Depends(check_rate_limit)])
@router.post("/orders")
async def create_order(sku: str, user_id: int = Depends(require_active_user),
repo: OrderRepository = Depends(get_order_repo),
session: AsyncSession = Depends(get_session),
audit: AsyncSession = Depends(get_session, use_cache=False)):
# Deliberately separate transaction: the audit row persists even if the order fails
await audit.execute(text("INSERT INTO audit_log (user_id, action) VALUES (:u, 'create_order')"), {"u": user_id})
await audit.commit()
await repo.add(user_id, sku)
await session.commit() # The handler owns the commit for the shared unit of work
return {"status": "created"}
The repository, auth check and handler share one cached AsyncSession and one transaction, while use_cache=False gives the audit write its own independent session and a router-level dependency handles a cross-cutting check that returns no value.
When should you avoid request-scoped sessions, and what are the async pitfalls?
That visibility matters most when one session per request holds resources longer than the request appears to. A StreamingResponse that reads rows while it sends them keeps a pooled connection checked out for the whole transfer to a slow client. When a yield dependency's cleanup runs relative to the stream has changed across FastAPI releases, so don't rely on the injected session still being open. Have the generator open its own session from the factory. The same applies to a handler that awaits a slow external API while a transaction is open: row locks and the connection stay held for the full round trip. Websocket handlers are worse, because the "request" can last for hours. Under load, these long holds exhaust the pool, and unrelated requests stall waiting for a connection.
Background tasks and coroutines started with asyncio.create_task should also create their own session from the factory. By the time they run, the injected session may already be closed, or it may still be in use by the handler. An AsyncSession is not safe for concurrent use.
Async SQLAlchemy has its own traps:
- Lazy loading issues implicit I/O when you access an attribute, and the async driver can't do that implicitly, so the access raises an error. Eager options such as
selectinloadavoid this but can over-fetch. Choose a loading strategy deliberately for each query. expire_on_commit=Falseon the session factory keeps attributes readable after commit. Otherwise, reading one triggers a refresh, which is another implicit load.- Sync
Sessionin anasync defendpoint blocks the event loop, which stalls every other request on that worker.
How do you test endpoints that use dependency injection for sessions?
FastAPI gives you a direct seam for tests: app.dependency_overrides, a dictionary that maps the original dependency callable to a replacement. Because routes declare Depends(get_session) rather than constructing sessions themselves, a test can swap get_session for a generator that yields a session bound to a test database. The endpoint code does not change.
Roll back instead of truncating
A fresh database per test is clean but slow. A cheaper approach is to open a connection, begin an outer transaction, bind an AsyncSession to that connection, and yield it from the override. After the test, roll back the outer transaction so nothing persists. If your service code calls commit(), configure the session to use savepoints when it joins an existing transaction. Otherwise the commit ends the outer transaction and the rollback has nothing to undo.
Reset overrides every time
dependency_overrides is plain mutable state on the app object. If a test sets an override and never removes it, every later test in that process inherits it. That produces failures that depend on test order. Put app.dependency_overrides.clear() in fixture teardown, not at the end of the test body, so it runs even when an assertion fails. For the same reason, do not run tests concurrently against one shared app instance in the same process. Build the app in a fixture through a factory function instead.
Skip HTTP when you can
If service functions accept a session, or a session factory, as a parameter, you can test them directly with the same rolled-back session. Keep HTTP-level tests for routing, validation, and status codes.
What are the alternatives, and how does this pattern affect development cost?
The yield dependency is one of several ways to scope a session. The table compares it with the common alternatives.
| Approach | Where lifecycle lives | Strength | Cost |
|---|---|---|---|
Yield dependency (get_session) |
One dependency | Centralized cleanup, easy test overrides | Transaction boundary is hidden from the endpoint |
| Manual context manager per endpoint | Every handler | Fully explicit | Repeated boilerplate that tends to drift |
| Middleware-managed session | Request pipeline | Applies to every request automatically | Opens sessions for routes that never touch the DB; awkward with streaming responses |
| Session factory passed into services | Caller of each service | Clear ownership, framework-agnostic | Verbose signatures; callers must remember to close |
| Context-variable scoping | Implicit global | No parameters to thread through | Hard to trace; spawned tasks may inherit or lose the wrong session |
Dependency injection only applies to callables that FastAPI invokes. CLI scripts, task workers and scheduled jobs need their own entry point. Put the open, commit-or-rollback and close logic in one shared async context manager. get_session should only enter that helper and yield, and workers should call the same helper directly. This prevents the background path from slowly developing different error handling than the HTTP path.
The effect on engineering time is mostly positive. A single small, tested dependency removes repeated session boilerplate and gives tests one override point. Leaked connections also become easier to debug, because there is only one place where a session can fail to close.
There are two costs. The commit point is not visible in handler code, and a deep dependency graph adds indirection when someone traces a failure. Keep the graph shallow, and document where transactions end.
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
.envby 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.