Schema Migrations

Difficulty: Intermediate

Question

How do you safely apply schema changes to a production database without downtime?

Answer

Treat schema changes as versioned, reviewed migration files run by a tool like Flyway, Liquibase, Prisma Migrate, Alembic or Rails migrations, and make every change backward compatible with the code currently running. The standard technique is expand and contract: add new structures first, deploy code that uses both, backfill data, switch reads, and only then remove the old structures in a later release.

Why production migrations are different

In development, ALTER TABLE finishes instantly. In production the table might hold 200 million rows and receive thousands of writes per second. Two things bite:

  • Locks. Many DDL statements take an ACCESS EXCLUSIVE lock in PostgreSQL. Even a fast statement can queue behind a long-running query, and every new query then queues behind it, causing an outage.
  • Mixed code versions. During a rolling deploy, old and new app instances run at the same time. If the schema only works with the new code, the old instances throw errors.

The expand and contract pattern

Renaming users.phone to users.mobile_number safely looks like this:

  1. Expand: add the nullable column mobile_number. Old code ignores it.
  2. Dual write: deploy code that writes both columns and still reads phone.
  3. Backfill: copy old values in small batches (for example 5,000 rows per transaction) to avoid long locks and replication lag.
  4. Switch reads: deploy code that reads mobile_number.
  5. Contract: in a later release, stop writing phone and drop it.

Each step is independently deployable and reversible.

Database-specific operations to know

ChangeRisky waySafer way (PostgreSQL)
Add indexCREATE INDEX blocks writesCREATE INDEX CONCURRENTLY (cannot run inside a transaction)
Add NOT NULLSET NOT NULL scans under exclusive lockAdd CHECK (col IS NOT NULL) NOT VALID, VALIDATE, then SET NOT NULL (PG 12+ skips the scan)
Add foreign keyValidates every row under lockAdd with NOT VALID, then VALIDATE CONSTRAINT separately
Add column with defaultRewrote the table before PG 11Constant defaults are metadata-only since PG 11
Change column typeUsually rewrites the tableNew column plus backfill plus switch

In MySQL 8.0, many column additions use ALGORITHM=INSTANT, and tools like gh-ost or pt-online-schema-change copy the table in the background for heavier changes.

Guard rails teams use

  • Set lock_timeout (for example '5s') in migrations so a blocked DDL fails fast instead of freezing traffic, then retry.
  • Run migrations in CI against a production-sized copy or at least a staging database.
  • Keep migrations immutable once merged; fix forward with a new migration rather than editing history.
  • Separate schema migrations from large data backfills, which should run as throttled background jobs.
  • Take a backup or confirm point-in-time recovery before destructive changes like DROP COLUMN.

Common mistakes

  • Dropping or renaming a column in the same deploy as the code change.
  • Running a huge UPDATE in one transaction, which bloats the table and lags replicas.
  • Writing a "down" migration and assuming it can undo a dropped column. Data loss is not reversible.
Expand and contract for a column rename. Each step ships separately, so old and new code always find the schema they expect.
  1. Expand: add new nullable column: Old code keeps working because it ignores the column.
  2. Deploy dual writes: New code writes both columns, still reads the old one.
  3. Backfill in batches: Copy historical values a few thousand rows at a time.
  4. Switch reads to new column: Verify data matches before flipping the read path.
  5. Contract: drop old column: Done in a later release once nothing references it.

Code examples

Safe index and NOT NULL migration in PostgreSQL

-- Fail fast instead of blocking traffic behind a lock queue
SET lock_timeout = '5s';

-- 1. Index without blocking writes (run outside a transaction)
CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_user_id_idx
  ON orders (user_id);

-- 2. Make a column NOT NULL without a long exclusive lock
ALTER TABLE orders
  ADD CONSTRAINT orders_user_id_not_null CHECK (user_id IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_user_id_not_null;  -- weaker lock
ALTER TABLE orders ALTER COLUMN user_id SET NOT NULL;            -- uses the CHECK, no scan (PG 12+)
ALTER TABLE orders DROP CONSTRAINT orders_user_id_not_null;

NOT VALID plus VALIDATE splits the expensive row check from the brief exclusive lock, and CONCURRENTLY keeps writes flowing during the index build.

Batched backfill instead of one giant UPDATE

-- Run repeatedly from a job until it updates 0 rows
UPDATE users
SET    mobile_number = phone
WHERE  id IN (
  SELECT id FROM users
  WHERE  mobile_number IS NULL AND phone IS NOT NULL
  LIMIT  5000
);

Small batches keep each transaction short, limit row locks and give replicas time to catch up.

Key points

  • Every migration must work with both the old and new application code during a rolling deploy.
  • Expand and contract: add, dual write, backfill, switch reads, drop later.
  • Use CREATE INDEX CONCURRENTLY and NOT VALID constraints in PostgreSQL to avoid long locks.
  • Set lock_timeout so DDL fails fast instead of queueing all traffic behind it.
  • Backfill large data in throttled batches, separate from the schema migration.

Common follow-up questions

  • Why can a fast ALTER TABLE still cause an outage in PostgreSQL?
  • How do you roll back a migration that has already dropped a column?
  • How would you add a NOT NULL column with a default to a 500 million row table?
  • How do gh-ost or pt-online-schema-change work in MySQL?

Interview tips

  • Walk through a concrete rename with expand and contract; a specific sequence impresses more than generic advice.
  • Mention lock queues and lock_timeout; most candidates only talk about how long a statement runs.
  • Name the migration tool you have actually used and how it tracks applied versions.

Concepts covered

Schema Migration, Expand and Contract, Zero-Downtime Deployment, Lock Timeout, Backward Compatibility

More Database Design questions