Senior Backend Engineer Guide: Async SQLAlchemy 2.0, asyncpg & Zero-Downtime Alembic
In high-concurrency asynchronous Python services (FastAPI, Starlette, aiohttp, or asyncio worker pools), accidentally calling a synchronous psycopg2 database query blocks the entire Python event loop—freezing every concurrent HTTP request and WebSocket connection on that worker process. Conversely, migrating to SQLAlchemy 2.0 AsyncIO with asyncpg without understanding session lifecycle and lazy-loading rules triggers dreaded MissingGreenlet runtime crashes. As a Senior Backend Engineer, I architect non-blocking PostgreSQL persistence layers and zero-downtime Alembic migration pipelines.
1. Eliminating MissingGreenlet Crashes & Scoping AsyncSession per Request
In async SQLAlchemy 2.0, implicit lazy-loading of relationship attributes over the network is forbidden outside an explicit greenlet context because attribute access in Python (user.orders) is synchronous syntax. By setting expire_on_commit=False on the async_sessionmaker and using explicit selectinload() or joinedload() options, queries remain 100% non-blocking and predictable:
from collections.abc import AsyncGenerator
from sqlalchemy import select
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import selectinload
engine = create_async_engine(
"postgresql+asyncpg://app_user:secret@db.internal:5432/prod_ledger",
pool_size=20,
max_overflow=10,
pool_pre_ping=True,
)
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
)
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
yield session
async def fetch_tenant_with_active_keys(session: AsyncSession, tenant_id: str):
stmt = (
select(TenantModel)
.options(selectinload(TenantModel.api_keys))
.where(TenantModel.id == tenant_id)
)
result = await session.execute(stmt)
return result.scalar_one_or_none()
2. Lock-Safe, Zero-Downtime Alembic Migrations on High-Traffic Tables
Running a naive op.create_index() or adding a foreign key constraint in Alembic acquires an ACCESS EXCLUSIVE or SHARE table lock in PostgreSQL—blocking production writes for minutes on multi-million-row tables. I enforce three Alembic migration invariants in CI/CD:
- Concurrent Index Creation: Execute
op.create_index(..., postgresql_concurrently=True)inside anop.get_context().autocommit_block(). - Two-Step
NOT VALIDForeign Keys & Check Constraints: Add constraints withNOT VALID(instant metadata operation) followed byVALIDATE CONSTRAINT(which only takes a non-blockingSHARE UPDATE EXCLUSIVElock). - Explicit
lock_timeoutGuards: SetSET LOCAL lock_timeout = '3s'at the start of every migration so a blocked DDL statement aborts cleanly instead of queuing application queries into a cascading outage.
3. Hire a Senior Backend Engineer for Python, FastAPI & PostgreSQL
Scaling an async FastAPI/SQLAlchemy backend or untangling risky Alembic migrations? Explore my Backend Engineer Pillar Guide, review my High-Throughput PostgreSQL Outbox Guide, or book a 1-Day Database Architecture Sprint.