Writing
Fullstack English

Database Migrations Without the Maintenance Window

Expand-migrate-contract: shipping schema changes to a live database while old and new code run side by side.

  • Published
  • 1 min read

During a deploy, old and new code run simultaneously against the same database. Any migration that breaks either one causes the 2-minute outage everyone calls “the deploy being flaky”. The cure is a pattern, not a tool: expand, migrate, contract.

Renaming a column, the safe way

Goal: phone becomes phone_number.

  1. Expand - add phone_number, nullable. Deploy code that writes both, reads old.
  2. Migrate - backfill in batches (never one giant UPDATE that locks the table):
sql
UPDATE users SET phone_number = phone
WHERE id IN (SELECT id FROM users WHERE phone_number IS NULL LIMIT 5000);
  1. Deploy code that reads new, still writes both. Verify.
  2. Contract - stop writing old, then a release later, drop phone.

Four boring steps instead of one exciting one.

The other classics

  • Adding an index: CREATE INDEX CONCURRENTLY (Postgres) - or you just locked writes on your biggest table.
  • Adding NOT NULL: backfill first, add CHECK (col IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT, then SET NOT NULL - Postgres 12+ uses the validated check and skips the full-table scan.
  • Never ship a migration and the code that requires it in the same deploy step.

A structural engineer never removes a load-bearing column before the new one carries load. Same building, same rule.