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.
AI Generated with Qwen 3.0 via CometAPIEvery 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.
| Phase | Action | Reversible? | Code deploy |
|---|---|---|---|
| 0. Prepare | Add new column/table/index — additive only | Yes | None |
| 1. Dual write | New code writes old and new | Yes | Deploy A |
| 2. Backfill | Resumable batched job fills history | Yes | Job |
| 3. Dual read → new read | Shadow-compare, then flip reads | Yes | Deploy B |
| 4. Stop old writes | Old column frozen | Yes | Deploy C |
| 5. Contract | Drop old column/table/trigger | No | Deploy 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.
-- 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.
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:
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:
-- 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 COLUMNnullable, no defaultADD COLUMNwith a non-volatile default (PostgreSQL 11+)CREATE INDEX CONCURRENTLY/DROP INDEX CONCURRENTLY(cannot run inside a transaction)ADD CONSTRAINT ... CHECK (...) NOT VALIDVALIDATE CONSTRAINT(takesSHARE UPDATE EXCLUSIVEonly)CREATE TABLE,DROP TABLEfor objects no live code touches
Never safe in a single step:
ALTER COLUMN ... TYPEon a populated table (rewrite + full-duration lock)RENAME COLUMN/RENAME TABLEduring a rolling deploySET NOT NULLwithout a pre-validatedCHECKADD COLUMN ... DEFAULT gen_random_uuid()(volatile → rewrite)VACUUM FULL(rewrite,ACCESS EXCLUSIVEfor 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:
-- 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:
-- 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:
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.
// 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.
// 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.
- 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 withBACKWARDcompatibility so a consumer built against an old schema can always read new records. - 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_timeouton replicas too. - 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:
expand DDL → deploy dual-write code → backfill job → verify divergence = 0
→ deploy new-read code → bake 7–14 days → contract DDL → cleanup deployRollback 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_lockswaiters on the target relation, andpg_stat_activitywait_event_type = 'Lock'- p99 latency on the affected service endpoints
- Logical replication lag and
pg_stat_replicationreplay_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:
- name: Reject unsafe DDL
run: |
squawk --config .squawk.toml migrations/*.sql
sqlfluff lint migrations/ --dialect postgresSquawk 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) andstatement_timeoutset 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 addedNOT VALIDthenVALIDATEd - 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 COLUMNis 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. Setidle_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
- PostgreSQL Global Development Group — ALTER TABLE (non-volatile defaults,
NOT VALID/VALIDATE,SET NOT NULLoptimization) - PostgreSQL Global Development Group — CREATE INDEX, including CONCURRENTLY
- PostgreSQL Global Development Group — Explicit Locking and lock modes
- PostgreSQL Global Development Group — Monitoring pg_stat_replication
- Oracle — MySQL 8.0 Online DDL Operations and ALGORITHM/LOCK clauses
- GitHub — gh-ost: GitHub's online schema migration tool for MySQL
- Percona — pt-online-schema-change documentation
- Martin Fowler — ParallelChange (expand/contract) pattern
- Redgate — Flyway documentation: schema history table and locking
- Liquibase — DATABASECHANGELOGLOCK and changeset execution
- Debezium — Schema evolution and compatibility
- Confluent — Schema Registry schema evolution and compatibility types
- Amazon Web Services — RDS Blue/Green Deployments: logical replication requirements
- Google SRE — Canarying Releases, SRE Workbook
- Squawk — PostgreSQL migration linter
Discussion (0)
Continue Reading
More production-grade engineering deep dives and architectural guides

Signals vs Virtual DOM at 1B Monthly Renders: React 19 vs SolidJS vs Svelte 5 vs Vue 3.5 — Measured p99 Frame Time, Memory, Bundle Size, and True Cost per 1M Updates
We rebuilt the same 10,000-row update workload in React 19, SolidJS, Svelte 5, and Vue 3.5 and measured p99 frame time, retained heap, bundle weight, and a defensible cost model per million updates. The numbers show that architecture, not micro-optimization, decides whether your tail latency survives a billion renders.

Postgres Egress Cost Optimization: Cutting Network Bandwidth by 70% in High-Throughput APIs
Your Postgres bill is rarely about CPU — it is about bytes leaving the database, crossing an availability zone, and traversing a NAT gateway. Here is the systematic playbook we used to cut data transfer cost by 70% in a high-throughput API without touching query latency.

Gemini 4 Neon: A Principal Engineer's Deep Dive into the Architecture
Gemini 4 Neon is a serving-systems release disguised as a model launch: the interesting engineering lives in its control plane, cache fabric, and streaming transport, not the benchmark table. This analysis breaks down the four-plane topology, the latency budget you must own, and the production patterns that keep a Neon integration from melting down under load.