← All articles
· 2 min read

Zero-downtime Postgres migrations with expand and contract

You almost never need a maintenance window. The trick is to split every schema change into an additive step and a cleanup step, deployed separately.

The phrase "we need a maintenance window for the migration" is usually a sign that the migration was written as one step when it should have been two. The pattern that removes the window is expand and contract: make every schema change additive first, then clean up in a later deploy once no running code depends on the old shape.

Say you want to rename users.email to users.email_address. Done in one statement, old app instances break the instant the column disappears. Done in phases, nothing breaks.

01_expand.sql
-- Phase 1 (expand): add the new column, nullable, no rewrite.
ALTER TABLE users ADD COLUMN email_address text;

-- Backfill in batches so you never hold a long lock.
UPDATE users SET email_address = email
WHERE email_address IS NULL AND id BETWEEN $1 AND $2;

Deploy code that writes to both columns and reads from the new one. Let it run. When the backfill is complete and every instance is on the new code, you contract.

02_contract.sql
-- Phase 2 (contract): now nothing reads the old column.
ALTER TABLE users ALTER COLUMN email_address SET NOT NULL;
ALTER TABLE users DROP COLUMN email;

Two more rules keep this safe on Postgres specifically. First, adding a column with a volatile default rewrites the whole table on older versions, so add the column nullable and backfill yourself. Second, creating an index on a live table takes a lock unless you ask it not to:

CREATE INDEX CONCURRENTLY idx_users_email_address
    ON users (email_address);

CONCURRENTLY cannot run inside a transaction block, so it gets its own migration. It is slower and can fail halfway, leaving an invalid index you drop and retry — a fair price for not locking writes on a busy table.