← Back to FastAPI, page 2

fastapi-0036 · Hard senior

How do you use SQLAlchemy's async engine and AsyncSession with FastAPI, and what problems are specific to async ORM usage?

Create an engine with create_async_engine and an async driver (asyncpg, psycopg async, aiosqlite), an async_sessionmaker with expire_on_commit=False, and an async generator dependency that yields an AsyncSession. Use await session.execute/scalars/get and await session.commit. The async-specific trap is implicit lazy loading: touching an unloaded relationship raises MissingGreenlet, so load relationships eagerly with selectinload or use AsyncAttrs.awaitable_attrs, and never share one AsyncSession across concurrent tasks.

Full answer

Setup:

python
engine = create_async_engine("postgresql+asyncpg://...", pool_size=10, pool_pre_ping=True)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)

async def get_db():
    async with SessionLocal() as session:
        yield session

Usage in async def endpoints:

  • await session.get(Book, id)
  • (await session.scalars(select(Book).where(...))).all()
  • session.add(obj) (not awaited), await session.commit(), await session.refresh(obj)
  • await session.delete(obj) in SQLAlchemy 2.x
  • async with session.begin(): for a transaction block

Create tables in lifespan with async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) (demos only; use Alembic for real schemas, it supports async engines via run_sync).

Async-specific problems:

  1. Lazy loading. In sync code, book.author silently runs a query. In async code, SQLAlchemy cannot run I/O implicitly and the attempt fails with MissingGreenlet. When it happens while a statement is executing, SQLAlchemy wraps it, so you catch StatementError and find the original under exc.orig (the snippet shows this). Fixes: select(Book).options(selectinload(Book.author)), lazy="selectin" on the relationship, or lazy="raise" (fail fast: any lazy access raises InvalidRequestError before I/O, a clearer error than the wrapped one), or await book.awaitable_attrs.author with the AsyncAttrs mixin.
  2. Expired attributes after commit. With the default expire_on_commit=True, reading book.title after commit triggers a refresh, which fails the same way. Set expire_on_commit=False.
  3. Sharing a session. An AsyncSession is not safe for concurrent use. asyncio.gather(query1(session), query2(session)) on one session raises errors. Use one session per task, or run queries sequentially.
  4. Pool sizing. Async code can start many more concurrent queries than sync code. Keep pool_size + max_overflow under the database's connection budget across all workers, and use a semaphore for big fan-outs.
  5. Engine disposal. await engine.dispose() in lifespan shutdown.

Async is worth it when the service does lots of concurrent I/O (database plus outbound HTTP) per request. For simple CRUD, sync SQLAlchemy in def endpoints is often just as fast and simpler.

python
import asyncio
from contextlib import asynccontextmanager
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
from sqlalchemy import ForeignKey, select
from sqlalchemy.exc import InvalidRequestError, MissingGreenlet, StatementError
from sqlalchemy.ext.asyncio import AsyncAttrs, AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, selectinload

engine = create_async_engine("sqlite+aiosqlite:///:memory:")
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)


class Base(AsyncAttrs, DeclarativeBase):
    pass


class Author(Base):
    __tablename__ = "authors"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    books: Mapped[list["Book"]] = relationship(back_populates="author")


class Book(Base):
    __tablename__ = "books"
    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str]
    author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"))
    author: Mapped[Author] = relationship(back_populates="books")
    editor: Mapped[Author] = relationship(foreign_keys=[author_id], viewonly=True, lazy="raise")


class BookOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    title: str
    author_name: str


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    async with SessionLocal() as s:
        rk = Author(name="R. K. Narayan")
        s.add_all([Book(title="Swami and Friends", author=rk), Book(title="The Guide", author=rk)])
        await s.commit()
    yield
    await engine.dispose()


async def get_db():
    async with SessionLocal() as session:
        yield session


DB = Annotated[AsyncSession, Depends(get_db)]
app = FastAPI(lifespan=lifespan)


@app.get("/books-lazy")
async def books_lazy(db: DB):
    books = (await db.scalars(select(Book).order_by(Book.id))).all()
    try:
        return [b.author.name for b in books]          # implicit lazy load
    except StatementError as exc:                      # SQLAlchemy wraps MissingGreenlet here
        return {"error": "lazy load attempted inside async code",
                "cause": type(exc.orig).__name__, "is_missing_greenlet": isinstance(exc.orig, MissingGreenlet)}


@app.get("/books-raise")
async def books_raise(db: DB):
    books = (await db.scalars(select(Book).order_by(Book.id))).all()
    try:
        return [b.editor.name for b in books]          # relationship declared with lazy="raise"
    except InvalidRequestError as exc:
        return {"error": "blocked before any I/O", "cause": type(exc).__name__}


@app.get("/books", response_model=list[BookOut])
async def books(db: DB):
    stmt = select(Book).options(selectinload(Book.author)).order_by(Book.id)
    rows = (await db.scalars(stmt)).all()
    return [BookOut(title=b.title, author_name=b.author.name) for b in rows]


@app.get("/authors/{author_id}/count")
async def count_books(author_id: int, db: DB):
    author = await db.get(Author, author_id)
    return {"author": author.name, "books": len(await author.awaitable_attrs.books)}


with TestClient(app) as c:
    print(c.get("/books-lazy").json())
    print(c.get("/books-raise").json())
    print(c.get("/books").json())
    print(c.get("/authors/1/count").json())

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install "sqlalchemy[asyncio]" aiosqlite`; production uses asyncpg or psycopg with PostgreSQL. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'error': 'lazy load attempted inside async code', 'cause': 'MissingGreenlet', 'is_missing_greenlet': True} {'error': 'blocked before any I/O', 'cause': 'InvalidRequestError'} [{'title': 'Swami and Friends', 'author_name': 'R. K. Narayan'}, {'title': 'The Guide', 'author_name': 'R. K. Narayan'}] {'author': 'R. K. Narayan', 'books': 2}

Key points

  • create_async_engine + async_sessionmaker(expire_on_commit=False)
  • Async generator dependency yields AsyncSession
  • Await execute, scalars, get, commit, refresh
  • Lazy loading raises MissingGreenlet; eager load with selectinload
  • One AsyncSession per task; size pools carefully

Common mistakes

  • Relying on lazy loading and getting MissingGreenlet errors
  • Keeping expire_on_commit=True and reading attributes after commit
  • Sharing one AsyncSession across asyncio.gather tasks
  • Using async SQLAlchemy with a sync driver like psycopg2
  • Choosing async for plain CRUD where sync would be simpler

Follow-ups

  • What does lazy='raise' on a relationship do, and why use it?
  • How do you run Alembic migrations with an async engine?
  • How would you run two independent queries concurrently?

Tips

  • Show the setup and the await points
  • Explain MissingGreenlet and two fixes
  • Say when async SQLAlchemy is not worth it