FastAPI Async SQLAlchemy¶
Drop-in async SQLAlchemy middleware for FastAPI. A request-scoped
AsyncSession you reach through a single global db — no per-route
dependency wiring, no manual session plumbing.
Why this middleware?¶
SQLAlchemy's AsyncSession is not safe to share across concurrent tasks, and
FastAPI gives you a fresh request per coroutine. This middleware binds one
session to each request context using a Python ContextVar, so
db.session always resolves to the right session for the request you're in —
whether you access it from a route, a service function, or a background helper.
from fastapi import FastAPI
from fastapi_async_sqlalchemy import SQLAlchemyMiddleware, db
from sqlalchemy import text
app = FastAPI()
app.add_middleware(
SQLAlchemyMiddleware,
db_url="postgresql+asyncpg://user:pass@localhost:5432/app",
)
@app.get("/ping")
async def ping():
result = await db.session.execute(text("SELECT 1"))
return {"db": result.scalar()}
No Depends(get_session), no passing the session down every call. Access the
session anywhere in the request with db.session.
Features¶
-
Request-scoped sessions
A
ContextVar-backedAsyncSessionper request. Reach it from anywhere withdb.session— no dependency injection boilerplate. -
Engine lifecycle done right
Pass a
db_urland the middleware owns and disposes the engine on shutdown; pass acustom_engineand you keep ownership. -
Pool-throttled concurrency
Run many queries in parallel without exhausting the pool.
db.gather()anddb.connection()cap in-flight sessions atmax_concurrent. -
Multiple databases
Build independent middleware/proxy pairs with
create_middleware_and_session_proxy()— one per database. -
Streaming-aware
Clear rules for
StreamingResponseso the session lifetime belongs to the body, not a closed request transaction. -
Typed & SQLModel-ready
Ships
py.typed, aDBSessionMetaProtocol for full autocomplete, and works transparently withsqlmodel.
Installation¶
Requires Python 3.12+, starlette>=0.40, and SQLAlchemy>=2.0. Add the async
driver for your database (asyncpg, aiomysql, aiosqlite, …).