Zero-downtime database migrations (expand/contract)
Why rolling deploys mean two app versions share one schema, the expand/contract pattern for renames and type changes, backfills in batches, lock-safe DDL in Postgres, and concurrent index builds.
The problem
During a rolling deploy (ECS, Kubernetes), old and new app versions run at the same time against the same database. A migration that the old version can’t handle (a dropped or renamed column, a new NOT NULL) causes errors until the rollout finishes, and rollback becomes impossible.
db.changelog-005-rename-room-priceRenaming a column in one step is exactly the risky case. Old tasks still SELECT price while new tasks expect the new name. On a single-instance deploy it’s fine; on Fargate rolling updates it’s a brief outage.
Expand / contract (parallel change)
Renaming rooms.price to rooms.price_per_semester:
| Step | Deploy | Schema | Code |
|---|---|---|---|
| 1. Expand | Migration | ADD COLUMN price_per_semester NUMERIC(10,2) (nullable) |
Old code unaffected |
| 2. Dual write | App v2 | n/a | Writes both columns, reads old |
| 3. Backfill | Job | UPDATE ... SET price_per_semester = price WHERE price_per_semester IS NULL, in batches |
n/a |
| 4. Switch reads | App v3 | n/a | Reads new, still writes both |
| 5. Contract | App v4 + migration | Stop writing the old column, then DROP COLUMN price |
Done |
It takes more deploys, but every step is backward compatible and can be rolled back.
Postgres lock hazards
| DDL | Lock risk | Safe approach |
|---|---|---|
ADD COLUMN nullable / with constant default |
Fast (PG 11+) | ✅ |
ADD COLUMN ... NOT NULL without a default on a big table |
Rewrites or fails | Add nullable, backfill, then SET NOT NULL (PG12+ can use a validated CHECK first) |
CREATE INDEX |
Blocks writes for the whole build | CREATE INDEX CONCURRENTLY (outside a transaction; Liquibase runInTransaction: false) |
ADD FOREIGN KEY / CHECK |
Scans while locking | ADD CONSTRAINT ... NOT VALID, then VALIDATE CONSTRAINT (lighter lock) |
ALTER COLUMN TYPE |
Rewrites the table | Expand/contract with a new column |
| Any DDL behind a long query | Waits, and queues everyone behind it | SET lock_timeout = '5s' and retry |
# Liquibase changeset for a concurrent index
- changeSet:
id: 100-idx-clip-views-concurrently
author: leroy
runInTransaction: false
changes:
- sql: CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_clip_views_clip ON clip_views (clip_id);
99 Liquibase changesets on RDSAt 99 changesets against a live production RDS, IR3D is right at the point where these rules start to matter. Tables like views, ledger entries and messages grow quickly.
Related concepts you must know
- Backfill in batches (1–10k rows per transaction) with pauses, to avoid WAL spikes and replica lag.
- Tools.
pg-osc,pgroll(expand/contract automation), andsquawk(lints migrations for unsafe DDL in CI). - Make migrations part of deploys. Run them before the new app version (expand), and contract after the old version is gone.