Lesson 17 of 59Data and storage
Database Migrations with Alembic
Set up Alembic, review autogenerated migrations, move data safely, and run migrations in CI and on deploy without locking production.
Your models will change every few weeks: a new column, a new table, a field that becomes required. On your laptop you could drop the database and recreate it, but production holds real customers' data and has to keep serving requests while it changes. Migrations are versioned scripts that move a database from one schema to the next, in order, on every environment. The last lesson ran four Alembic commands. This one shows how Alembic actually works, what autogenerate gets wrong, and how teams ship schema changes without downtime.
Why migrations
Without migrations, schema changes happen by hand: someone runs an ALTER TABLE in production and hopes staging and every developer's laptop get the same change. That falls apart fast. Migrations give you:
- History in git. Every schema change is a reviewed file next to the code that needs it.
- Repeatability. A new developer, a CI job and production all reach the same schema by running the same scripts.
- A known state. The database records which migration it is on, so the tool knows exactly what still needs to run.
Alembic is the migration tool for SQLAlchemy, written by the same author. Django has its own built-in system that works the same way.
Setting up Alembic
uv add alembicuv run alembic init alembic- my-api/
- alembic.iniconfig: script location, logging, a default database URL
- alembic/
- env.pyruns on every command: connects and sets target_metadata
- script.py.makotemplate for new migration files
- versions/your migrations live here, one file each
- app/
- models.pyBase and your models
- pyproject.toml
Two edits in env.py connect Alembic to your app. First, point target_metadata at your models so autogenerate can compare them with the database. Second, take the database URL from your settings instead of hardcoding it in alembic.ini:
from app.config import get_settings
from app.models import Base # importing models registers every table on Base.metadata
config = context.config
config.set_main_option("sqlalchemy.url", get_settings().database_url)
target_metadata = Base.metadataTwo details trip people up here. set_main_option goes through Python's configparser, so a % in the URL (common in URL-encoded passwords) must be doubled to %%. And if your app uses an async driver like asyncpg, start with alembic init -t async alembic instead, which generates an env.py that runs migrations through an async engine. The migration files themselves look the same either way.
If you forget to import a model module, its tables are missing from Base.metadata, and autogenerate will happily suggest dropping them. Make sure app.models imports every model.
One more setup step that seniors insist on: give constraints predictable names. Postgres invents names for unnamed constraints, and a later migration cannot reliably drop a constraint whose name it does not know.
from sqlalchemy import MetaData
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
metadata = MetaData(naming_convention={
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
})Autogenerate, then review
Add a column to the model, then ask Alembic to write the migration:
uv run alembic revision --autogenerate -m "add due_at to todos""""add due_at to todos"""
import sqlalchemy as sa
from alembic import op
revision = "3f2a9c1b7d10"
down_revision = "a81e4f0c2b55"
def upgrade() -> None:
op.add_column("todos", sa.Column("due_at", sa.DateTime(timezone=True), nullable=True))
op.create_index("ix_todos_due_at", "todos", ["due_at"])
def downgrade() -> None:
op.drop_index("ix_todos_due_at", table_name="todos")
op.drop_column("todos", "due_at")Each file has a revision id and a down_revision pointing at its parent, which forms a chain. upgrade() moves forward, downgrade() reverses it. Alembic stores the current revision in a one-row table called alembic_version.
Autogenerate compares your models with the live database and writes its best guess. It is a draft, not a finished migration. It reliably detects new and removed tables and columns, nullability changes, indexes, unique constraints and foreign keys. It does not detect renames, and it misses or mishandles some details such as server default changes and Postgres enum values. Always read the file before committing it.
title to name and run autogenerate. What does the generated migration most likely contain?Running migrations
uv run alembic upgrade head # apply everything not yet applieduv run alembic downgrade -1 # undo the most recent migrationuv run alembic current # which revision is this database on?uv run alembic history # the chain of revisionsuv run alembic upgrade head --sql # print the SQL instead of running ithead means the newest revision. The --sql flag ("offline mode") is useful when a DBA wants to review the exact SQL before it touches production.
When two branches each add a migration from the same parent, merging both gives you two heads, and upgrade head refuses to guess. Run alembic heads to see them and alembic merge heads -m "merge" to create a small migration that joins them. Many teams avoid this by rebasing and regenerating before merging.
Put the life of a schema change in order.
- Tap the steps below in the right order.
Adopting Alembic on an existing database
Many teams add Alembic to a project whose database already exists, created by hand or by Base.metadata.create_all(). Running upgrade head would try to create tables that are already there. Instead, generate a first migration that describes the current schema (autogenerate against an empty database gives you that), check it matches production, and then run alembic stamp head on the existing database. stamp only writes the revision id into alembic_version without running anything, telling Alembic "this database is already at this point". From then on, every change goes through migrations, and create_all() should be deleted from the app so nothing creates tables behind Alembic's back.
Data migrations
Sometimes the schema change needs the data to change too. Say you split name into first_name and last_name. Alembic migrations can run SQL with op.execute:
def upgrade() -> None:
op.add_column("users", sa.Column("first_name", sa.Text(), nullable=True))
op.add_column("users", sa.Column("last_name", sa.Text(), nullable=True))
op.execute("""
UPDATE users
SET first_name = split_part(name, ' ', 1),
last_name = substr(name, length(split_part(name, ' ', 1)) + 2)
""")Two rules. First, do not import your app's models in a migration. The model reflects today's code, while the migration must work exactly as written forever, even years later when the model looks different. Use plain SQL, or lightweight sa.table(...) definitions inside the migration file. Second, for big tables, update in batches (for example 10,000 ids at a time) so one giant UPDATE does not lock the table and bloat it for minutes.
Pitfalls that cause outages
Most migration incidents come from locks. Many ALTER TABLE statements take a strong lock on the table. While it is held, nobody can read or write it. Worse, if a long-running query is already using the table, your ALTER waits in line, and every new query queues behind your ALTER. A migration that should take 5 milliseconds can freeze the site.
- Set a lock timeout. Run
SET lock_timeout = '5s'at the start of a migration so it fails fast instead of queueing everything. Then retry when the database is quieter. - Build indexes concurrently.
CREATE INDEX CONCURRENTLYdoes not block writes, but it cannot run inside a transaction. In Alembic, wrap it inwith op.get_context().autocommit_block():and passpostgresql_concurrently=Truetoop.create_index. - Adding a required column whose values must be computed needs care. Use expand and contract: add the column as nullable, deploy code that writes it, backfill old rows in batches, then add
NOT NULLin a later migration. - Renames and drops break running code. During a deploy, old and new versions of your app run side by side. If a migration drops a column the old version still reads, the old version errors until it is replaced. Stop using a column in one release and drop it in the next.
tenant_id column on a 50-million-row orders table with zero downtime. What is the safest plan?Migrations in CI and on deploy
In CI, start a fresh Postgres service, run alembic upgrade head from an empty database, then run your tests against it. That proves the whole chain still works. Add alembic check, which fails if your models have changes with no migration, so nobody merges a model change and forgets the file. Some teams also run downgrade base and upgrade head again to keep downgrades honest.
On deploy, run migrations once, as their own step, before the new code takes traffic:
CI tests the full migration chain on a fresh database, then builds one image containing both the app and its migrations.
Do not run alembic upgrade head inside the app's startup code. With four workers on three servers, twelve processes race to migrate the same database at once.
Match each command or setting to its job.
- migration
- A versioned script with
upgrade()anddowngrade()that changes the schema one step. - revision
- A migration's id. Each file points to its parent with
down_revision, forming a chain. - autogenerate
- Alembic's draft of a migration from the difference between your models and the database. Always review it.
- head
- The newest revision.
alembic upgrade headapplies everything up to it. - data migration
- A migration that changes rows, not just schema. Uses SQL, never the app's current models.
- expand and contract
- Ship a schema change in small backward-compatible steps: add, backfill, switch, then remove.
- lock_timeout
- A Postgres setting that makes a statement give up if it cannot get its lock in time.