Lesson 19 of 59Data and storage
Async Databases: SQLAlchemy AsyncSession, asyncpg and SQLModel
Run SQLAlchemy 2 with asyncio in FastAPI: engine and session setup, MissingGreenlet, eager loading, drivers, pool sizing, and when SQLModel fits.
You convert a FastAPI service to async def routes, swap in create_async_engine, and the first endpoint that returns a user with their orders crashes with MissingGreenlet: greenlet_spawn has not been called. A week later the service falls over under load with QueuePool limit ... reached, connection timed out, and someone asks whether async was worth it at all. Async SQLAlchemy is not hard, but it changes a few rules you relied on without noticing, mostly around lazy loading and sessions. This lesson shows the setup that works, why the famous error happens, how to size connection pools, and when plain sync code is the better choice. It builds on the models and sessions from Databases with SQLAlchemy and on Async and Await from the Python course. How FastAPI runs async def routes on the event loop gets its own lesson, Background Tasks and Async, at the start of the next unit.
Setting up the engine and session
Install the asyncio extra. In SQLAlchemy 2.1 the greenlet package is no longer installed by default, so sqlalchemy[asyncio] (or a driver extra that includes it) is required:
uv add "sqlalchemy[asyncio]" asyncpgThen one module owns the engine, the session factory and the dependency:
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import Depends, FastAPI
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.settings import settings
engine = create_async_engine(
settings.database_url, # "postgresql+asyncpg://app:secret@db:5432/shop"
pool_size=5,
max_overflow=5,
pool_pre_ping=True,
pool_recycle=1800,
)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session:
async with session.begin(): # COMMIT on success, ROLLBACK on any exception
yield session
SessionDep = Annotated[AsyncSession, Depends(get_session, scope="function")]
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await engine.dispose() # close pooled connections cleanly on shutdownThe URL picks the driver. postgresql+asyncpg:// uses asyncpg. postgresql+psycopg:// uses psycopg 3, which supports both sync and async, so the same URL works with create_engine and create_async_engine.
Queries look exactly like sync 2.0 style, with await in front of anything that talks to the database:
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import Order
async def list_orders(session: AsyncSession, customer_id: int) -> list[Order]:
stmt = select(Order).where(Order.customer_id == customer_id).order_by(Order.id.desc()).limit(50)
result = await session.scalars(stmt)
return list(result)
async def create_order(session: AsyncSession, customer_id: int) -> Order:
order = Order(customer_id=customer_id, status="pending")
session.add(order) # no await: only tracks the object in memory
await session.flush() # sends the INSERT, fills order.id
return ordersession.add is not awaited because it does no I/O. flush, commit, execute, scalars, get, refresh and delete are. Note that delete is awaited too, because deleting may need to load related rows first.
How async SQLAlchemy works underneath
The ORM is a large body of synchronous code: the unit of work, the identity map, relationship loading. Rewriting all of it with async and await would have meant two ORMs. Instead, SQLAlchemy runs the sync ORM inside a greenlet, a lightweight coroutine that can pause from deep inside ordinary function calls. When the sync code needs the database, it hands the driver's coroutine up to your event loop, the loop awaits it, and the greenlet resumes with the result.
You call the async API. AsyncSession is a thin wrapper around a normal sync Session.
This explains the core rule: any database access must start from an awaited call. Plain attribute access cannot be awaited, so it must never need the database.
Put the steps of one await session.scalars(stmt) call in order.
- Tap the steps below in the right order.
MissingGreenlet and lazy loading
In sync SQLAlchemy, order.customer on an unloaded relationship quietly runs a SELECT. That is lazy loading, and it is the default. In async code the same line raises:
sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_() here.
Was IO attempted in an unexpected place?The usual places it hides are a Pydantic response model that reads a relationship while FastAPI serialises the result, a property on the model that touches a relationship, and a loop in a template or service. You have four fixes, from most to least common.
1. Load what you need up front. This is the fix for almost every case, and it also kills N+1 queries:
from sqlalchemy.orm import joinedload, selectinload
stmt = (
select(Order)
.where(Order.customer_id == customer_id)
.options(
joinedload(Order.customer), # many-to-one: one JOIN
selectinload(Order.items), # one-to-many: one extra SELECT ... WHERE order_id IN (...)
)
)
orders = (await session.scalars(stmt)).all()Use joinedload for many-to-one and selectinload for collections. A joined collection multiplies rows, and then you also need .unique() on the result.
2. Make accidental lazy loads fail loudly. Set lazy="raise" on relationships (or raiseload("*") as a query option). An unloaded access then raises InvalidRequestError: 'Order.customer' is not available due to lazy='raise' immediately, in your tests, with a clear message, instead of failing only on code paths that run under async.
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(ForeignKey("customers.id"))
customer: Mapped["Customer"] = relationship(lazy="raise")
items: Mapped[list["OrderItem"]] = relationship(lazy="raise")3. Await the attribute explicitly. Add the AsyncAttrs mixin to your base class and you get awaitable_attrs, an awaitable version of every attribute:
from sqlalchemy.ext.asyncio import AsyncAttrs
from sqlalchemy.orm import DeclarativeBase
class Base(AsyncAttrs, DeclarativeBase):
pass
items = await order.awaitable_attrs.items # lazy load, done the async wayThis is fine for an occasional access. In a loop it is the N+1 problem again.
4. Drop into sync code with run_sync. await session.run_sync(fn) calls fn(sync_session) inside the greenlet, where lazy loading works. It is useful for porting existing sync helpers. It is not a design to build on.
expire_on_commit and refresh
By default a session expires every object when you commit: all loaded attributes are marked stale, so the next access reloads them from the database. That is a reasonable default in sync code, where the reload is a hidden SELECT. In async code the hidden SELECT is a lazy load, and you get MissingGreenlet on the line after commit(), typically when you return the object you just created.
That is why every async setup uses async_sessionmaker(engine, expire_on_commit=False). Objects keep the values they had at commit time. The trade-off is that they can be stale if the database changed them, for example through a trigger or a server_default. When you need the database's version of a row, ask for it explicitly:
order = Order(customer_id=7, status="pending")
session.add(order)
await session.flush()
await session.refresh(order) # reload columns, including server defaults like created_at
await session.refresh(order, ["items"]) # or load one relationship explicitlyOn Postgres you can often skip the extra round trip: for a column declared with server_default, SQLAlchemy 2 adds it to the INSERT ... RETURNING, so created_at is already filled in after flush(). Check the SQL in your logs with echo=True before adding refresh calls everywhere.
One session per task, never shared
An AsyncSession is one database transaction on one connection, plus mutable state: the identity map and pending changes. It is not safe to use from two tasks at once. This looks like a speed-up and is a bug:
# Wrong: two tasks share one session
summary, orders = await asyncio.gather(
session.scalar(select(func.count(Order.id))),
session.scalars(select(Order).limit(10)),
)Depending on timing you get This session is provisioning a new connection; concurrent operations are not permitted, an IllegalStateChangeError, or a driver error such as asyncpg's another operation is in progress. Sometimes it seems to work, because the queries are quietly serialised on the one connection, and you gained nothing. One connection can only run one query at a time anyway.
If you truly need queries in parallel, give each task its own session (and so its own connection):
async def count_orders() -> int:
async with SessionLocal() as session:
return await session.scalar(select(func.count(Order.id)))
async def recent_orders() -> list[Order]:
async with SessionLocal() as session:
return list(await session.scalars(select(Order).order_by(Order.id.desc()).limit(10)))
async with asyncio.TaskGroup() as tg:
count_task = tg.create_task(count_orders())
recent_task = tg.create_task(recent_orders())The cost is that each one is its own transaction, so they may see slightly different snapshots, and each request now holds two pool connections. Usually the better fix is one query, or accepting two sequential ones. The same rule applies to background tasks: never pass the request's session to a task that outlives the request. Open a new one inside the task.
asyncpg or psycopg 3
| asyncpg | psycopg 3 | |
|---|---|---|
| API | Async only, its own API (not DB-API) | Sync and async in one package, DB-API style |
| Speed | Very fast, binary protocol throughout | Fast, especially with the C or binary build |
| Prepared statements | Caches them per connection by default | Prepares a statement after it runs a few times |
| Extras | COPY, server-side cursors, the same driver for sync scripts and Alembic | |
| Good default when | The service is async only and you want raw speed | You want one driver for the app, scripts and migrations |
Both are good choices. The difference that bites in production is PgBouncer in transaction mode. A prepared statement lives on a server connection, and PgBouncer may give your next transaction a different one, so you get errors like prepared statement "__asyncpg_stmt_1__" does not exist. Your options:
- Run PgBouncer 1.21 or later with
max_prepared_statementsset, which teaches it to track prepared statements across connections. - Or turn the caches off in the driver. With asyncpg through SQLAlchemy this means
?prepared_statement_cache_size=0in the URL plusconnect_args={"statement_cache_size": 0}. With psycopg 3 it meansconnect_args={"prepare_threshold": None}. The SQLAlchemy dialect docs have the current recipe for each driver, so check them when you set this up.
Sizing the pool
Each engine keeps a pool per process. The defaults are pool_size=5 connections kept open and max_overflow=10 extra connections allowed during bursts. When all are busy, a request waits up to pool_timeout (30 seconds by default) and then fails with the QueuePool limit error. Two settings protect you from stale connections: pool_pre_ping=True tests a connection with a cheap round trip before handing it out, and pool_recycle replaces connections older than N seconds, before a firewall or proxy silently drops them.
The number that matters is the total across every process that talks to the database. Each Uvicorn worker and each Celery prefork child has its own pool:
Press Run (⌘ Enter) to see what happens.A small pool per worker is usually plenty, because an async worker only needs a connection while a query is actually running. Once the arithmetic stops working as you add pods, put a pooler such as PgBouncer (or your cloud's proxy) in front of Postgres. Then many app connections share a few real ones, and some teams switch the app to poolclass=NullPool so the external pooler is the only pool. Performance and Scaling covers the server side of connection limits.
Using the 'sized on purpose' settings, the API scales from 4 pods to 6. What does this print?
peak_connections([
("api", 6, 4, 3, 1),
("worker", 2, 8, 1, 0),
])When sync is the better choice
Async is not automatically faster. A sync def route runs in FastAPI's threadpool (40 threads by default via AnyIO), and with sync SQLAlchemy and psycopg each request blocks its own thread while the database works. For a typical CRUD API, where the database does the heavy lifting, throughput is often similar, and sync code is simpler: lazy loading works, every library works, and stack traces are ordinary.
Async earns its place when one request waits on several slow things at once (other HTTP APIs, Redis, the database), when you hold many long-lived connections such as WebSockets or server-sent events, or when the rest of the service is already async. A sensible rule:
- New service, mostly CRUD, team new to asyncio: sync SQLAlchemy in
defroutes is a perfectly professional choice. - Service that fans out to other APIs, streams, or is already async: async SQLAlchemy, with
lazy="raise"and eager loading as house rules. - Never mix them in one route: a sync
Sessioncalled from anasync defroute blocks the event loop for every other request on that worker.
Match each symptom to its cause.
SQLModel: one class for the table and the schema
SQLModel, by FastAPI's author, builds on both SQLAlchemy and Pydantic. A class with table=True is a mapped table and a Pydantic model at the same time:
from sqlmodel import Field, Relationship, SQLModel
class TeamBase(SQLModel):
name: str = Field(min_length=2, max_length=60)
class Team(TeamBase, table=True):
id: int | None = Field(default=None, primary_key=True)
heroes: list["Hero"] = Relationship(back_populates="team")
class HeroBase(SQLModel):
name: str = Field(index=True)
team_id: int | None = Field(default=None, foreign_key="team.id")
class Hero(HeroBase, table=True):
id: int | None = Field(default=None, primary_key=True)
secret_name: str
team: Team | None = Relationship(back_populates="heroes")
class HeroCreate(HeroBase):
secret_name: str
class HeroPublic(HeroBase):
id: intThe official tutorial recommends exactly this split, and for good reasons. HeroPublic leaves out secret_name, so returning a Hero with response_model=HeroPublic cannot leak it. And table=True models do not validate when you construct them: Team(name="x") is accepted despite min_length=2, while HeroCreate and TeamCreate reject bad input. Always accept the Create model in the route, then build the table model from it with Hero.model_validate(hero_in).
SQLModel works with the async engine too (it ships an AsyncSession in sqlmodel.ext.asyncio.session), and everything in this lesson about MissingGreenlet and eager loading still applies, because underneath it is SQLAlchemy. Its limits: it lags SQLAlchemy in features and typing, it is still a 0.x library, and complex queries, custom types and advanced relationship options often mean dropping to plain SQLAlchemy anyway. Teams pick it for small and medium services where the table shape and the API shape really are close. Teams with large domains usually keep SQLAlchemy models and Pydantic schemas separate, so each can change on its own.
- AsyncSession
- SQLAlchemy's asyncio session: a wrapper that runs a sync Session inside greenlets. One per request or task.
- async_sessionmaker
- The factory that creates AsyncSession objects with shared settings such as expire_on_commit=False.
- MissingGreenlet
- The error raised when the ORM tries database I/O outside an awaited call, usually a lazy load.
- eager loading
- Loading relationships in the original query with selectinload or joinedload, so no lazy load happens later.
- expire_on_commit
- Whether commit marks loaded attributes stale. Set it to False with async sessions.
- pool_pre_ping
- An engine option that tests each pooled connection before use and replaces dead ones.
- SQLModel
- A library combining a SQLAlchemy table model and a Pydantic model in one class, built on both.