Database, chapter 04 of 05
Zero-Downtime Migrations
Changing a live schema without downtime: the expand and contract pattern, safe backfills, lock-aware DDL, and the order to ship code and migrations in.
During a deploy, old and new versions of the code run against the same database at the same time: for seconds with a rolling deploy, longer with a canary, and indefinitely if you roll back. Every migration has to work with both. That one constraint rules out most "simple" changes, like renaming a column in a single step, and it's why schema changes deserve their own discipline.
A maintenance window avoids the problem by taking the product down, which means scheduling around traffic and batching changes into risky releases. With continuous deployment there's no window to schedule into, so migrations have to be safe on a live system.
Expand and Contract#
Every breaking schema change is split into steps that are each backward compatible, a pattern also known as parallel change:
- Expand. Add the new structure alongside the old one. Nothing reads it yet.
- Write both. Deploy code that writes to the old and the new.
- Backfill. Copy existing data into the new structure.
- Read new. Deploy code that reads from the new structure.
- Stop writing old. Deploy code that no longer touches the old structure.
- Contract. Drop the old structure.
Each step is its own deploy, and each can be rolled back without undoing the one before. At no point is there a version of the code the current schema can't serve. It costs more deploys than a one-shot change, and in exchange none of them can take the site down.
Example: Renaming a Column
Renaming users.name to users.full_name:
-- 1. Expand
ALTER TABLE users ADD COLUMN full_name TEXT;
-- 3. Backfill, one batch at a time until no rows are left (see below)
UPDATE users SET full_name = name
WHERE id IN (SELECT id FROM users WHERE full_name IS NULL LIMIT 1000);
-- 6. Contract, once no code reads or writes "name"
ALTER TABLE users DROP COLUMN name;
A single ALTER TABLE users RENAME COLUMN takes effect instantly, and every old instance still running fails on its next query until it's replaced.
Backfills#
- Batch it. Hundreds to low thousands of rows per batch, each in its own transaction, with a short pause between. One
UPDATEacross 50 million rows holds row locks for its whole duration, floods replicas with write-ahead log, and leaves a table full of dead tuples for vacuum. - Make it resumable. Key off
WHERE new_column IS NULLor an ID cursor, so a backfill interrupted at 60% resumes at 60%, not zero. - Run it as a job, not a migration. Schema migrations should finish in seconds, inside the deploy. Data work that takes hours runs separately, with progress you can watch and a way to pause it.
- Verify before you contract. Count the rows that still differ; drop only at zero. Dropping a column with data you didn't copy is the one step here you can't roll back.
Lock-Aware DDL#
Some DDL takes an ACCESS EXCLUSIVE lock that blocks every read and write on the table while it runs, so a statement that's instant in development can stall production for minutes. On Postgres:
| Change | Safe approach |
|---|---|
| Add an index | CREATE INDEX CONCURRENTLY (slower, and can't run in a transaction, but doesn't block writes) |
| Add a foreign key | ADD CONSTRAINT ... NOT VALID, then VALIDATE CONSTRAINT separately |
Add a CHECK |
The same: ADD CONSTRAINT ... CHECK (...) NOT VALID, then validate. A CHECK written inline on a new column scans the whole table too; an inline REFERENCES on a new column doesn't, because every value is null |
| Add a unique constraint | CREATE UNIQUE INDEX CONCURRENTLY, then ADD CONSTRAINT ... UNIQUE USING INDEX, which attaches the finished index. To widen a key, build the new index first and swap the constraint in one ALTER, so the old key holds until the new one does |
| Add an exclusion constraint | No safe form: NOT VALID covers only foreign keys, CHECK and not-null, and USING INDEX only unique and primary keys. Add it while the table is small, or in a maintenance window |
Add NOT NULL |
Add a CHECK (col IS NOT NULL) NOT VALID, validate it, then SET NOT NULL, which skips the table scan once a valid check proves there are no nulls. Postgres 18 can also add the NOT NULL constraint itself as NOT VALID: ADD CONSTRAINT t_c_not_null NOT NULL c NOT VALID, then VALIDATE CONSTRAINT after the backfill |
| Add a column with a default | Safe on Postgres 11+ when the default is non-volatile: it's stored as metadata, not written to every row |
| Change a column's type | Usually rewrites the table. Use expand and contract with a new column |
NOT VALID is the general trick: add the constraint for new rows immediately, under a brief lock, and validate existing rows later under a lock that doesn't block writes.
Set a lock_timeout of a few seconds on migration sessions. The dangerous case isn't the DDL itself; it's DDL waiting for a lock behind one long-running query, while every other query on the table queues behind it, so a 10-second report becomes a site-wide stall. With a timeout, the migration fails fast and retries instead.
Shipping Order#
- Migrations run before the code that needs them, as their own pipeline step, so the expanded schema is in place before any code relies on it.
- No deploy depends on migration and code landing at the same instant. Either can be ahead of the other and nothing breaks, which is what makes the deploy safe to roll back.
- Destructive steps ship last and alone. A
DROPis never bundled with other changes, and waits at least one full deploy cycle after the last code that used the column, so a rollback never lands on code that expects a column that's gone.
Financial Tables#
On ledger and payment tables the bar is higher. Backfills never modify existing financial rows in place: those rows are append-only, and an in-place backfill is exactly the untraceable edit the ledger exists to prevent. New derived columns are filled from the history, and reconciliation runs before and after to prove no balance changed.
References#
Reference
- PostgreSQL: CREATE INDEX, building indexes
CONCURRENTLY - PostgreSQL: ALTER TABLE,
NOT VALIDand which constraints allow it,VALIDATE CONSTRAINT,UNIQUE USING INDEX, skipped scans forSET NOT NULL, and non-volatile defaults - PostgreSQL: Explicit locking, which DDL takes which lock
- PostgreSQL: Client connection defaults,
lock_timeout
In practice
- Martin Fowler: Parallel Change, the expand and contract pattern
- Stripe: Online migrations at scale, dual writes and backfills on live data
- strong_migrations, a catalog of unsafe migrations and safe alternatives