Topic 3 of 5 · 6 min read
Zero-downtime schema migrations
Goal: Split a breaking schema change into expand, backfill and contract steps that keep the running app working after each step.
Change a live schema in small steps where the old and the new application version both keep working after every step. The pattern is called expand and contract.
Check yourself · 1 of 3
What is the first step when replacing a column that the running app reads?
Why it matters
During a deploy, old and new code run at the same time against one database. If a migration renames a column in one step, the old code breaks the moment it runs. Some statements also hold a lock that blocks every other query on the table until they finish. An agent that writes ALTER TABLE ... RENAME COLUMN in one file has produced a correct migration and an outage.
How to do it
Example: replace users.name with first_name and last_name.
- Expand. Add the new nullable columns. Nothing reads them yet, so nothing can break. Deploy.
- Dual write. Ship app code that writes both the old and new columns. Deploy.
- Backfill. Copy existing rows in batches, for example 5,000 rows per run with a short pause, so no single statement runs for minutes or holds long locks. Make it safe to re-run.
- Switch reads. Ship code that reads the new columns. Verify, and keep the old column for a while.
- Contract. Once no running version uses the old column, drop it in its own migration.
Safe habits for each step:
- Add columns as nullable or with a constant default. Check your PostgreSQL version's notes in the
ALTER TABLEdocs for which forms rewrite the table. - Build indexes with
CREATE INDEX CONCURRENTLY, which does not block writes, and cannot run inside a transaction block. - Add a foreign key or check as
NOT VALID, then runVALIDATE CONSTRAINTseparately, so the long scan does not hold the strong lock. - Set a
lock_timeoutso a migration that cannot get its lock fails quickly instead of queuing behind a long query and blocking everyone after it. - Write the way back: each step has a down path, or you state that it is not reversible, as with a dropped column.
Before and after
-- Weak: one step, locks the table, breaks the old app
ALTER TABLE users RENAME COLUMN name TO full_name;
CREATE INDEX idx_users_email ON users (email);
-- Strong: separate migrations
SET lock_timeout = '3s';
ALTER TABLE users ADD COLUMN full_name text;
-- later, outside a transaction:
CREATE INDEX CONCURRENTLY idx_users_email ON users (email);
What goes wrong
- One-shot backfill.
UPDATE users SET ...over millions of rows runs for minutes and bloats the table. - Contract too early. Dropping the old column while an older app version is still running throws errors.
- No lock timeout. One blocked
ALTERqueues all later queries behind it. - Untested on real size. A migration that takes a second on a 1,000-row dev table can take an hour on production.
Examples
Safe rename in five migrations
Add full_name, deploy dual-write code, backfill in batches of 5,000, switch reads to full_name, and only then drop name in a separate migration after one full release cycle.
Reviewing an agent's migration
The agent returns one file with a rename, a NOT NULL addition and a plain CREATE INDEX. Ask three things: does the previous app version still work after it runs, which statements take strong locks, and what is the roll-back? Then split it into steps.
Key points
- Expand first, backfill in batches, switch reads, and contract last, so both app versions work after each step.
- A rename or a type change in one step breaks the running old version during a deploy.
- Build indexes with CREATE INDEX CONCURRENTLY and add constraints as NOT VALID, then validate separately.
- Set a lock_timeout so a migration fails fast instead of queuing every other query behind it.
- Every migration states its way back, or says plainly that it cannot be reversed.
Common mistakes
- Renaming or dropping a column in the same release that stops using it.
- Running one huge UPDATE for the backfill instead of batches.
- Creating an index without CONCURRENTLY on a busy table.
- Testing the migration only on a tiny development database.
Check yourself · 2 of 3
Why backfill a large table in batches rather than with one UPDATE?
Check yourself · 3 of 3
A migration builds an index on a busy table. What makes it safe for writers?
Practice items, not counted towards your mastery.
Start here
- PostgreSQL: Data definition (opens in a new tab)DocsFree
How tables, constraints, row security and schema changes are declared in PostgreSQL.
- PostgreSQL: Constraints (opens in a new tab)DocsFree
Exact behaviour of CHECK, NOT NULL, UNIQUE, primary and foreign keys and their ON DELETE actions.
- PostgreSQL: ALTER TABLE (opens in a new tab)DocsFree
Which ALTER TABLE forms rewrite the table or take strong locks, and the NOT VALID option.
More for this topic
- strong_migrations: catch unsafe migrations in development (opens in a new tab)ToolFree
A catalogue of unsafe migrations and the safer step-by-step alternative for each.
- Evolutionary Database Design (Martin Fowler) (opens in a new tab)ArticleFree
The case for small, reversible schema changes shipped alongside application code.