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:

  1. Concurrent Index Creation: Execute op.create_index(..., postgresql_concurrently=True) inside an op.get_context().autocommit_block().
  2. Two-Step NOT VALID Foreign Keys & Check Constraints: Add constraints with NOT VALID (instant metadata operation) followed by VALIDATE CONSTRAINT (which only takes a non-blocking SHARE UPDATE EXCLUSIVE lock).
  3. Explicit lock_timeout Guards: Set SET 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.


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