Database migration
The golden rule: old code and new code both run during a deploy
Rolling deploys mean the old version of the app keeps running while (and after) the migration runs. Every migration must work with both versions. That single rule explains every pattern below.
Expand / contract
Never rename or change a column in one step. Do it across deploys:
| Step | Deploy | Example: rename users.fullname -> users.display_name |
|---|---|---|
| 1. Expand | migration | Add nullable display_name |
| 2. Dual write | app | Write both columns; read the old one |
| 3. Backfill | job | Copy old -> new in batches |
| 4. Switch reads | app | Read the new column (still writing both) |
| 5. Stop old writes | app | Write only the new column |
| 6. Contract | migration | Drop fullname (after no code references it) |
The same shape works for type changes, splitting tables and moving data between services.
PostgreSQL operations: what is safe
| Operation | Risk | Safer way |
|---|---|---|
ADD COLUMN nullable, no default |
Fast (metadata only) | Fine |
ADD COLUMN ... DEFAULT <constant> |
Fast on PG 11+ (no rewrite) | Fine on 11+; on older versions add column, then set default, then backfill |
ADD COLUMN ... DEFAULT <volatile> (e.g. random(), clock_timestamp()) |
Rewrites the table under an exclusive lock | Add nullable, backfill in batches, then set default |
ADD COLUMN ... NOT NULL without default |
Fails on non-empty tables | Add nullable, backfill, then enforce NOT NULL (below) |
ALTER COLUMN ... SET NOT NULL |
Full table scan under ACCESS EXCLUSIVE lock |
Add CHECK (col IS NOT NULL) NOT VALID, VALIDATE CONSTRAINT, then SET NOT NULL (PG 12+ uses the valid check to skip the scan), then drop the check |
ALTER COLUMN ... TYPE |
Usually rewrites table + indexes under exclusive lock | New column + backfill + switch (expand/contract). Some changes are metadata-only (e.g. increasing varchar(n) length, varchar -> text) |
CREATE INDEX |
Blocks writes for the whole build | CREATE INDEX CONCURRENTLY (cannot run inside a transaction block) |
DROP INDEX |
Exclusive lock | DROP INDEX CONCURRENTLY |
ADD FOREIGN KEY |
Validates all rows while holding locks on both tables | ADD CONSTRAINT ... NOT VALID, then VALIDATE CONSTRAINT separately |
ADD CHECK |
Full scan under lock | NOT VALID then VALIDATE CONSTRAINT |
ADD UNIQUE / primary key |
Builds an index under lock | CREATE UNIQUE INDEX CONCURRENTLY, then ADD CONSTRAINT ... UNIQUE USING INDEX |
RENAME COLUMN/TABLE |
Instant, but breaks running old code | Expand/contract, or a view for compatibility |
DROP COLUMN |
Fast, but breaks old code that selects it | Remove all code references first (and ORM column caches), deploy, then drop |
| Any DDL | Waits for the lock behind long-running queries, and blocks everyone queued behind it | SET lock_timeout = '5s'; and retry; keep transactions short |
Backfills
- Batch by primary key ranges (
WHERE id > $last AND id <= $last + 5000), commit per batch, sleep briefly if replicas lag. - Make it idempotent and resumable (re-running must be safe).
- Run it as a job or script, not inside the schema migration transaction.
- Measure first:
SELECT count(*)(orreltuplesestimate for huge tables) to size batches and runtime.
Lint the SQL
python3 scripts/migration_lint.py migrations/20261201_add_display_name.sql
python3 scripts/migration_lint.py migrations/ # every .sql file
Flags: non-concurrent index creation/drop, CONCURRENTLY inside BEGIN, SET NOT NULL, NOT NULL column without default, volatile defaults, column type changes, foreign keys/checks without NOT VALID, unique constraints not using an index, renames, DROP COLUMN/TABLE, and DDL without a lock_timeout. Exit code 1 on errors. For framework migrations (Django, Rails, Alembic, Prisma, Knex), lint the generated SQL (sqlmigrate, --sql, migrate diff --script, etc.).
Every migration PR includes
- The SQL that will actually run.
- Estimated table size and expected lock/duration.
- Deploy order (migration before or after the app change) and why both versions work.
- Rollback: the down migration, or why it is forward-only and what the recovery plan is.
- Backfill plan if any, with batch size.