FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Schema Migrations with Alembic

Database revision histories, auto-generation DDL scripts, lock timeout safety, and zero-downtime migrations.

Freshness: current•15 min read•Data Engineering and Databases

Key Learning Outcomes

  • ✓Write non-blocking Alembic migration scripts
  • ✓Execute zero-downtime schema migrations in CI/CD
Full Technical Reference Document

Mental model

Alembic is SQLAlchemy's version-controlled DDL migration runner that tracks a directed acyclic revision graph (alembic_version) against live PostgreSQL metadata. While alembic revision --autogenerate dramatically accelerates authoring schema diffs from Base.metadata, shipping unreviewed DDL directly into production traffic is one of the fastest ways to cause a multi-minute API outage: PostgreSQL DDL commands request heavy table locks (ACCESS EXCLUSIVE or SHARE) that queue silently behind active long queries—blocking every subsequent SELECT and INSERT until connection pools collapse. Safe production migrations combine explicit lock_timeout + retry guards, non-blocking CONCURRENTLY index builds, and Expand-and-Contract zero-downtime rollouts.

Inspect SQLAlchemy Model Metadata
Auto-generate Migration Script (alembic revision)
Apply Lock Timeout Safety Guards
Execute DDL inside Migration Transaction
Update alembic_version revision table
Conceptual teaching model synthesized from:alembic-docs,sqlalchemy-docs,postgresql-docs

Theory

PostgreSQL lock queues obey strict FIFO ordering: even if a fast metadata ALTER TABLE takes 2 ms once acquired, waiting on ACCESS EXCLUSIVE behind one slow 30-second analytics query blocks every subsequent lightweight SELECT arriving afterward because readers cannot jump ahead of a pending ACCESS EXCLUSIVE waiter.

Migration OperationLock Acquired in PostgreSQLZero-Downtime Safe PatternUnsafe Mistake to Avoid
Add Nullable Column (NULL, no volatile default)Brief ACCESS EXCLUSIVE (PG 11+ constant DEFAULT also metadata-only!)Set short lock_timeout = '2s' + statement_timeoutLetting ALTER hang indefinitely behind long report queries
Create / Drop IndexSHARE / ACCESS EXCLUSIVE (blocks writes during full scan)with op.get_context().autocommit_block(): op.create_index(..., postgresql_concurrently=True)Running standard CREATE INDEX inside Alembic's default transaction block
Add NOT NULL or CHECK ConstraintFull table scan under ACCESS EXCLUSIVE blocking all reads & writesAdd NOT VALID (SHARE UPDATE EXCLUSIVE), then VALIDATE CONSTRAINT (SHARE UPDATE EXCLUSIVE)Enforcing NOT NULL directly in one ALTER on live 100M-row tables
Rename or Drop ColumnACCESS EXCLUSIVE + old running pods immediately throw UndefinedColumnExpand-and-Contract: dual-write -> backfill -> deploy read switch -> drop lastDropping/renaming columns in the same deployment that removes code usage

Transaction vs autocommit_block() and Expand-Contract Workflows

By default, Alembic wraps every upgrade() execution inside a single SQL transaction via env.py, which ensures rollback safety on syntax or data errors—except PostgreSQL forbids CREATE INDEX CONCURRENTLY and DROP INDEX CONCURRENTLY inside explicit BEGIN...COMMIT blocks. Wrapping concurrent index creation in with op.get_context().autocommit_block(): instructs Alembic to exit the migration transaction cleanly around those non-blocking statements, and adding if_not_exists=True simplifies retrying safely if an interrupted concurrent build left an INVALID index behind (DROP INDEX CONCURRENTLY IF EXISTS ... first). Additionally, wire alembic check into CI pull requests to fail builds automatically whenever an engineer edits an ORM Mapped[] column without committing the corresponding migration revision.

python
# alembic/env.py lock-safety wrapper + concurrent index example
from sqlalchemy import text
from alembic import context, op
​
def configure_safe_migration_session(connection) -> None:
# Fail fast instead of piling up the entire application behind an ACCESS EXCLUSIVE lock queue
connection.execute(text("SET LOCAL lock_timeout = '2s'"))
connection.execute(text("SET LOCAL statement_timeout = '30s'"))
​
# Inside versions/20261125_add_idx_tokens_org_created.py:
def upgrade() -> None:
# 1. Fast metadata-only nullable column addition with lock guard
op.execute("SET LOCAL lock_timeout = '2s'")
op.add_column("api_tokens", sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True))
​
# 2. Non-blocking concurrent index build outside migration transaction block
with op.get_context().autocommit_block():
op.execute("SET lock_timeout = '2s'")
op.create_index(
"ix_api_tokens_org_expires",
"api_tokens",
["org_id", "expires_at"],
unique=False,
postgresql_concurrently=True,
if_not_exists=True,
)
​
def downgrade() -> None:
with op.get_context().autocommit_block():
op.drop_index(
"ix_api_tokens_org_expires",
table_name="api_tokens",
postgresql_concurrently=True,
if_exists=True,
)
op.drop_column("api_tokens", "expires_at")

Alternatives and trade-offs

  • Alembic + SQLAlchemy MetaData Autogeneration: Tightly synchronized with Python ORM models (alembic check), supports branching/merging migration heads across concurrent feature teams (alembic merge heads), and executes arbitrary Python/SQL backfills inside migrations; requires strict manual review of autogenerated scripts (CONCURRENTLY, NOT VALID, column renames which autogenerate sees as drop + add!).
  • Raw SQL Up/Down Runners (Flyway, Atlas, dbmate): Language-agnostic SQL-first migrations with declarative HCL/SQL linting (such as Atlas lock checks), avoiding ORM magic at the cost of manual schema synchronization against Python types.
  • Schema-per-Service Loose Coupling + Online Schema Changers: For multi-terabyte tables undergoing column-type conversions (INT -> BIGINT), physical table rewrites or shadow-table trigger swaps (pg_repack) replace plain ALTER TABLE locks entirely.

Failure modes and misconceptions

  1. Trusting autogenerate Blindly on Column Renames: Alembic cannot distinguish renaming full_name -> display_name from DROP COLUMN full_name; ADD COLUMN display_name, silently destroying production column data if applied unmodified. Always manually replace autogenerated drop/add pairs with Expand-and-Contract steps or explicit op.alter_column(..., new_column_name=...).
  2. FIFO Lock Queue Collapse Without lock_timeout: Running ALTER TABLE users ADD COLUMN ... without SET lock_timeout = '2s' during a 20-second analytical query causes the migration to wait silently while blocking every normal SELECT * FROM users behind it—taking down login across the entire app within 3 seconds.
  3. Dropping Columns While Old App Containers Still Serve Traffic: Rolling deployments overlap old and new application pods (N and N-1). If a migration runs before rollout and drops column legacy_flag, old pods still issuing SELECT legacy_flag immediately fail with 500 errors. Always ship code that stops reading the column in Release A, then run DROP COLUMN only in Release B (Contract phase).
  4. Multiple Concurrent Pods Running alembic upgrade head on Boot: Launching migrations inside every replica entrypoint races two pods against alembic_version simultaneously or fails half-started pods. Execute migrations once per deploy via a dedicated pre-deploy release job/init-container or serialize behind a PostgreSQL advisory lock.
Reflect before revealing the guide

Decision scenario

Your FastAPI service uses a 40-million-row embeddings table behind PgBouncer (session mode reserved for migrations) and deploys new rolling Kubernetes pods six times per day without maintenance windows. Configure CI with alembic check to catch model drift, run migrations strictly as a single Kubernetes pre-deploy Job (never in pod startup loops) injecting SET lock_timeout = '2s' with 5 exponential retries on lock timeout, build new indexes exclusively inside autocommit_block() using postgresql_concurrently=True, enforce NOT NULL constraints in two steps via NOT VALID + VALIDATE CONSTRAINT, and split column removals across separate Expand-and-Contract releases.

Learning outcomes

  • Explain why PostgreSQL FIFO lock queuing causes cascading outages even during millisecond metadata ALTER statements.
  • Author non-blocking Alembic migrations using lock_timeout, autocommit_block(), postgresql_concurrently=True, and NOT VALID constraint validation.
  • Apply Expand-and-Contract sequencing so rolling N/N-1 application pods never hit UndefinedColumn errors.
  • Isolate migration execution from multi-pod startup race conditions and catch schema drift via alembic check in CI.

Trade-offs

Alembic turns schema evolution into reviewable, deterministic Git artifacts tied cleanly to SQLAlchemy models, yet requires disciplined engineering guardrails around autogenerate blind spots (renames, CONCURRENTLY), explicit lock_timeout protection, and multi-phase Expand-Contract rollouts.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next