Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Zero-Downtime Online DDL
for Large Tables.

An ALTER TABLE on a 1.8B-row orders table acquires an ACCESS EXCLUSIVE / metadata lock, queuing behind a 12-minute analytics query and blocking all production writes behind it.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep the architecture evolvable without sacrificing reliability, enforce lock_timeout + statement_timeout on all DDL, use CONCURRENTLY / gh-ost online schema change, and apply Expand-Contract for non-trivial column changes.

TL;DR30-second simplified summary
▾

Core Mechanics: Running ALTER TABLE orders on a 1.4 TB (1.8B-row) PostgreSQL 15 / MySQL 8 table at 4,200 TPS writes and 15,000 TPS reads caused a 47-minute total write outage.

Visual & Structural Flow: Depicts 47-Minute Lock Queue Freeze vs. Safe Online Migration (Long SELECT -> ALTER TABLE -> 4.2k/s OLTP -> PG / gh-ost); Zero-Downtime 1.4 TB Migration with Replica-Lag Throttling (1. Expand (2s lock) -> 2. Dual-Write + Backfill -> Lag Monitor (<2s) -> 3. Swap & Contract).

Trade-Offs & Production: Running ALTER TABLE directly during a 'low-traffic' window still fails if any reporting query or idle in transaction session is open, and table-rewriting changes (e.g., INT. Execute schema changes with zero write downtime and < 2s replica lag: **Always Set lock_timeout = '2s' + statement_timeout**: If ALTER` cannot acquire the metadata lock.

Failure Modes & Application: Zero-downtime schema evolution is foundational for continuous deployment on high-scale OLTP databases: Multi-Terabyte Fintech & E-Commerce Ledgers: Safely evolving orders and payments tables without maintenance windows.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Zero-Downtime Online DDL Matters.

Why this matters: The mechanism: understand how Why Zero-Downtime Online DDL Matters works from first principles.

Think of Why Zero-Downtime Online DDL Matters as the intuition layer for Zero-Downtime Online DDL for Large Tables: The mechanism: understand how Why Zero-Downtime Online DDL Matters works from first principles.

Running ALTER TABLE orders on a 1.4 TB (1.8B-row) PostgreSQL 15 / MySQL 8 table at 4,200 TPS writes and 15,000 TPS reads caused a 47-minute total write outage. Even instant metadata-only ALTERs queue behind a single long-running query for ACCESS EXCLUSIVE lock—blocking all subsequent SELECTs and INSERTs behind the lock queue (PgBouncer max_client_conn = 5,000) while keeping streaming replica lag < 2s.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Real-World Impact of Unbounded DDL Lock Queues.

Why this matters: The problem: see what breaks without Real-World Impact of Unbounded DDL Lock Queues under real concurrency or scale.

A naive ALTER TABLE triggers a two-sided outage:

  1. Lock Queue Pile-Up: ALTER waits for an active 20-minute analytics SELECT to release ACCESS SHARE; meanwhile, all 4,200 TPS writes queue behind the waiting ACCESS EXCLUSIVE lock.
  2. PgBouncer Connection Exhaustion: Blocked writes saturate all 5,000 PgBouncer client connections in seconds.
  3. Replication Lag Spike: Rewriting 1.4 TB in one transaction generates massive WAL/binlog bursts, blowing past the < 2s replica lag SLA.
DDL Lock Queue Pile-Up vs. Lock-Timeout + Expand-Contract

47-Minute Lock Queue Freeze vs. Safe Online Migration

Long SELECTALTER TABLE4.2k/s OLTPPG / gh-ost1. Holds ACCESS SHARE (20 min)2. Naive: waits for ACCESSEXCLUSIVE3. 4.2k/s queries pile up behindDDL -> 47m outage4. Fixed: SET lock_timeout='2s' +Expand-Contract5. Throttled backfill keepsreplica lag <2s

Short lock_timeout retries + Expand-Contract (or gh-ost) prevent DDL from ever blocking OLTP traffic.

Engineering Decision Framework
Problem
How to implement Zero-Downtime Online DDL for Large Tables without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To keep the architecture evolvable without sacrificing reliability, enforce lock_timeout + statement_timeout on all DDL, use CONCURRENTLY / gh-ost online schema change, and apply Expand-Contract for non-trivial column changes.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Zero-Downtime Online DDL for Large Tables experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive Solution (and Why It Breaks).

Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.

Think of Naive Solution (and Why It Breaks) as the intuition layer for Zero-Downtime Online DDL for Large Tables: The problem: see what breaks without Naive Solution under real concurrency or scale.

Running ALTER TABLE directly during a 'low-traffic' window still fails if any reporting query or idle in transaction session is open, and table-rewriting changes (e.g., INT -> BIGINT or VARCHAR resize) rewrite 1.4 TB under an exclusive lock.

Request & State Flow

Naive Solution (and Why It Breaks)

CallerService EntryCore ProcessorState Store1. Submit bounded request2. Apply domain invariant3. Persist or read state4. Return verified response
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise Solution: `lock_timeout` Retries, `CONCURRENTLY` & Expand-Contract / `gh-ost`.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Execute schema changes with zero write downtime and < 2s replica lag:

  • Always Set lock_timeout = '2s' + statement_timeout: If ALTER cannot acquire the metadata lock within 2s, abort and retry with backoff rather than queueing 4,200 TPS behind it.
  • Concurrent Indexes & NOT VALID Constraints: Use CREATE INDEX CONCURRENTLY and ADD CONSTRAINT ... NOT VALID followed by VALIDATE CONSTRAINT (which only takes SHARE UPDATE EXCLUSIVE, allowing reads and writes).
  • Expand-Contract / gh-ost: For type changes or 1.4 TB rewrites, add a nullable new column, dual-write in app/triggers, backfill in throttled batches (pausing whenever replica_lag > 1.5s), swap reads, and drop the old column (or use gh-ost on MySQL).
Expand-Contract & Throttled Backfill

Zero-Downtime 1.4 TB Migration with Replica-Lag Throttling

1. Expand (2s lock)Add nullable col / NOT VALID2. Dual-Write + BackfillBatches of 5k rowsLag Monitor (<2s)Throttle if replica_lag…3. Swap & ContractCutover reads -> drop…

1.lock_timeout = 2s: Prevents DDL from queuing behind long analytics SELECTs.

2.NOT VALID + VALIDATE: Validates 1.8B rows without blocking concurrent INSERT/UPDATEs.

3.Lag-Aware Throttle: Pauses backfill if streaming replica lag exceeds 1.5 seconds.

4.gh-ost (MySQL): Shadow table + binlog stream cutover with atomic RENAME.

Expand-Contract and lag-throttled backfills migrate 1.8B rows online without saturating PgBouncer or lagging replicas.

SELECT pid, wait_event_type, wait_event, state, left(query, 80) FROM pg_stat_activity WHERE wait_event = 'Lock';

SET lock_timeout = '1500ms';
ALTER TABLE orders ADD COLUMN amount_v2 BIGINT NULL;
ALTER TABLE orders ADD CONSTRAINT chk_v2_nn CHECK (amount_v2 IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT chk_v2_nn;

ALTER TABLE orders VALIDATE CONSTRAINT chk_v2_nn; -- SHARE UPDATE EXCLUSIVE (writes allowed)
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Online DDL Applies in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Zero-downtime schema evolution is foundational for continuous deployment on high-scale OLTP databases:

  • Multi-Terabyte Fintech & E-Commerce Ledgers: Safely evolving orders and payments tables without maintenance windows.
  • 32-bit to 64-bit Primary Key Migrations: Migrating INT PKs before overflow via Expand-Contract shadow columns.
  • CI/CD Migration Gates: Automated linters (Squawk / Atlas) blocking unguarded ALTER TABLEs in PRs.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why can even a fast metadata-only `ALTER TABLE` cause a total outage on a busy PostgreSQL table?

Recommended Learning Flow