Zero-Downtime Schema Migrations
- Plan a breaking schema change (rename, type change, split) as a sequence of backward-compatible expand/contract steps
- Predict which DDL statements rewrite tables or take blocking locks in Postgres and MySQL, and use the safe alternatives
- Add indexes, constraints and
NOT NULLcolumns to large live tables without blocking traffic - Run resumable, throttled backfills
- Choose between dual writes, triggers and CDC when moving data, and verify the result
- Test migrations and define rollback points before running them in production
TL;DR
- During a rolling deploy, old and new application versions run at the same time. Every schema state must work with both. That rules out one-step renames, type changes and drops.
- Expand/contract (parallel change): add the new structure → write to both → backfill → switch reads → stop writing the old → remove it. Each step is separately deployable and reversible until the final contract.
- Most risk is locks, not duration: a 5 ms
ALTER TABLEthat waits behind a long query blocks every query behind it. Always setlock_timeoutand retry. - Postgres:
CREATE INDEX CONCURRENTLY; constraints withNOT VALIDthenVALIDATE;SET NOT NULLvia a validatedCHECK(12+); constant defaults are metadata-only (11+); type changes usually rewrite. - MySQL: online DDL (
ALGORITHM=INSTANT/INPLACE,LOCK=NONE) where supported; otherwise gh-ost or pt-online-schema-change. Watch metadata locks and replica lag. - Backfill in small, idempotent, resumable batches, throttled by replica lag and load. Never one giant
UPDATE. - Rollback: roll forward when you can; keep the old structure until the new one is proven; the contract step is the point of no return, so take it late and deliberately.
Why it matters
Banks and large e-commerce platforms rarely get maintenance windows any more: instant payments run 24/7, and every minute of checkout downtime during a campaign is measurable revenue. At the same time, their schemas keep changing: new regulatory fields, currency support, splitting a monolith's tables into services. A migration that locks the payment table for two minutes is a production incident, and a migration that drops a column still read by an old pod produces errors until rollback. Architects are expected to design change processes that make such incidents structurally unlikely, not merely to "be careful".
Core concepts
Why naive migrations break
Two independent problems:
- Compatibility. Deploys are rolling: for minutes (or, with canaries, hours) version N and N+1 both serve traffic, and N may be rolled back. If the migration renames
amounttototal_minor, version N fails immediately. If N+1 writes a new required column, N's inserts fail. - Locking and rewrites. Many DDL statements take an exclusive table lock, and some rewrite the whole table while holding it. Even a metadata-only change needs the lock briefly, and acquiring it requires waiting for every running transaction on the table.
Expand/contract
The breaking change "rename orders.amount numeric to orders.total_minor bigint (minor units)" becomes:
| Step | Schema | Application | Reversible? |
|---|---|---|---|
| 1 Expand | ADD COLUMN total_minor bigint (nullable) | Unchanged | Yes: drop the column |
| 2 Dual write | — | v2 writes amount and total_minor (or a trigger syncs them) | Yes: deploy v1 |
| 3 Backfill | Batched UPDATE of old rows | — | Yes |
| 4 Verify | CHECK … NOT VALID, VALIDATE, SET NOT NULL; compare columns | — | Yes |
| 5 Switch reads | — | v3 reads total_minor behind a feature flag | Yes: flip the flag |
| 6 Stop old writes | Make amount nullable if it was NOT NULL | v4 no longer writes amount | Yes: deploy v3 (needs dual write again) |
| 7 Contract | DROP COLUMN amount | — | No (only via restore) |
The same skeleton handles splitting a table (moving addresses out of customer), changing a key's type (int to bigint before the sequence overflows), and moving a table to another service's database (with CDC instead of dual writes, below). Wait long enough between steps 6 and 7 to be sure nothing reads the old column: other services, reports, ETL jobs, CDC consumers, and ORMs selecting every column.
Lock-aware DDL in Postgres
| Change | Naive behavior | Safe approach |
|---|---|---|
| Add nullable column | Metadata only; brief ACCESS EXCLUSIVE | Fine with lock_timeout |
Add column with constant default (incl. NOT NULL DEFAULT 0) | 11+: metadata only. Older: full rewrite | Fine on 11+; avoid volatile defaults (clock_timestamp(), gen_random_uuid()), which rewrite |
SET NOT NULL on existing column | Full scan under ACCESS EXCLUSIVE | CHECK (col IS NOT NULL) NOT VALID → VALIDATE → SET NOT NULL (12+ skips the scan) → drop the check |
Add CHECK or foreign key | Full scan (FK also locks the referenced table) while blocking writes | ADD CONSTRAINT … NOT VALID, then VALIDATE CONSTRAINT (takes SHARE UPDATE EXCLUSIVE, allows reads and writes) |
| Add unique constraint / primary key | Builds the index while blocking writes | CREATE UNIQUE INDEX CONCURRENTLY, then ADD CONSTRAINT … UNIQUE USING INDEX (or PRIMARY KEY USING INDEX) |
| Create index | SHARE lock blocks writes for the whole build | CREATE INDEX CONCURRENTLY |
| Drop index | ACCESS EXCLUSIVE | DROP INDEX CONCURRENTLY |
| Change column type | Usually a full rewrite plus index rebuilds under ACCESS EXCLUSIVE | Expand/contract with a new column; exceptions are binary-compatible changes such as varchar(n) to a larger n or to text |
| Rename column or table | Metadata only, but breaks running code | Expand/contract, or a temporary view/compatibility column |
| Drop column | Metadata only (space reclaimed later) | Only after no code reads it; ORMs may still select it |
| Rebuild a bloated table | VACUUM FULL / CLUSTER lock the table for the duration | pg_repack |
CREATE INDEX CONCURRENTLY details: it cannot run inside a transaction block (configure your migration tool accordingly, for example goose's -- +goose NO TRANSACTION annotation); it scans the table twice and waits for transactions that might not see the new index, so it is slower and can stall behind long transactions; if it fails it leaves an INVALID index that still slows writes. Check and clean up:
SELECT indexrelid::regclass AS index_name FROM pg_index WHERE NOT indisvalid;
DROP INDEX CONCURRENTLY IF EXISTS payment_merchant_created_idx;
The safe NOT NULL recipe:
SET lock_timeout = '3s';
SET statement_timeout = '0'; -- validation may take a while; it does not block traffic
ALTER TABLE orders ADD CONSTRAINT orders_total_minor_nn
CHECK (total_minor IS NOT NULL) NOT VALID; -- brief lock, no scan
ALTER TABLE orders VALIDATE CONSTRAINT orders_total_minor_nn; -- scans, reads/writes continue
ALTER TABLE orders ALTER COLUMN total_minor SET NOT NULL; -- brief lock, uses the valid CHECK
ALTER TABLE orders DROP CONSTRAINT orders_total_minor_nn;
MySQL: online DDL, gh-ost and pt-online-schema-change
InnoDB online DDL supports three algorithms: INSTANT (metadata only; adding a column as the last column since 8.0.12, adding at any position and dropping columns since 8.0.29), INPLACE (rebuilds or modifies without blocking DML for many operations, such as adding a secondary index with LOCK=NONE), and COPY (full table copy with writes blocked, for example most type changes). Specify ALGORITHM and LOCK explicitly so the statement fails instead of silently falling back to a blocking mode. Two MySQL-specific hazards: metadata locks queue exactly like the Postgres lock queue, and a long INPLACE operation runs again on each replica, delaying replication by its duration.
When native online DDL is not enough, use a tool that builds a shadow table and swaps it in:
| Tool | Mechanism | Strengths | Caveats |
|---|---|---|---|
| gh-ost (GitHub) | Creates a ghost table, copies rows in chunks, applies ongoing changes by reading the binlog (no triggers), then atomically swaps | No trigger overhead on the primary, pausable, throttles on replica lag and load, controllable cut-over timing | Requires row-based binlog; foreign keys largely unsupported |
| pt-online-schema-change (Percona) | Shadow table, chunked copy, triggers propagate ongoing changes, rename swap | Mature, works on many setups, foreign-key handling options | Triggers add write overhead and can contend under heavy load |
| pg_repack (Postgres) | Rebuilds a table or index online using a log table and triggers, brief ACCESS EXCLUSIVE at the end | Removes bloat, reorders rows, without VACUUM FULL locks | Needs a primary key or unique not-null index; not a general schema-change tool; needs free disk for a full copy |
| pgroll, Reshape (Postgres) | Automate expand/contract by serving old and new schema versions through views | Encodes the pattern in tooling | Younger projects; evaluate carefully |
Migration linters such as squawk (Postgres) catch unsafe statements (non-concurrent index creation, NOT NULL without the check pattern, missing lock_timeout) in code review.
Backfills
A backfill fills new structures for existing rows. Requirements:
- Small batches in separate transactions (for example 1,000–10,000 rows, tuned by measurement), so locks are brief, vacuum can keep up, and replicas do not fall far behind.
- Keyset iteration by primary key, never
OFFSET. - Idempotent:
WHERE new_col IS NULL(or a version marker), so re-running a batch is harmless. - Resumable: persist the last processed key.
- Throttled: pause when replica lag, CPU or lock waits exceed thresholds; run heavier phases off-peak.
- Observable: progress, rate and ETA metrics; a kill switch.
package backfill
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
type Config struct {
BatchSize int64
MaxLag time.Duration
Pause time.Duration
StartAfter int64 // resume point
ReplicaPool *pgxpool.Pool
}
// FillTotalMinor copies amount (numeric major units) into total_minor in batches.
func FillTotalMinor(ctx context.Context, primary *pgxpool.Pool, cfg Config, progress func(lastID int64)) error {
lastID := cfg.StartAfter
for {
if err := waitForReplica(ctx, cfg); err != nil {
return err
}
var maxID *int64
err := primary.QueryRow(ctx, `
WITH batch AS (
SELECT id FROM orders
WHERE id > $1
ORDER BY id
LIMIT $2
), upd AS (
UPDATE orders o
SET total_minor = round(o.amount * 100)::bigint
FROM batch
WHERE o.id = batch.id AND o.total_minor IS NULL
)
SELECT max(id) FROM batch`, lastID, cfg.BatchSize).Scan(&maxID)
if err != nil {
return fmt.Errorf("batch after id %d: %w", lastID, err)
}
if maxID == nil {
return nil // no rows left
}
lastID = *maxID
progress(lastID) // persist for resumability
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(cfg.Pause):
}
}
}
func waitForReplica(ctx context.Context, cfg Config) error {
for {
var lagSeconds float64
err := cfg.ReplicaPool.QueryRow(ctx, `
SELECT COALESCE(EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp()), 0)::float8`).Scan(&lagSeconds)
if err != nil {
return err
}
if time.Duration(lagSeconds*float64(time.Second)) <= cfg.MaxLag {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second):
}
}
}
The conversion round(amount * 100) assumes a two-decimal currency; for a multi-currency table, join the currency's minor units (see Schema Patterns). Replay-timestamp lag reads high when the primary is idle; production tools often compare LSNs instead. After a large backfill, run ANALYZE (and check vacuum progress) so plans reflect the new data.
Moving data: dual writes, triggers or CDC
When data moves to a new table, a new database or a new service (for example extracting payment from a monolith into a payments service), you need both copies in sync during the transition.
| Approach | How | Consistency | Risks |
|---|---|---|---|
| Application dual write | Code writes old and new stores | None across two databases: one write can fail after the other succeeded | Divergence, ordering issues; needs reconciliation |
| Database trigger (same database) | Trigger on old table writes new table in the same transaction | Atomic | Write overhead, logic in triggers, same-database only |
| CDC (Debezium, logical replication, binlog readers) | Stream committed changes from the old store's log into the new one | Eventually consistent, ordered per key, no lost writes | Lag, schema mapping, operating the pipeline |
| Outbox events | Application emits domain events in the same transaction; new service consumes | Eventually consistent, semantic events | Requires changing the producer |
CDC or an outbox is usually the right answer across databases (see Transactional Outbox & CDC); dual writes from application code are acceptable only with a reconciliation job that detects and repairs divergence.
Verification before switching reads: row counts and checksums per key range (for example hash of (id, amount, status) aggregated per 10,000 ids), shadow reads (serve from the old store, read the new one in parallel, compare and log mismatches), and a burn-in period with zero unexplained mismatches. Then switch reads per tenant or percentage behind a flag, keep the old path warm, and only then stop writes to the old store. This is the strangler fig applied to data.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Single-step migration in a maintenance window | Simple, fast to write | Downtime; risky rollback | Internal tools, tiny tables, genuinely allowed downtime |
| Expand/contract | Zero downtime, reversible until contract | Several deploys, temporary complexity, longer elapsed time | Any breaking change on a live system |
Native online DDL (Postgres concurrent ops, MySQL INSTANT/INPLACE) | No extra tooling | Limited to supported operations; still needs lock timeouts | Indexes, constraints, additive columns |
| gh-ost / pt-osc | Arbitrary MySQL alterations online | Full table copy, disk and I/O, tool constraints | Large MySQL tables needing rebuilds |
| Triggers for sync | Atomic within one database | Write overhead, hidden logic | Column or table moves inside one database |
| CDC for sync | Reliable across systems | Pipeline to run, eventual consistency | Moving data between databases or services |
In practice
A migration checklist for a bank or large e-commerce platform:
- Classify each statement: lock taken, rewrite or not, expected duration on production-sized data.
- Separate schema changes from data backfills and from code deploys; one concern per migration.
- Set guards in every migration session:
lock_timeout(seconds), sensiblestatement_timeout, and retry with backoff on lock timeout. - Check for long transactions before starting (
pg_stat_activityoldestxact_start); pause reports and batch jobs that hold locks on the target table. - Rehearse on a recent, anonymized production-sized copy and record timings and lock waits.
- Test compatibility: run version N's test suite against the post-migration schema in CI (N-1 compatibility), so you know rollback of the code is safe.
- Monitor during execution: lock waits, replica lag, error rates, p99 latency; have a stop button.
- Define the rollback point for each step and the go/no-go criteria for the contract step; take a restore point (verified backup, PITR timestamp) before destructive steps.
- Communicate: change tickets, approvals (maker-checker is common in banks), and an ADR for significant changes (see Documenting Architecture).
A retry wrapper for lock-timeout-protected DDL, as many teams run it from a migration runner:
for attempt in 1 2 3 4 5; do
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 <<'SQL' && break
SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN total_minor bigint;
SQL
echo "attempt $attempt failed (lock timeout?), retrying in $((attempt * 5))s"
sleep $((attempt * 5))
done
Make migrations idempotent where possible (ADD COLUMN IF NOT EXISTS, CREATE INDEX CONCURRENTLY IF NOT EXISTS) so a retried or partially applied run is harmless.
Rollback strategy. Down migrations are often lossy or impossible (you cannot un-drop a column's data), so the real rollback plan is: steps 1–6 of expand/contract are reversible by deploying the previous application version or flipping a flag; step 7 is irreversible and therefore delayed until the new path has run in production through at least one full business cycle (month-end, a sale). For data transformations, keep the old data until reconciliation passes. Prefer rolling forward with a fix over rolling back schema changes under pressure.
Common pitfalls
- DDL without
lock_timeout. Symptom: a "safe"ADD COLUMNtakes the table offline during a long-running report. - Plain
CREATE INDEXon a busy table. Symptom: all writes to the table block for the duration of the build. CREATE INDEX CONCURRENTLYinside a transaction-wrapped migration. Symptom: the migration fails ("cannot run inside a transaction block"), or the tool silently runs a non-concurrent build.- Leftover
INVALIDindexes after a failed concurrent build. Symptom: write overhead with no read benefit. - Renaming or dropping in one step. Symptom: errors from old pods during the rolling deploy, and a rollback that cannot work.
- One huge backfill
UPDATE. Symptom: hours-long transaction, doubled table size from dead tuples, WAL spike, replicas minutes behind, vacuum blocked. - Forgetting other readers. Dropping a column still used by a reporting job, a CDC consumer, or another service's read replica query. Symptom: broken pipelines discovered the next morning.
- Volatile defaults (
DEFAULT now()is fine as it is stable within a statement, butDEFAULT clock_timestamp()orgen_random_uuid()rewrites the table when adding a column). Symptom: unexpected full rewrite and lock. - Changing
inttobiginttoo late. Symptom: the sequence approaches 2³¹ − 1 and you must do an urgent rewrite of the largest table. Monitor sequence headroom.
Interview angle
- Prompts: "How would you rename a column in a 2-billion-row table with zero downtime?", "How do you add a NOT NULL column?", "Walk me through migrating the payments table out of the monolith", "What is your rollback plan?"
- A strong answer explains the two problems (compatibility during rolling deploys, locks), applies expand/contract, names the specific safe DDL patterns for the engine, describes batched backfills and verification, and identifies the irreversible step.
- Show operational maturity: lock timeouts, rehearsal on production-sized data, N-1 compatibility tests, monitoring replica lag, approvals.
- Follow-ups: "What if the backfill falls behind live writes?" (dual write or trigger first, then backfill only old rows), "How do you detect divergence between old and new stores?", "Which tool would you use on MySQL and why?"
- Red flags: "we run migrations at deploy time and hope", "just take a maintenance window" for a 24/7 payment system, no mention of locks.
Self-check
1. Why can a metadata-only ALTER TABLE still cause an outage in Postgres?
It needs an ACCESS EXCLUSIVE lock, which must wait for all transactions currently using the table. While it waits in the lock queue, every new query on the table queues behind it, so a single long-running query turns a millisecond change into minutes of blocked traffic. A short lock_timeout with retries prevents this.
2. Give the safe sequence to add a NOT NULL constraint to an existing column on a large Postgres table.
Add CHECK (col IS NOT NULL) NOT VALID (brief lock, no scan); run VALIDATE CONSTRAINT, which scans under a lock that allows reads and writes; then ALTER COLUMN … SET NOT NULL, which on Postgres 12+ uses the validated check instead of scanning; finally drop the redundant check constraint. Run each step with lock_timeout.
3. Describe the expand/contract steps to change orders.amount (numeric) to total_minor (bigint).
Add total_minor as a nullable column; deploy code (or a trigger) that writes both columns; backfill old rows in batches; validate and add NOT NULL via the check pattern; switch reads to total_minor behind a flag; deploy code that stops writing amount; after a safe period confirming no readers remain, drop amount. Every step except the drop can be reversed by redeploying the previous version or flipping the flag.
4. What are the failure modes of CREATE INDEX CONCURRENTLY and how do you handle them?
It cannot run in a transaction block, it waits for existing transactions (so long transactions delay it), it takes longer than a normal build, and if it fails (deadlock, uniqueness violation, cancellation) it leaves an INVALID index that still adds write cost. Detect invalid indexes in pg_index, drop them with DROP INDEX CONCURRENTLY, fix the cause, and retry.
5. How do gh-ost and pt-online-schema-change differ, and when would you still prefer native online DDL?
Both copy the table into a shadow table in chunks and swap it in. gh-ost captures ongoing changes from the binlog without triggers, is pausable and throttles on replica lag; pt-osc uses triggers on the original table, which adds write overhead but works without binlog access. Prefer native ALGORITHM=INSTANT (or INPLACE, LOCK=NONE) when MySQL supports the operation, since it avoids copying the table at all.
6. Scenario: you are moving the payments table from a monolith database to a new payments service database. How do you keep data in sync and decide when to cut over?
Stream changes from the monolith with CDC (or have the monolith emit outbox events) into the new database after an initial snapshot load. Verify with per-range checksums and shadow reads comparing both stores until mismatches are zero for an agreed period. Switch reads gradually behind a flag, then move writes to the new service (with the old store updated via reverse sync or frozen), and decommission the old table only after a full business cycle with reconciliation passing.
7. What makes a backfill safe to run on a production payments table?
Small batches in separate transactions using keyset iteration, idempotent updates (WHERE new_col IS NULL), a persisted resume point, throttling on replica lag and load, metrics and a kill switch, and running heavy phases off-peak. Afterwards, ANALYZE and check vacuum, so the dead tuples created do not degrade performance.
Exercise
Reproduce the lock queue, then perform a full expand/contract on Postgres.
docker run --name pg-mig -e POSTGRES_PASSWORD=pg -p 5432:5432 -d postgres:17
docker exec -it pg-mig psql -U postgres
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
amount numeric(12, 2) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO orders (amount) SELECT round((random() * 1000)::numeric, 2) FROM generate_series(1, 3000000);
- Lock queue. Session A:
BEGIN; SELECT count(*) FROM orders;(leave open). Session B:ALTER TABLE orders ADD COLUMN note text;(it waits). Session C:SELECT * FROM orders WHERE id = 1;(it waits too). Inspectpg_locksandpg_blocking_pids()from a fourth session. Commit A and watch B and C proceed. - Repeat with
SET lock_timeout = '2s';in session B and confirm C is no longer stuck behind it. - Expand. Add
total_minor bigint. Create a trigger that setsNEW.total_minor := round(NEW.amount * 100)on insert and update (simulating dual write). - Backfill in batches of 10,000 with a
DOblock that commits per batch (Postgres 11+ allowsCOMMITinsideDOwhen run outside a transaction):
DO $$
DECLARE
last_id bigint := 0;
max_id bigint;
BEGIN
SELECT max(id) INTO max_id FROM orders;
WHILE last_id < max_id LOOP
UPDATE orders SET total_minor = round(amount * 100)::bigint
WHERE id > last_id AND id <= last_id + 10000 AND total_minor IS NULL;
last_id := last_id + 10000;
COMMIT;
END LOOP;
END $$;
- Constrain with the
CHECK … NOT VALID→VALIDATE→SET NOT NULLrecipe, then buildCREATE INDEX CONCURRENTLY orders_total_minor_idx ON orders (total_minor);while a pgbench script inserts orders in the background. Confirm inserts never block for long. - Contract (after imagining the read switch): drop the trigger, then
ALTER TABLE orders DROP COLUMN amount;withlock_timeout. - Write the rollback plan for each step in one line.
Done when every step ran without blocking concurrent inserts for more than your lock timeout, the final table has only total_minor with NOT NULL, and your rollback plan identifies the irreversible step.
Further reading
- PostgreSQL documentation, "ALTER TABLE" (notes on locks and rewrites) and "CREATE INDEX" (building indexes concurrently).
- MySQL Reference Manual, "Online DDL Operations".
- gh-ost documentation (github.com/github/gh-ost) and Percona Toolkit documentation for
pt-online-schema-change. - Danilo Sato, "Parallel Change" (martinfowler.com bliki).
- Pramod Sadalage and Martin Fowler, "Evolutionary Database Design" (martinfowler.com).
- Scott W. Ambler and Pramod J. Sadalage, Refactoring Databases: Evolutionary Database Design.
- squawk, a linter for Postgres migrations (squawkhq.com).
Related
- Locking & Concurrency Control — table lock modes and the lock queue.
- PostgreSQL Deep Dive — vacuum, bloat and pg_repack context.
- Legacy Modernization & Migration — strangler fig and data migration strategy.
- Transactional Outbox & CDC — syncing data across stores during migrations.
- Cloud-Native, Kubernetes & Deployment Strategies — rolling, blue-green and canary deploys that schema changes must survive.
- Testing Strategy — compatibility and migration tests in CI.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).