← Back to FastAPI, page 5

fastapi-0086 · Hard senior

How do you manage transactions and savepoints with async SQLAlchemy in FastAPI, and what are the common failure modes?

Use one AsyncSession per request from a dependency, and make the transaction boundary explicit: async with session.begin() (commit on success, rollback on error) in the service layer or the dependency. Use session.begin_nested() for a SAVEPOINT so one failing step can roll back without losing the rest. Set expire_on_commit=False to avoid lazy loads after commit, load relationships eagerly, and never share a session between concurrent tasks.

Full answer

Session lifecycle:

  • Create the engine once (create_async_engine), a async_sessionmaker(engine, expire_on_commit=False) once, and a dependency that yields one AsyncSession per request and closes it at the end.
  • Transaction boundary: either async with session.begin(): around a unit of work, or commit explicitly at the end of the service function. Pick one convention for the codebase. Do not commit in repositories or random helpers.
  • Autobegin: a session starts a transaction implicitly on first use; a long-lived dependency that never commits holds a connection (and locks) open until closed. With the default dependency scope, exit code runs after the response, so heavy post-processing keeps the connection busy.

Savepoints:

python
async with session.begin():
    session.add(order)
    try:
        async with session.begin_nested():       # SAVEPOINT
            session.add(loyalty_points_row)
            await session.flush()                # may raise IntegrityError
    except IntegrityError:
        ...                                      # only the inner work is undone

Use them for optional or retryable steps (inserting a duplicate-prone row, a best-effort audit record) without aborting the outer transaction. PostgreSQL aborts the whole transaction after an error unless the failing statement ran inside a savepoint.

Failure modes:

  • MissingGreenlet errors: touching a lazy relationship or an expired attribute outside an awaitable context. Use selectinload/joinedload, await session.refresh(obj), or lazy="raise" to find mistakes early. expire_on_commit=False prevents attributes from expiring at commit.
  • Sharing one AsyncSession across asyncio.gather tasks: sessions are not concurrency-safe. Create a session per task.
  • Exceptions after flush() leave the session in a failed state until you roll back; with session.begin() this is automatic.
  • Concurrency: row races need SELECT ... FOR UPDATE (with_for_update()), optimistic version columns, or unique constraints with retry on IntegrityError.
  • Isolation level: default READ COMMITTED on PostgreSQL; use REPEATABLE READ or SERIALIZABLE (with retries) for stricter guarantees.
  • Pool exhaustion when requests hold sessions while waiting on slow external calls; do external I/O outside the transaction.
python
import asyncio

from sqlalchemy import event, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column


class Base(DeclarativeBase):
    pass


class Account(Base):
    __tablename__ = "account"
    id: Mapped[int] = mapped_column(primary_key=True)
    owner: Mapped[str] = mapped_column(unique=True)
    balance: Mapped[int]


engine = create_async_engine("sqlite+aiosqlite://")


@event.listens_for(engine.sync_engine, "connect")
def no_implicit_begin(dbapi_connection, record):
    dbapi_connection.isolation_level = None            # pysqlite recipe so SAVEPOINT works


@event.listens_for(engine.sync_engine, "begin")
def emit_begin(conn):
    conn.exec_driver_sql("BEGIN")


Session = async_sessionmaker(engine, expire_on_commit=False)


async def main():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    async with Session() as session:
        async with session.begin():                     # commits at the end of the block
            session.add(Account(owner="asha", balance=100))
            try:
                async with session.begin_nested():      # SAVEPOINT: only this part can roll back
                    session.add(Account(owner="asha", balance=999))        # unique violation
                    await session.flush()
            except IntegrityError:
                print("duplicate rejected, outer transaction still alive")
            session.add(Account(owner="ravi", balance=50))

    async with Session() as session:
        rows = (await session.execute(select(Account.owner, Account.balance).order_by(Account.owner))).all()
        print([tuple(r) for r in rows])

    try:
        async with Session() as session:
            async with session.begin():
                session.add(Account(owner="meera", balance=10))
                await session.flush()
                raise RuntimeError("business rule failed")
    except RuntimeError as exc:
        print("rolled back:", exc)
    async with Session() as session:
        print("meera saved:", (await session.scalar(select(Account).where(Account.owner == "meera"))) is not None)
    await engine.dispose()


asyncio.run(main())

Standalone script. Run it with `python file.py`. Requires `pip install sqlalchemy aiosqlite`; SQLite needs the small connect and begin event hooks so savepoints work, PostgreSQL does not. 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): duplicate rejected, outer transaction still alive [('asha', 100), ('ravi', 50)] rolled back: business rule failed meera saved: False

Key points

  • One AsyncSession per request; one explicit transaction convention
  • begin_nested() creates a SAVEPOINT for partial rollback
  • expire_on_commit=False and eager loading avoid MissingGreenlet
  • Never share a session between concurrent tasks
  • Keep external I/O outside the transaction

Common mistakes

  • Sharing one AsyncSession between concurrent tasks
  • Triggering lazy loads in async code and hitting MissingGreenlet
  • Committing in many layers so the unit of work is unclear
  • Calling slow external services while holding a transaction open
  • Ignoring that PostgreSQL aborts the transaction after an error unless a savepoint was used

Follow-ups

  • How do you handle serialization failures with retries?
  • When do you use SELECT FOR UPDATE versus optimistic locking?
  • How do you test code that uses savepoints?

Tips

  • Show begin() plus begin_nested()
  • Name MissingGreenlet and how to avoid it
  • Mention session per request