All ArticlesDevOps & Cloud•November 18, 2026•9 min read

Zero-Downtime Database Migrations: A Production Playbook for Distributed Systems

Schema changes are the single most common cause of self-inflicted outages in distributed systems. This playbook gives you the expand/contract pattern, lock-safe DDL, and resumable backfills that let you evolve a production schema while thousands of requests per second never notice.

Zero-Downtime Database Migrations: A Production Playbook for Distributed SystemsAI Generated with Qwen 3.0 via CometAPI

Why Traditional Migrations Break in Distributed Systems

In a monolith with a maintenance window and one writer process, ALTER TABLE is a 2 a.m. chore. In a distributed production environment it is a distributed protocol change. During a rolling deploy you have N and N-1 application versions alive simultaneously. Those pods share a database that also feeds read replicas, a CDC stream into Kafka, a search index, a materialized view, and an analytics warehouse. A schema change is not a change to a database — it is a change to a contract that every one of those consumers must already satisfy.

Three invariants separate teams that ship schema changes daily from teams that schedule outages:

  1. Every intermediate schema state must be both readable and writable by at least two adjacent application versions.
  2. No DDL may hold a lock longer than your health-check timeout. A 40 ms ALTER TABLE that queues behind a 12-second analytics query blocks the table for 12 seconds.
  3. No data movement may happen inside a DDL transaction. Backfills are separate, resumable, throttled jobs.

The Compatibility Matrix Is Your Real Migration Spec

Before writing SQL, classify the change. The matrix below is the decision table most senior platform teams use:

ChangeN-1 code readsN code readsRequired strategy
Add nullable columnOK (ignores it)OKSingle additive DDL
Add NOT NULL columnOKOK if defaultedAdd nullable → backfill → SET NOT NULL
Rename columnBrokenBrokenExpand/contract, 3+ releases
Narrow a type (bigint → int)BrokenBrokenNew column + dual write
Drop columnOK if never referencedOKContract release only
Add indexOKOKCREATE INDEX CONCURRENTLY
Split tableBrokenBrokenDual write both shapes, backfill, cut reads

The N-1 Guarantee and Forward-Only Rollback

Your rollback plan is redeploy the previous image, not run the down-migration. Destructive down scripts are how a bad deploy becomes a data-loss incident. Treat migrations as forward-only; the final contract step is the only irreversible one, and it lands a full release cycle after the code that depended on the old shape was deleted.

The Expand/Contract (Parallel Change) Pattern

Every non-additive change decomposes into three deploys:

  • Expand — additive DDL only. Old code unaffected.
  • Migrate — new code dual-writes both shapes; a background job backfills history; new reads come from the new shape behind a flag.
  • Contract — stop writing the legacy shape, verify zero readers, then drop it in a subsequent release.

Locking Forensics: What Actually Takes Your Cluster Down

PostgreSQL and the ACCESS EXCLUSIVE Queue Cascade

Most ALTER TABLE variants acquire ACCESS EXCLUSIVE, which conflicts with everything, including SELECT. The danger is not duration — it is the queue. A fast DDL that waits for a lock blocks every query that arrives behind it, producing a thundering-herd stall that looks like a database outage but is a lock-ordering problem.

The fix is a bounded lock wait plus retry, so the DDL fails fast and you re-attempt instead of freezing the table:

ts
import { Client } from 'pg';

const LOCK_TIMEOUT = '3s';
const MAX_ATTEMPTS = 5;

const sleep = (ms: number): Promise<void> =>
  new Promise((resolve) => setTimeout(resolve, ms));

export class LockTimeoutError extends Error {
  constructor(public readonly ddl: string, cause?: unknown) {
    super(`DDL could not acquire ACCESS EXCLUSIVE within ${LOCK_TIMEOUT}: ${ddl}`);
    this.name = 'LockTimeoutError';
    this.cause = cause;
  }
}

/**
 * Runs one DDL statement with a bounded lock wait and jittered exponential
 * backoff. Never wraps DDL in a long-lived transaction.
 */
export async function guardedDdl(client: Client, ddl: string): Promise<void> {
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
    try {
      await client.query(`SET lock_timeout = '${LOCK_TIMEOUT}'`);
      await client.query(`SET statement_timeout = '30s'`);
      await client.query(ddl);
      return;
    } catch (err: unknown) {
      const code = (err as { code?: string }).code;
      if (code !== '55P03') throw err; // lock_not_available only
      if (attempt === MAX_ATTEMPTS) throw new LockTimeoutError(ddl, err);
      await sleep(2 ** attempt * 250 + Math.random() * 250);
    } finally {
      await client.query('RESET lock_timeout');
      await client.query('RESET statement_timeout');
    }
  }
}

Two more PostgreSQL specifics that trip up even experienced teams:

  • CREATE INDEX CONCURRENTLY cannot run inside a transaction block. Flyway needs executeInTransaction=false; Alembic needs with op.get_context().autocommit_block():. If your runner opens a transaction per migration file, this statement will fail at 3 a.m.
  • A failed concurrent index build leaves an INVALID index behind. CREATE INDEX CONCURRENTLY IF NOT EXISTS will silently skip it. Always check pg_index.indisvalid on retry, drop the corpse, and rebuild.

MySQL: Assert the Algorithm, Do Not Hope for It

MySQL 8.0 gives you ALGORITHM=INSTANT (metadata-only: adding a column at the end since 8.0.12, adding or dropping anywhere since 8.0.29), INPLACE (rebuild without a full copy), and COPY (full table copy, writes blocked). Never leave the algorithm to chance — pin it so a surprise fallback to COPY fails loudly in staging instead of silently locking production:

sql
ALTER TABLE orders
  ADD COLUMN fulfillment_state VARCHAR(32) NULL,
  ALGORITHM=INSTANT;

For anything that requires a rebuild on a hot table, use a shadow-table tool: gh-ost (triggerless, binlog-driven, throttled by replica lag) or pt-online-schema-change (trigger-based). Both copy in chunks and swap atomically; neither is safe if your table has no primary key.

Production-Grade Implementation: The Expand Phase

ts
export async function expandEmailVerified(client: Client): Promise<void> {
  // 1. Metadata-only add. Safe on any version, takes ACCESS EXCLUSIVE briefly.
  await guardedDdl(
    client,
    `ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified boolean`,
  );

  // 2. NOT VALID adds the constraint WITHOUT scanning the table. This
  //    validated CHECK is the proof PostgreSQL 12+ needs to skip the
  //    full-table scan when we later run SET NOT NULL.
  await guardedDdl(
    client,
    `ALTER TABLE users
       ADD CONSTRAINT users_email_verified_chk
       CHECK (email_verified IS NOT NULL) NOT VALID`,
  );

  // 3. Separate connection: CONCURRENTLY cannot run in a transaction.
  await client.query(
    `CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_email_verified
       ON users (id) WHERE email_verified IS FALSE`,
  );
}

Dual-Write: Keeping Both Shapes Truthful

During the migrate phase, every write must land in both the legacy and the new column, because you cannot know which pod version handles the next request.

ts
export interface UserPatch {
  emailVerified?: boolean;
}

export interface FeatureFlags {
  isEnabled(flag: string): boolean;
}

export async function updateUser(
  db: Pool,
  flags: FeatureFlags,
  id: string,
  patch: UserPatch,
): Promise<void> {
  const assignments: string[] = ['updated_at = now()'];
  const values: unknown[] = [id];
  let i = 1;

  if (patch.emailVerified !== undefined) {
    if (flags.isEnabled('users.email_verified.write')) {
      assignments.push(`email_verified = $${++i}`);
      values.push(patch.emailVerified);
    }
    // Legacy column stays writable until N-1 is fully drained.
    assignments.push(`is_verified_legacy = $${++i}`);
    values.push(patch.emailVerified);
  }

  const { rowCount } = await db.query(
    `UPDATE users SET ${assignments.join(', ')} WHERE id = $1`,
    values,
  );
  if (rowCount !== 1) {
    throw new Error(`expected to update exactly 1 user, got ${rowCount}`);
  }
}

Backfilling Billions of Rows Without Melting Replicas

A backfill is a throughput problem disguised as a correctness problem. Rules: keyset paginate (never OFFSET, which drifts and degrades quadratically), batch small (500–2000 rows), checkpoint after every batch, and throttle on replica lag, not on wall-clock time.

sql
CREATE TABLE IF NOT EXISTS migration_checkpoints (
  migration_id text PRIMARY KEY,
  last_id      bigint      NOT NULL,
  updated      bigint      NOT NULL,
  updated_at   timestamptz NOT NULL DEFAULT now()
);
ts
export interface BackfillCheckpoint {
  lastId: number;
  updated: number;
}

async function readReplicaLagSeconds(db: Pool): Promise<number> {
  const { rows } = await db.query<{ lag_seconds: string | null }>(
    `SELECT EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp()))::text
       AS lag_seconds`,
  );
  // NULL on a primary; combine with metrics scraped from replicas.
  return Number(rows[0]?.lag_seconds ?? 0);
}

export async function backfillEmailVerified(
  db: Pool,
  checkpoint: BackfillCheckpoint,
  opts: { batchSize?: number; maxLagSeconds?: number } = {},
): Promise<BackfillCheckpoint> {
  const batchSize = opts.batchSize ?? 1000;
  const maxLag = opts.maxLagSeconds ?? 10;
  const state: BackfillCheckpoint = { ...checkpoint };

  for (;;) {
    if ((await readReplicaLagSeconds(db)) > maxLag) {
      await sleep(5_000);
      continue;
    }

    const { rows } = await db.query<{ id: number }>(
      `UPDATE users
          SET email_verified = is_verified_legacy
        WHERE id IN (
          SELECT id FROM users
           WHERE id > $1
             AND email_verified IS NULL
             AND is_verified_legacy IS NOT NULL
           ORDER BY id
           LIMIT $2
        )
      RETURNING id`,
      [state.lastId, batchSize],
    );

    if (rows.length === 0) return state;

    const last = rows[rows.length - 1];
    if (!last) return state;

    state.lastId = last.id;
    state.updated += rows.length;
    await persistCheckpoint(db, 'users_email_verified_backfill', state);

    if (rows.length < batchSize) return state;
    await sleep(50); // yield to OLTP traffic
  }
}

Note the is_verified_legacy IS NOT NULL guard: without it, rows whose legacy value is NULL would be selected forever and the loop would spin. Handle that residual set with an explicit defaulted pass after the main sweep.

The Contract Phase: Removing the Old Shape

Only after two full deploy cycles and a verified zero-read window (check pg_stat_statements for the legacy column name) do you finalize:

sql
-- SHARE UPDATE EXCLUSIVE: does not block reads or writes.
ALTER TABLE users VALIDATE CONSTRAINT users_email_verified_chk;

-- PostgreSQL 12+ skips the full scan because a validated CHECK proves it.
ALTER TABLE users ALTER COLUMN email_verified SET NOT NULL;

-- Ship this in the NEXT release, after the constraint above is live.
ALTER TABLE users DROP CONSTRAINT users_email_verified_chk;
ALTER TABLE users DROP COLUMN is_verified_legacy;

Orchestration: Deploy Ordering and Rollback Safety

  • Run migrations as a separate pre-deploy Job, never in the container entrypoint, where N pods race each other. Elect a leader with SELECT pg_advisory_lock($1) keyed on a hashed migration namespace.
  • Backfills are flag-gated jobs, not migrations. They must be independently pausable, resumable, and cancellable without touching schema state.
  • Feature flags decouple deploy from release so a schema change can be exercised on 1% of traffic before full rollout.
  • If you publish CDC events from the table, set your schema registry compatibility to BACKWARD_TRANSITIVE — otherwise a rename in the database becomes a poisoned record in Kafka that breaks every downstream consumer.
  • Blue/green deployments share one schema: both colors must be able to write, which categorically forbids destructive DDL during the switch window.

Observability and Automated Guardrails

Alert on lock queues, not on CPU. This query is the single highest-value dashboard panel for migration safety:

sql
SELECT pid,
       wait_event_type,
       wait_event,
       now() - query_start AS age,
       left(query, 80)     AS query
FROM pg_stat_activity
WHERE wait_event_type = 'Lock'
  AND state <> 'idle'
ORDER BY age DESC
LIMIT 20;

Also track: pg_blocking_pids(pid) for cascade roots, pg_stat_progress_create_index for concurrent builds, p99 replication lag (never the average), and error rate bucketed by SQLSTATE — 23502 not-null violation, 23514 check violation, and 42P01 undefined table are the three signals that a contract step ran too early.

Operational Checklist

  • Change classified against the compatibility matrix; expand/contract plan written down.
  • Every DDL statement wrapped in lock_timeout + bounded retry.
  • CREATE INDEX CONCURRENTLY isolated from any transaction block in the runner config.
  • Backfill uses keyset pagination, checkpoints, and replica-lag throttling.
  • Dual-write live for at least one full deploy cycle before reads switch.
  • Reads switched behind a flag with a canary percentage.
  • Legacy column confirmed unreferenced via pg_stat_statements before DROP COLUMN.
  • Down-migrations are forward-only; rollback is a redeploy, never a reverse DDL.
  • Runbook names the abort lever for the backfill job and the exact SQL to verify lock state.
  • Estimated duration published, with an alert at 5x historical p95.

Sources & Technical References

5 views•0 comments

Discussion (0)

Join the conversation

Loading comments...

Continue Reading

More production-grade engineering deep dives and architectural guides

Explore all articles