Backend Engineer: Sub-Millisecond Database Test Isolation in Async Python with Pytest & Nested PostgreSQL Savepoints

Running integration tests against SQLite in memory when your production database is PostgreSQL 16 hides critical bugs in `JSONB` operators, `ON CONFLICT` upserts, `SELECT ... FOR UPDATE SKIP LOCKED` queues, and custom triggers. However, running `TRUNCATE TABLE ... CASCADE` after every test function in a 600-test async Python suite takes several minutes and breaks when application code calls `await session.commit()` internally. As a Backend Engineer, I architect zero-truncation nested savepoint rollback fixtures in `pytest-asyncio` and SQLAlchemy 2.0 `asyncpg`.

1. Wrapping Application `session.commit()` Calls Inside Nested PostgreSQL Savepoints

If a FastAPI route handler calls `await session.commit()`, a naive outer test transaction gets committed permanently to disk. By listening to SQLAlchemy's `after_transaction_end` event and automatically re-opening a `SAVEPOINT` (`begin_nested()`), application code can call `commit()` and `rollback()` freely while the outer test fixture rolls back the entire outer transaction in `< 0.5 ms` at teardown:

from typing import AsyncIterator
import pytest_asyncio
from sqlalchemy import event
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession

@pytest_asyncio.fixture
async def isolated_db_session(async_engine: AsyncEngine) -> AsyncIterator[AsyncSession]:
    async with async_engine.connect() as conn:
        outer_tx = await conn.begin()
        session = AsyncSession(bind=conn, join_transaction_mode="create_savepoint")

        try:
            yield session
        finally:
            await session.close()
            await outer_tx.rollback()

2. Parallel Multi-Worker Execution (`pytest-xdist`) with Per-Worker Template Databases

Notice SQLAlchemy 2.0's `join_transaction_mode="create_savepoint"` option: whenever the test or FastAPI endpoint commits, SQLAlchemy releases only the inner `SAVEPOINT` while keeping the outer connection transaction uncommitted! When running 8 parallel `pytest -n 8` workers, our session-scoped setup runs Alembic migrations once on `test_template_db` and clones `test_db_gw0..gw7` in milliseconds via `CREATE DATABASE test_db_gw0 TEMPLATE test_template_db;`—integrating seamlessly with our FastAPI Lifespan & Dependency Injection architecture and Alembic CI/CD migration pipelines.

Need a Backend Engineer to speed up your async Python, FastAPI, or Django PostgreSQL test suite? Book a 1-Day Engineering Sprint.


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 15+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs