All ArticlesPortfolio•November 18, 2026•12 min read

Designing Zero-Downtime Database Migrations in Distributed Production Environments

Most outages blamed on migrations are actually caused by the code/schema interleaving across a fleet of rolling pods — not the SQL itself. This guide gives you the expand/contract model, lock-queue physics, batched backfills, and a production checklist for shipping schema evolution with backwards compatibility at every step.

Designing Zero-Downtime Database Migrations in Distributed Production EnvironmentsAI Generated with Qwen 3.0 via CometAPI

Every senior engineer eventually ships a migration that takes the platform down for eleven minutes. Almost never is the culprit the ALTER TABLE statement itself — it is the interleaving: three hundred pods running two different code versions, a CDC consumer replaying an old schema, and a read replica eight seconds behind. Zero downtime is not a property of your SQL. It is a property of the deployment sequence you designed around that SQL.

This article lays out the mechanics used by teams running multi-tenant, multi-service systems on PostgreSQL and MySQL: the expand/contract model, PostgreSQL lock-queue physics, safe DDL catalogs, resumable backfills, dual writes, and the coordination rules that keep schema evolution backwards compatible across a rolling fleet.

Zero Downtime Is a Deployment Invariant, Not a Syntax Feature

State the invariant explicitly and enforce it in code review:

At every instant during a rollout, the live schema must be simultaneously valid for the oldest and the newest code version running in production.

In a Kubernetes deployment with maxSurge: 25%, a bad imagePullBackOff, or a slow readiness probe, the mixed-version window can stretch from ninety seconds to several hours. Your migration plan must survive that window, not just the happy path.

That single invariant kills a whole class of tempting operations: renaming columns, tightening NOT NULL in one shot, changing types, and dropping anything the previous release still selects.

The Expand/Contract (Parallel Change) Model

Every non-trivial schema change decomposes into five phases. Nothing is ever modified in place while it is live.

PhaseActionReversible?Code deploy
0. PrepareAdd new column/table/index — additive onlyYesNone
1. Dual writeNew code writes old and newYesDeploy A
2. BackfillResumable batched job fills historyYesJob
3. Dual read → new readShadow-compare, then flip readsYesDeploy B
4. Stop old writesOld column frozenYesDeploy C
5. ContractDrop old column/table/triggerNoDeploy D

Only phase 5 is irreversible, which is why it must be the last thing you do — days or weeks after phase 4, gated on a metric proving nothing reads the old column anymore.

sql
-- Phase 0: strictly additive, metadata-only in PostgreSQL 11+
ALTER TABLE orders
  ADD COLUMN IF NOT EXISTS fulfillment_state text;

Note that adding a column with a volatile default (now(), gen_random_uuid(), random()) still rewrites the table on older engines and can be expensive even on PostgreSQL 11+ for volatile expressions. Add nullable, backfill, then constrain.

Locking Physics: The Lock Queue Is What Actually Kills You

In PostgreSQL, an ALTER TABLE requests ACCESS EXCLUSIVE. It must wait for every in-flight query on that relation. Worse: while it waits in the queue, every subsequent query on that table queues behind it, including plain SELECTs. Long-running analytics query + one impatient ALTER TABLE = a fully stalled table with an empty-looking pg_stat_activity and rising connection counts.

The fix is not to avoid locks — it is to never wait unboundedly for one.

sql
SET LOCAL lock_timeout = '2s';       -- fail fast, don't queue behind analytics
SET LOCAL statement_timeout = '60s';

ALTER TABLE orders ADD COLUMN IF NOT EXISTS fulfillment_state text;

A lock_timeout expiry raises SQLSTATE 55P03 (lock_not_available). Wrap every migration step in a bounded retry loop:

go
package migrate

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"time"
)

var ErrLockContention = errors.New("migration step blocked by lock contention")

type Step struct {
	Name string
	SQL  string
}

// RunStep applies a single DDL/DML step under bounded lock waits with
// exponential-ish backoff. Safe to call from every replica: the advisory
// lock guarantees exactly one executor.
func RunStep(ctx context.Context, db *sql.DB, s Step, maxAttempts int) error {
	for attempt := 1; attempt <= maxAttempts; attempt++ {
		tx, err := db.BeginTx(ctx, nil)
		if err != nil {
			return fmt.Errorf("begin %s: %w", s.Name, err)
		}

		if _, err := tx.ExecContext(ctx, `SET LOCAL lock_timeout = '2s'`); err != nil {
			_ = tx.Rollback()
			return fmt.Errorf("set lock_timeout: %w", err)
		}
		if _, err := tx.ExecContext(ctx, `SET LOCAL statement_timeout = '90s'`); err != nil {
			_ = tx.Rollback()
			return fmt.Errorf("set statement_timeout: %w", err)
		}

		if _, err := tx.ExecContext(ctx, s.SQL); err != nil {
			_ = tx.Rollback()
			var state interface{ SQLState() string }
			if errors.As(err, &state) && state.SQLState() == "55P03" {
				backoff := time.Duration(attempt*attempt) * 250 * time.Millisecond
				select {
				case <-time.After(backoff):
					continue
				case <-ctx.Done():
					return ctx.Err()
				}
			}
			return fmt.Errorf("apply %s: %w", s.Name, err)
		}

		if err := tx.Commit(); err != nil {
			return fmt.Errorf("commit %s: %w", s.Name, err)
		}
		return nil
	}
	return fmt.Errorf("%w: %s after %d attempts", ErrLockContention, s.Name, maxAttempts)
}

Serializing Migrators Across a Fleet

If migrations run on pod start (common with Flyway, Liquibase, Alembic, or goose), N replicas will race. Use a database-scoped advisory lock so only one executes while the others block or exit cleanly:

sql
-- Session-scoped: released automatically if the pod dies
SELECT pg_try_advisory_lock(hashtext('schema_migrations'));

Flyway and Liquibase both implement this natively (Flyway's schema history table lock, Liquibase's DATABASECHANGELOGLOCK). If you run a custom runner, do not skip this — duplicate concurrent DDL is a genuinely nasty failure mode.

A Safe/Unsafe DDL Catalog for PostgreSQL

Always safe (no rewrite, short or no `ACCESS EXCLUSIVE`):

  • ADD COLUMN nullable, no default
  • ADD COLUMN with a non-volatile default (PostgreSQL 11+)
  • CREATE INDEX CONCURRENTLY / DROP INDEX CONCURRENTLY (cannot run inside a transaction)
  • ADD CONSTRAINT ... CHECK (...) NOT VALID
  • VALIDATE CONSTRAINT (takes SHARE UPDATE EXCLUSIVE only)
  • CREATE TABLE, DROP TABLE for objects no live code touches

Never safe in a single step:

  • ALTER COLUMN ... TYPE on a populated table (rewrite + full-duration lock)
  • RENAME COLUMN / RENAME TABLE during a rolling deploy
  • SET NOT NULL without a pre-validated CHECK
  • ADD COLUMN ... DEFAULT gen_random_uuid() (volatile → rewrite)
  • VACUUM FULL (rewrite, ACCESS EXCLUSIVE for the whole duration)

Adding NOT NULL Without a Full-Table Lock

The three-step pattern exploits PostgreSQL 12+ behavior, which lets SET NOT NULL trust an existing validated CHECK constraint and skip the sequential scan:

sql
-- 1. Cheap metadata-only constraint, not enforced for existing rows
ALTER TABLE orders
  ADD CONSTRAINT orders_fulfillment_state_nn
  CHECK (fulfillment_state IS NOT NULL) NOT VALID;

-- 2. Scans without blocking reads or writes
ALTER TABLE orders VALIDATE CONSTRAINT orders_fulfillment_state_nn;

-- 3. Metadata-only because a valid CHECK backs it
ALTER TABLE orders ALTER COLUMN fulfillment_state SET NOT NULL;

-- 4. Tidy up
ALTER TABLE orders DROP CONSTRAINT orders_fulfillment_state_nn;

For MySQL 8.0, prefer ALGORITHM=INSTANT (append-only ADD COLUMN, default changes) and fall back to ALGORITHM=INPLACE, LOCK=NONE. When neither is possible, hand off to gh-ost or pt-online-schema-change, which shadow-copy the table and swap via rename — but remember the swap itself needs a brief metadata lock, so run it during a low-traffic window and watch for long transactions holding the table open.

Backfilling Billions of Rows Without Melting the Primary

A naive UPDATE orders SET fulfillment_state = 'pending' on a large table generates one enormous transaction: WAL bloat, replication lag measured in minutes, lock escalation, and an autovacuum bill you pay for a week.

Use keyset pagination with bounded batches, a resumable cursor, and a throttle tied to measured replication lag:

sql
-- One batch. Idempotent, resumable, non-blocking on hot rows.
WITH batch AS (
  SELECT id
    FROM orders
   WHERE fulfillment_state IS NULL
     AND id > $1
   ORDER BY id
   LIMIT 5000
   FOR UPDATE SKIP LOCKED
)
UPDATE orders o
   SET fulfillment_state = 'pending'
  FROM batch
 WHERE o.id = batch.id
RETURNING o.id AS last_id;

The driver loop should: track last_id in a durable progress table, sleep between batches (100–500 ms for hot tables), and pause when replica lag exceeds a budget (e.g. 5 seconds). Read lag from the primary:

sql
SELECT COALESCE(MAX(EXTRACT(EPOCH FROM replay_lag)), 0) AS max_lag_seconds
  FROM pg_stat_replication;

Go with FOR UPDATE SKIP LOCKED means concurrent application writes never deadlock with the backfill, and multiple backfill workers can run in parallel safely.

Dual Writes and the Read Cutover

During phase 1, new code writes both fields. Reads still come from the old field until you have proven the new one is correct.

ts
// Phase 1: dual write, single source of truth for reads = old column
async function createOrder(tx: PoolClient, id: string, status: OrderStatus) {
  const fulfillment = mapStatusToFulfillment(status);
  await tx.query(
    `INSERT INTO orders (id, status, fulfillment_state)
     VALUES ($1, $2, $3)`,
    [id, status, fulfillment]
  );
}

Phase 3 flips reads, but not blindly. Use shadow reads first: read both, serve the old value, and emit a divergence metric.

ts
// Phase 3a: shadow read with divergence telemetry
const { rows } = await pool.query(
  `SELECT status, fulfillment_state FROM orders WHERE id = $1`,
  [id]
);

const legacy = rows[0].status;
const next = rows[0].fulfillment_state;

if (mapStatusToFulfillment(legacy) !== next) {
  metrics.increment('order.fulfillment.divergence');
}

// Serve legacy until divergence rate is zero for a full bake period
return toApiStatus(legacy);

Only after divergence sits at zero (or within a known-tolerable delta) across a full business cycle — including month-end jobs and batch importers — do you flip the read path and deploy it as a canary first.

Coordinating the Fleet: CDC, Consumers, and Replication Lag

Distributed systems add three failure modes that single-service teams never see.

  1. CDC consumers (Debezium, logical replication, Kafka Connect) receive row-level change events. Adding a column produces events with null; dropping one produces events that break older consumers. Manage schemas through a registry with BACKWARD compatibility so a consumer built against an old schema can always read new records.
  2. Schema propagation to read replicas. DDL replicates asynchronously. A replica can serve a query for a column that does not exist yet, or reject a write referencing one. Route schema-dependent reads to the primary during the mixed window, and keep lock_timeout on replicas too.
  3. Long mixed-version windows. With 300 pods, partial deploys, and a stalled canary, code version skew can last hours. Never merge a contract-phase PR in the same release as the expand phase.

The safe release ordering is a linear pipeline — enforce it in your platform, not in tribal memory:

code
expand DDL  →  deploy dual-write code  →  backfill job  →  verify divergence = 0
           →  deploy new-read code  →  bake 7–14 days  →  contract DDL  →  cleanup deploy

Rollback Realities

  • Phases 0–4 roll back by reverting code. Because the schema is strictly compatible with both versions, a rollback is a normal deploy.
  • Phase 5 does not roll back. Dropping a column is unrecoverable short of a PITR restore, which in a distributed production environment means an outage and data loss for every write since the snapshot. Gate it on evidence: no reads of the column in query logs, no SELECT * consumers, no CDC consumer bound to it.
  • Type changes never roll back cleanly either. If you must change a type, add a new column, dual-write with conversion, backfill, flip reads, and contract the old column — same five phases.

Observability and Guardrails

Instrument these during every migration window:

  • pg_locks waiters on the target relation, and pg_stat_activity wait_event_type = 'Lock'
  • p99 latency on the affected service endpoints
  • Logical replication lag and pg_stat_replication replay_lag
  • Divergence counter between old and new columns
  • Rows remaining in the backfill and elapsed throughput

Automate the policy check in CI so no one has to remember the rules at 2 AM:

yaml
- name: Reject unsafe DDL
  run: |
    squawk --config .squawk.toml migrations/*.sql
    sqlfluff lint migrations/ --dialect postgres

Squawk flags missing lock_timeout, SET NOT NULL without a validated check, volatile defaults, and CREATE INDEX without CONCURRENTLY — exactly the failures this article describes.

Production Checklist

  • Migration is strictly additive; the schema is valid for the oldest deployed code version
  • lock_timeout (2–5 s) and statement_timeout set on every DDL session
  • Advisory lock or native migration lock prevents concurrent runners
  • Every step is idempotent (IF NOT EXISTS, CREATE OR REPLACE) and safe to retry
  • Indexes built CONCURRENTLY; constraints added NOT VALID then VALIDATEd
  • Backfill is keyset-paginated, resumable, throttled, and pausable on replica lag
  • New reads validated via shadow comparison before cutover
  • CDC/schema-registry compatibility mode set to BACKWARD
  • Contract phase separated into its own release, gated on a no-reads metric
  • Rollback plan documented per phase, with phase 5 explicitly marked irreversible
  • Migration rehearsed against a production-sized snapshot, with timing recorded

Pitfalls to Avoid

  • Renaming during a rolling deploy. RENAME COLUMN is instantaneous and catastrophic: the new code wins for a second, then every old pod errors. Always expand/contract.
  • `CREATE INDEX` without `CONCURRENTLY`. Blocks writes on the table for the full build duration.
  • `CREATE INDEX CONCURRENTLY` inside a transaction. It fails outright; native migration tools that wrap steps in transactions must be told not to.
  • Long-lived idle-in-transaction sessions. They hold locks indefinitely and defeat lock_timeout. Set idle_in_transaction_session_timeout.
  • Backfill in one transaction. WAL explosion, replication lag, and an autovacuum debt that outlives the sprint.
  • Assuming the deploy completes. A stuck rollout means indefinitely mixed versions; design for hours, not seconds.
  • Dropping the old column in the same release as the cutover. No bake time, no rollback, no thanks.

Sources & Technical References

1 views•0 comments

Discussion (0)

Join the conversation

Loading comments...

Continue Reading

More production-grade engineering deep dives and architectural guides

Explore all articles