FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

FastAPI + SQLAlchemy 2.0 Async Engine

AsyncEngine configuration, async_sessionmaker, AsyncSession lifecycle management, and AsyncPG driver integration.

Freshness: current•15 min read•Data Engineering and Databases

Key Learning Outcomes

  • ✓Configure async connection pools with asyncpg
  • ✓Prevent session leaks across concurrent FastAPI routes
Full Technical Reference Document

Mental model

SQLAlchemy 2.0 AsyncIO integration bridges Python's non-blocking asyncio event loop (uvicorn / uvloop) with PostgreSQL wire sockets via AsyncEngine, asyncpg (or psycopg 3 async), and greenlet-backed AsyncSession instances. Instead of freezing an entire ASGI worker thread while waiting 5–30 ms for PostgreSQL socket I/O—or silently crashing with MissingGreenlet when an expired attribute triggers an unexpected implicit lazy-load query outside await—explicit SQLAlchemy 2.0 select() + selectinload() eager loading plus expire_on_commit=False keeps every database round-trip awaited, deterministic, and isolated per HTTP request.

HTTP Request Route
FastAPI Depends(get_async_session)
Acquire AsyncSession from async_sessionmaker
Execute async SQL with await session.execute()
Yield Teardown & Commit/Rollback
Conceptual teaching model synthesized from:sqlalchemy-docs,postgresql-docs,fastapi-docs

Theory

In a single-threaded async def FastAPI route handler, running traditional synchronous SQLAlchemy Session calls starves every concurrent client sharing that worker process. Conversely, async ORM semantics demand explicit control over session identity lifespan and relationship loading because Python property getters (user.orders) cannot emit await transparently.

ORM Configuration / PatternSynchronous Legacy DefaultAsync 2.0 Production ConfigurationWhy It Prevents Runtime Failures
Attribute Expiryexpire_on_commit=True (default)async_sessionmaker(..., expire_on_commit=False)Prevents FastAPI Pydantic response serialization from triggering implicit lazy SELECT after await session.commit()
Relationship FetchingImplicit lazy="select"Explicit .options(selectinload(...)) or joinedload(...)Eliminates MissingGreenlet crashes and N+1 query storms inside async handlers
Driver Pooling Behind PgBouncerDefault statement_cache_size=1024 + QueuePoolconnect_args={"statement_cache_size": 0} (or poolclass=NullPool if delegating completely)Prevents prepared statement mismatch errors under PgBouncer transaction pooling
Connection LivenessNo pre-check before checkoutpool_pre_ping=True, pool_recycle=1800Detects silently dropped TCP sockets after database restart or cloud NAT idle drops

Lifespan Ownership, Transactions, and selectinload vs joinedload

Bind AsyncEngine once inside module/lifespan scope (ensuring await engine.dispose() runs on ASGI shutdown) and derive per-request AsyncSession objects via async_sessionmaker. When querying one-to-many collections (User -> many APIKeys), prefer selectinload(User.api_keys), which emits two clean, non-cartesian SQL queries (WHERE user_id IN (...)) without duplicating parent rows across network frames; reserve joinedload() for many-to-one (Order.user) lookups (remembering .unique() on scalar results when joins touch collections). Keep session transactions short: commit before calling external LLM APIs or uploading files so database row locks and connection pool slots do not idle behind slow upstream providers.

python
from collections.abc import AsyncIterator
from typing import Annotated
from fastapi import Depends, FastAPI
from sqlalchemy import ForeignKey, String, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, selectinload
​
DATABASE_URL = "postgresql+asyncpg://app:secret@pgbouncer:6432/app_db"
​
engine = create_async_engine(
DATABASE_URL,
pool_size=10,
max_overflow=10,
pool_pre_ping=True,
pool_recycle=1800,
# Required when PgBouncer runs in transaction pooling mode (< 1.21 or max_prepared_statements=0)
connect_args={"statement_cache_size": 0},
)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False, autoflush=False)
​
class Base(DeclarativeBase):
pass
​
class Workspace(Base):
__tablename__ = "workspaces"
id: Mapped[int] = mapped_column(primary_key=True)
slug: Mapped[str] = mapped_column(String(80), unique=True)
tokens: Mapped[list["ApiToken"]] = relationship(back_populates="workspace")
​
class ApiToken(Base):
__tablename__ = "api_tokens"
id: Mapped[int] = mapped_column(primary_key=True)
workspace_id: Mapped[int] = mapped_column(ForeignKey("workspaces.id"))
label: Mapped[str] = mapped_column(String(120))
workspace: Mapped[Workspace] = relationship(back_populates="tokens")
​
async def get_db() -> AsyncIterator[AsyncSession]:
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
​
DbDep = Annotated[AsyncSession, Depends(get_db)]
app = FastAPI()
​
@app.get("/workspaces/{slug}")
async def read_workspace(slug: str, db: DbDep) -> dict[str, object]:
stmt = (
select(Workspace)
.where(Workspace.slug == slug)
.options(selectinload(Workspace.tokens))
)
workspace = (await db.execute(stmt)).scalar_one_or_none()
if not workspace:
return {"found": False}
return {"slug": workspace.slug, "token_count": len(workspace.tokens)}

Alternatives and trade-offs

  • SQLAlchemy 2.0 ORM (AsyncSession + Typed Mapped[]): Full unit-of-work dirty tracking, Alembic autogeneration compatibility, clean Mapped[] type inference with Pyright, and seamless Core SQL escape hatches; demands explicit discipline around eager loading (selectinload) and short transaction scopes.
  • SQLAlchemy Core Async (AsyncConnection) or Raw asyncpg: Removes unit-of-work identity-map overhead for ultra-high-throughput bulk inserts (COPY), OLAP streaming, or custom CTE queries (20–40% faster Python CPU per row), at the cost of writing manual SQL row mapping.
  • Synchronous Session on def Endpoints: FastAPI runs def routes in an AnyIO threadpool, making sync SQLAlchemy reasonable for low-concurrency admin apps, though every blocked DB socket ties up an entire OS thread rather than scaling across thousands of suspended coroutines.

Failure modes and misconceptions

  1. MissingGreenlet: greenlet_spawn has not been called on Attribute Access: Triggered either by touching an un-loaded lazy relationship (workspace.tokens) or reading column attributes on a committed object when expire_on_commit=True (especially inside FastAPI's Pydantic response encoder). Fix by setting expire_on_commit=False on async_sessionmaker and marking relationships lazy="raise" or explicitly fetching with selectinload/joinedload.
  2. Sharing One AsyncSession Across Concurrent asyncio.gather() Tasks: AsyncSession holds a single underlying transaction and connection buffer and is strictly not concurrency-safe. Never share one injected AsyncSession across parallel asyncio.gather() coroutines; open distinct sessions per concurrent task instead.
  3. Default QueuePool Exhaustion Under pytest-asyncio Loops: Defining engine = create_async_engine(...) at import time binds pool futures to whichever event loop exists first. In pytest suites creating per-test loops, use NullPool in test fixtures or call await engine.dispose() between test loops.
  4. Blocking Event Loop via Implicit Lazy Joins During scalar() Serialization: Forgetting lazy="raise_on_sql" during development lets accidental N+1 relationships lurk until production concurrency peaks—or explode immediately under async mode. Set lazy="raise" on async ORM models globally as an architectural guardrail.
Reflect before revealing the guide

Decision scenario

Your FastAPI microservice handles 2,500 req/s behind PgBouncer pool_mode=transaction, returning nested workspace payloads via Pydantic V2 from_attributes=True response models. Instantiate a single AsyncEngine per process with connect_args={"statement_cache_size": 0} and pool_pre_ping=True, configure async_sessionmaker(..., expire_on_commit=False), mark all ORM relationships with lazy="raise" so forgotten joins fail loudly in tests rather than silently issuing N+1 queries, fetch collections explicitly with selectinload(), and never pass one AsyncSession into asyncio.gather().

Learning outcomes

  • Explain why synchronous ORM calls freeze ASGI worker event loops and how AsyncEngine + asyncpg resolves I/O stalls.
  • Prevent MissingGreenlet crashes using expire_on_commit=False, lazy="raise", and explicit selectinload/joinedload.
  • Configure AsyncEngine pool sizing and statement_cache_size=0 safely behind PgBouncer transaction pooling.
  • Isolate AsyncSession lifecycles per request and avoid concurrent sharing across asyncio.gather().

Trade-offs

SQLAlchemy 2.0 AsyncSession combines strict type safety and Alembic schema evolution with high non-blocking concurrency, but forces engineers to replace convenient implicit lazy loading with explicit query-loading plans (selectinload) and disciplined transaction boundaries.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next