Zero-Downtime Schema Migrations
Run versioned database migrations safely with expand/contract, batched backfills, immutable migration history, and realistic rollback plans.
TL;DR
Treat database schema changes as backward-compatible steps, never single-deploy swaps. Use versioned migrations, apply expand/contract so old and new app code coexist during rollouts, backfill in small batches, never edit an applied migration, and plan for forward-only fixes instead of destructive rollbacks.
Why it exists
During a rolling deploy, old pods and new pods share the same database for seconds or minutes. If a migration renames or drops a column before old pods drain, live requests crash with column does not exist—and rolling back the app code won't restore dropped data.
Mental model
Always keep the database compatible with both the previous release (N-1) and the next release (N) until N-1 is completely gone.
Do it
1. Versioned migrations (immutable history)
Store every DDL change as a timestamped or sequential file (0001_init.sql, 0002_add_user_handle.sql) tracked in a _migrations table. Once a migration is merged and applied to any shared environment, never edit it—create a new forward migration (0003_...) to fix mistakes.
2. Expand / contract for zero downtime
Suppose you want to rename users.full_name to users.display_name:
-- Deploy 1 (Expand): safe alongside old app code (not run)
ALTER TABLE users ADD COLUMN display_name TEXT;
-- Deploy 2 (Backfill in small batches, e.g., 1,000 rows per tx, not run)
UPDATE users
SET display_name = full_name
WHERE id IN (
SELECT id FROM users
WHERE display_name IS NULL AND full_name IS NOT NULL
LIMIT 1000
);
-- Deploy 3 (Enforce without long table lock, Postgres 12+, not run)
ALTER TABLE users ADD CONSTRAINT chk_display_name_nn
CHECK (display_name IS NOT NULL) NOT VALID;
ALTER TABLE users VALIDATE CONSTRAINT chk_display_name_nn;
-- Deploy 4 (Contract, only after old app instances are gone, not run)
ALTER TABLE users DROP COLUMN full_name;3. Rollback reality
As covered in Deployment & Rollback Strategies, rolling back application containers is fast, but rolling back a database migration is often unsafe:
- If Deploy 1 only added a nullable column or
CONCURRENTLYindex, you can roll back the app code without touching the DB at all. - Never run
down.sqlscripts thatDROP TABLEorDROP COLUMNin production—you will destroy data written after the deploy. Fix forward with a new migration instead.
When you DON'T need this
- Pre-launch prototypes with zero real users: When you can afford a 5-second maintenance window or
db push, multi-deploy expand/contract is unnecessary ceremony. - Static sites with no database: This site has no runtime database and ships only static assets.
- Cost / complexity trade-off: Expand/contract splits one conceptual rename into 2–4 smaller PRs and deploys. In return, you get zero-downtime rollouts and painless code rollbacks.
Gotchas
lock_timeoutomitted onALTER TABLE: Even fast metadata-onlyALTER TABLEcommands queue behind a long-runningSELECTand block every subsequent query until you setSET lock_timeout = '2s';.CREATE INDEXwithoutCONCURRENTLY: StandardCREATE INDEXblocks all writes on the table for the entire build duration.- Single-transaction backfills: Updating 5 million rows in one
UPDATEholds row locks, bloats WAL, and can stall replicas.
Production checklist
- Migrations run with a dedicated
lock_timeout(e.g.,2s) andstatement_timeout. - New indexes use
CREATE INDEX CONCURRENTLY(outside a transaction block). - Backfills run in bounded batches (500–5,000 rows) with short pauses between batches.
- Destructive drops (
DROP COLUMN,DROP TABLE) happen only in a separate follow-up deploy after old code is retired. - Applied migration files are treated as append-only and never edited.
Check yourself
Check Yourself
1. You want to rename column total to total_cents on a live production table with zero downtime. What is the safest first migration?
2. Why should a PostgreSQL migration set lock_timeout before running ALTER TABLE?
Sources
Related Notes
ORM Pitfalls & When to Drop to SQL
Spot and fix N+1 queries, compare eager vs lazy loading, use raw-query escape hatches safely without SQL injection, and know when plain SQL wins.
Error Handling & Structured Logging
Balance errors-as-values vs exceptions in TypeScript, centralize error boundaries, emit JSON logs with correlation IDs, redact secrets/PII, and fail closed.