Tutorial

Database Migration Strategies That Won't Break Production

Run schema changes safely with expand-contract migrations, backward-compatible code, and staged deployments that never lock out the old version.

On this page

  1. Introduction
  2. The Core Problem: Atomicity Across Two Systems
  3. The Expand-Contract Pattern in Practice
  4. Backward Compatibility Is the Contract
  5. Locks, Batched Backfills, and Large Tables
  6. Dropping Is a Two-Step Verification
  7. Versioning the Migrations and the Code Together
  8. Zero-Downtime Index Creation and Data-Only Migrations
  9. Conclusion

Introduction

A database migration is the most dangerous change a team makes, because it operates on the one piece of state you cannot redeploy away. A bad migration locks a table for ten minutes during peak traffic, drops a column the running code still reads, or leaves the schema and the code in incompatible states with the old version crashing and the new version unable to start. The fear is rational: many teams have a migration-gone-wrong story that ended in a restore from backup. This article covers the patterns that make migrations safe — the expand-and-contract pattern, backward compatibility, staged deployment, and the discipline of never requiring the schema and the code to change atomically.

The Core Problem: Atomicity Across Two Systems

A deployment changes the code; a migration changes the schema. These are two separate operations against two separate systems, and they cannot be made atomic. If you migrate the schema first, the old code may break against the new schema; if you deploy the code first, the new code may break against the old schema. The naive approach — migrate and deploy together, hoping nothing reads the table during the window — works on a small app with a maintenance window and fails on a 24/7 service with multiple replicas and zero downtime.

The expand-and-contract pattern resolves this by splitting every breaking change into two non-breaking migrations, separated by a deploy. You expand the schema to support both the old and new worlds, deploy the code that uses the new world, and then contract the schema to remove the old world once no code references it. At every point in the sequence, the running code is compatible with the current schema.

The Expand-Contract Pattern in Practice

Consider renaming a column from username to handle. A single migration that renames the column breaks the running code that reads username. The expand-contract sequence is:

  1. Expand (migration 1): add the new handle column, nullable, and a trigger or backfill job that keeps it in sync with username. The schema now has both columns. The old code still reads username and works.
  2. Deploy (code): deploy code that writes to both username and handle and reads from handle (falling back to username if handle is null). Both old and new code work against the schema.
  3. Backfill (data): populate handle for existing rows where it is null, in batches to avoid locking.
  4. Contract (migration 2): after confirming no code reads username, drop the username column.
-- Migration 1 (expand): add the new column, keep it in sync.
ALTER TABLE users ADD COLUMN handle VARCHAR(40);
CREATE OR REPLACE FUNCTION sync_handle() RETURNS TRIGGER AS $$
BEGIN NEW.handle := COALESCE(NEW.handle, NEW.username); RETURN NEW; END; $$ LANGUAGE plpgsql;
CREATE TRIGGER users_sync_handle BEFORE INSERT OR UPDATE ON users FOR EACH ROW EXECUTE FUNCTION sync_handle();
UPDATE users SET handle = username WHERE handle IS NULL; -- batched in practice

Between migration 1 and migration 2, the application runs with both columns present. The old version (still running during a rolling deploy) reads username; the new version reads handle. Neither breaks. Only after every old replica is gone do you run migration 2 to drop username. The breaking change is never required to be atomic with a deploy.

Backward Compatibility Is the Contract

The expand phase works only if the code you deploy is backward-compatible with the schema it finds. This means the new code must tolerate the old schema: read the new column but fall back to the old one, write to both, treat the absence of a new feature as the pre-migration state. The discipline is to never deploy code that requires a schema change that has not yet run, and never run a migration that requires code that has not yet deployed.

// New code: read handle, fall back to username. Tolerates both schemas.
function displayName(user: { handle?: string | null; username: string }): string {
  return user.handle ?? user.username;
}
// New code: write to both during the transition.
async function updateUser(id: string, handle: string) {
  await db.users.update({ where: { id }, data: { handle, username: handle } }); // write both
}

This dual-write period is the cost of zero downtime. It is temporary — you remove the fallback and the dual write in the contract phase — but while it exists, it is what lets you deploy without a maintenance window. Test the new code against both the old and the new schema in CI so the backward compatibility is verified, not assumed.

Locks, Batched Backfills, and Large Tables

A migration that rewrites a large table in a single statement locks the table for the duration. ALTER TABLE users ADD COLUMN handle VARCHAR(40) DEFAULT '' on a hundred-million-row table can lock for minutes under some databases. The safe approach is to add the column without a default (instant on most databases), then backfill the default in batches that touch a few thousand rows at a time, with a sleep between batches to hold no more than a brief lock.

async function backfillHandle(batchSize = 5000) {
  let migrated = 0;
  while (true) {
    const rows = await db.users.findMany({ where: { handle: null }, take: batchSize, orderBy: { id: "asc" } });
    if (rows.length === 0) break;
    await db.users.updateMany({ where: { id: { in: rows.map(r => r.id) } }, data: { handle: sql`username` } });
    migrated += rows.length;
    await sleep(100); // yield to reduce lock pressure
    console.log(`backfilled ${migrated} rows`);
  }
}

Run the backfill as a separate job, not in the migration transaction, so it can be paused, resumed, and monitored. A migration that runs a multi-hour backfill inside the migration tool blocks the deploy pipeline for hours; a backfill job that runs alongside the deploy lets the deploy proceed and the data catch up.

Dropping Is a Two-Step Verification

The contract phase — dropping the old column or table — is the step most often botched, because dropping is irreversible and a mistake means a restore. Before dropping, verify that nothing reads the old column. Search the codebase, yes, but also verify at runtime: log a warning (not an error) every time the old column is read, deploy, and watch the logs for a week. If the warning is silent, nothing reads it and the drop is safe; if it fires, you have found a reader you missed and the drop would have broken it.

// Instrument the fallback so you can verify it is unused before dropping.
function displayName(user: { handle?: string | null; username: string }): string {
  if (user.handle) return user.handle;
  logger.warn({ msg: "username column still read", userId: user.id }); // remove after migration 2
  return user.username;
}

Take a backup (or a snapshot, on cloud databases) immediately before the drop. If the drop breaks something, you restore from the snapshot rather than from last night’s backup, losing minutes of data rather than hours. Run destructive migrations during low-traffic windows even with all the safeguards, because a window with fewer users is a window with fewer users to affect if a safeguard fails.

Versioning the Migrations and the Code Together

Treat migrations as code: they live in version control, they are reviewed, and they are tested. Test a migration by running it against a copy of a production-shaped database (a sanitized dump, or a Testcontainer with seed data) and asserting the resulting schema and data are what you expect. A migration that passes against an empty test database can still fail against production’s data — the not-null constraint that succeeds on an empty table fails on a table with nulls. Test against data that has the nulls, the duplicates, and the edge cases production has.

Never edit a migration that has been applied to production. A migration is an append-only log of how the schema evolved; editing an applied migration creates a divergence between the migration history and the actual schema. If a migration is wrong, write a new migration that corrects it, the same way you commit a fix rather than editing history.

Zero-Downtime Index Creation and Data-Only Migrations

Adding an index to a large table is a migration that can lock the table for the duration of the build, which on a hundred-million-row table can be tens of minutes. The naive CREATE INDEX blocks writes (and, on some databases, reads) while it scans and sorts. The safe approach is a concurrent index creation, which builds the index without taking an exclusive lock, at the cost of taking longer and tolerating the table being written during the build. In Postgres, CREATE INDEX CONCURRENTLY is the incantation; it lets the application continue to read and write while the index builds, and it is the only way to add an index to a large production table without a maintenance window.

-- Locks the table for the duration — fine for small tables, dangerous for large ones.
CREATE INDEX orders_status_created ON orders (status, created_at);

-- Non-blocking: takes longer but allows concurrent reads and writes.
CREATE INDEX CONCURRENTLY orders_status_created ON orders (status, created_at);

A concurrently-built index has a caveat: if the build fails (a unique violation, a disk-full, an interruption), it leaves an invalid index that the database maintains on every write but never uses for reads. Detect and clean up invalid indexes after a concurrent creation, because an invalid index is pure write overhead with no read benefit. CREATE INDEX CONCURRENTLY also cannot run inside a transaction, so it must be a standalone migration, not bundled with other changes. These constraints are the price of non-blocking index creation, and they are worth paying to keep the table online.

Distinguish schema migrations (changes to the structure) from data migrations (changes to the data within the existing structure). A schema migration adds a column or an index; a data migration backfills a value, splits a field, or merges rows. Data migrations are the ones that can take hours on a large table, and they should never run inside the migration tool’s transaction — they should run as a separate, resumable, batched job that can be paused and resumed without losing progress. Track the job’s progress (the last processed id, the number of rows updated) in a control table, so a restart resumes from where it stopped rather than starting over.

async function dataMigration(controlKey: string) {
  const state = await control.get(controlKey) ?? { lastId: "0", done: false };
  if (state.done) return;
  while (true) {
    const batch = await db.users.findMany({ where: { id: { gt: state.lastId } }, take: 5000, orderBy: { id: "asc" } });
    if (batch.length === 0) { await control.set(controlKey, { ...state, done: true }); break; }
    await db.users.updateMany({ where: { id: { in: batch.map(b => b.id) } }, data: { searchVector: computeVector(batch) } });
    state.lastId = batch[batch.length - 1].id;
    await control.set(controlKey, state); // checkpoint progress
    await sleep(100); // yield to reduce load
  }
}

The checkpoint is what makes the data migration safe to pause and resume: if the job is killed at 40%, the control table records the last processed id, and a restart picks up from there. Run the data migration with a concurrency and batch size tuned to the database’s capacity, monitoring the replication lag and the query latency so the backfill does not degrade the production traffic. A data migration that runs at full throttle locks rows and inflates latency; one that runs in modest batches with a yield between them is invisible to the users.

The expand-and-contract pattern from the main article applies to data migrations too: write the new data alongside the old during the expand phase, deploy code that reads the new data, and remove the old data during the contract phase. The data migration is the backfill that populates the new field for existing rows; the deploy is the code that switches to reading it; the contract is the cleanup that removes the old. Each step is independently reversible, and the whole change happens without a moment where the schema and the code disagree.

Conclusion

Safe database migrations are the product of the expand-and-contract pattern, backward-compatible code, batched backfills, and verified drops. Expand the schema to support both worlds, deploy code that tolerates both, backfill the data in batches, verify the old world is unused, and contract the schema to remove it. At every step the running code is compatible with the current schema, so there is no atomicity requirement and no maintenance window. The discipline is patience: a rename that takes one statement in development takes two migrations and a deploy in production, and that patience is what keeps the table online and the users unaware.

Related Examples