← Lessons

quiz vs the machine

Gold1520

Databases

Database Migrations Zero Downtime

Schema changes must stay compatible with both old and new code so deploys need no outage.

5 min read · core · beat Gold to climb

Why Naive Migrations Break

During a rolling deploy, old and new application code run at the same time. A migration that renames or drops a column in one step breaks whichever version does not match. Zero downtime migrations avoid this by making every step compatible with both versions.

The Expand and Contract Pattern

  • Expand: add the new structure without removing the old. Add a new column, keep the old one.
  • Migrate: backfill data and deploy code that writes both old and new.
  • Contract: once all code uses the new structure, remove the old one in a later release.

Concrete Example Renaming a Column

  • Add the new column.
  • Deploy code writing to both columns and reading the new one.
  • Backfill existing rows.
  • Drop the old column after the next deploy.

Operational Hazards

  • Some changes take a table lock; adding a non null column with a default once required a full rewrite on older engines.
  • Backfills should run in batches to avoid long transactions and replication lag.

Key idea

Zero downtime migrations use expand and contract so each step stays compatible with both old and new code, deferring removals to a later release.

Check yourself

Answer to earn rating on the learn ladder.

1. Why does renaming a column in one step risk downtime?

2. What does the expand phase do?