Zero-Downtime Database Migrations: An Expand/Contract Playbook for Distributed Production Systems
Renaming a column should never page an on-call engineer. This playbook breaks schema evolution into a four-phase, backwards-compatible protocol — expand, dual-write, backfill, contract — with lock-aware DDL and resumable backfills you can ship today.
AI Generated with Qwen 3.0 via CometAPIRenaming a column should never be a pager-worthy event. Yet in distributed production it routinely is: a rolling deploy guarantees that version N and version N-1 of your service are serving traffic against the same schema simultaneously, and a naive ALTER TABLE ... RENAME COLUMN instantly breaks half your fleet. This guide is the playbook for shipping schema evolution at scale — expand/contract, N-1 compatibility, lock-aware DDL, and resumable backfills — with runnable code you can drop into your migration pipeline today.
Why "Just Run the Migration" Breaks in Distributed Production
Three independent failure modes compound each other.
1. The compatibility window. Kubernetes RollingUpdate, ECS blue/green, and Lambda alias shifting all guarantee that at least two code versions exist against one schema for the duration of a deploy — often for hours if you run canaries. Any schema change must therefore be readable and writable by both versions.
2. Lock queue amplification. In PostgreSQL, most ALTER TABLE variants take an ACCESS EXCLUSIVE lock. That lock must wait for every in-flight query to finish — and once it is queued, every new query queues behind it, because PostgreSQL lock acquisition is FIFO. One 90-second analytics SELECT can turn a 5ms DDL into a full outage for every query touching the table.
3. Unbounded backfills. Rewriting 400 million rows in a single UPDATE produces a long transaction, a massive WAL burst, replication lag, and bloat that VACUUM will chase for days.
The architectural answer is to stop treating a migration as one atomic event and start treating it as a multi-deploy, backwards-compatible protocol.
The Expand/Contract (Parallel Change) Pattern
Every schema change decomposes into four phases, each independently deployable and independently reversible:
Deploy 1 ──► Expand : add new column / table / index (nullable, no readers)
Deploy 2 ──► Dual : code writes BOTH old and new; backfill history
Deploy 3 ──► Switch : code reads NEW; old column becomes write-only
Deploy 4 ──► Contract : drop old column after N-1 is fully drainedThe invariant: the database schema is always a superset of what any live code version needs.
Phase 1 — Expand: Add Without Locking
Two rules govern expansion: never rewrite the table, and never hold a lock you cannot abandon.
-- 20240612_01_expand.sql (transactional, fast)
SET lock_timeout = '3s';
SET statement_timeout = '15s';
ALTER TABLE users
ADD COLUMN IF NOT EXISTS email_normalized text;
-- Reject garbage immediately for NEW rows, without scanning history.
ALTER TABLE users
ADD CONSTRAINT users_email_normalized_len_chk
CHECK (email_normalized IS NULL OR length(email_normalized) <= 320)
NOT VALID;-- 20240612_02_expand_index.sql -- MUST run outside a transaction block.
-- CONCURRENTLY cannot be wrapped in BEGIN/COMMIT.
SET lock_timeout = '3s';
SET statement_timeout = 0; -- index builds on large tables are long
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_email_normalized
ON users (email_normalized);NOT VALID is the single most underused DDL primitive in PostgreSQL: it installs the constraint for new writes in milliseconds and defers the historical scan to an explicit, interruptible VALIDATE CONSTRAINT. Nullable ADD COLUMN is catalog-only (no rewrite) since PostgreSQL 11.
Phase 2 — Dual-Write Behind a Flag
The moment the column exists, ship code that writes both representations. Ship it one deploy ahead of any read change; the N-1 replica of your code must remain correct.
import type { Pool, PoolClient } from 'pg';
export type WriteMode = 'legacy' | 'dual' | 'normalized';
export interface CreateUserInput {
readonly id: string;
readonly email: string;
}
export class UserWriteRepository {
constructor(
private readonly pool: Pool,
private readonly currentMode: () => WriteMode,
) {}
async create(input: CreateUserInput): Promise<void> {
const mode = this.currentMode();
const normalized = input.email.trim().toLowerCase();
const client: PoolClient = await this.pool.connect();
try {
await client.query('BEGIN');
// Always write the legacy column: N-1 code still SELECTs it.
const { rowCount } = await client.query(
`INSERT INTO users (id, email, email_normalized)
VALUES ($1, $2, $3)
ON CONFLICT (id) DO UPDATE
SET email = EXCLUDED.email,
email_normalized = COALESCE(EXCLUDED.email_normalized, users.email_normalized)
RETURNING id`,
[input.id, input.email, mode === 'legacy' ? null : normalized],
);
if (rowCount !== 1) {
throw new Error(`expected 1 upserted row, got ${rowCount}`);
}
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK').catch(() => undefined);
throw new Error(`create user ${input.id} failed`, { cause: err });
} finally {
client.release();
}
}
}Note the COALESCE: if the flag flips back to legacy, a re-write must not null out a previously backfilled value. Dual-write bugs almost always look like this — a partial update clobbering the new field.
Phase 3 — Backfill With Bounded, Resumable Batches
Backfills must be idempotent, keyset-paginated, throttled, and lag-aware. Never use LIMIT/OFFSET (O(n²) and skippable), and never run one giant UPDATE.
import type { Pool } from 'pg';
export interface BackfillConfig {
readonly batchSize: number;
readonly sleepMs: number;
readonly maxReplicaLagSeconds: number;
}
const LAG_SQL = `
SELECT COALESCE(
EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp())), 0
)::float8 AS lag_seconds
`;
export async function backfillEmailNormalized(
primary: Pool,
replica: Pool,
cfg: BackfillConfig,
): Promise<{ processed: number }> {
let lastId = '';
let processed = 0;
for (;;) {
// Throttle on *replica* lag: readers must never see a stale world.
const { rows } = await replica.query<{ lag_seconds: number }>(LAG_SQL);
const lag = rows[0]?.lag_seconds ?? 0;
if (lag > cfg.maxReplicaLagSeconds) {
await sleep(cfg.sleepMs * 4);
continue;
}
const batch = await primary.query<{ id: string; email: string }>(
`UPDATE users
SET email_normalized = lower(btrim(email))
WHERE id IN (
SELECT id FROM users
WHERE email_normalized IS NULL
AND id > $1
ORDER BY id
LIMIT $2
FOR UPDATE SKIP LOCKED
)
RETURNING id, email`,
[lastId, cfg.batchSize],
);
if (batch.rowCount === 0) break;
processed += batch.rowCount;
lastId = batch.rows[batch.rowCount - 1]!.id; // keyset cursor
await sleep(cfg.sleepMs);
}
return { processed };
}
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));FOR UPDATE SKIP LOCKED makes the backfill safe to run as N parallel workers — it never blocks live traffic and never double-processes a row. Once the backfill reports zero remaining (SELECT count(*) FROM users WHERE email_normalized IS NULL is 0 and stays 0 for a full traffic cycle), run VALIDATE CONSTRAINT and move to reads.
Phase 4 — Contract: Delete Only After the Long Tail Is Gone
Dropping a column is irreversible and instantly fatal to any straggler process — a forgotten cron job, an analytics pipeline, a customer's BI dashboard pointed at your replica. Gate the drop on evidence, not on a release calendar:
-- Run against query telemetry, not vibes.
SELECT calls, total_exec_time
FROM pg_stat_statements
WHERE query ILIKE '%users.email%'
AND query NOT ILIKE '%email_normalized%'
AND calls > 0;Only when this returns zero rows for a full deploy cycle (ideally seven days) do you ship the contract migration.
The N-1 Backwards-Compatibility Cheat Sheet
| DDL operation | Safe in a rolling deploy? | Correct approach |
|---|---|---|
ADD COLUMN (nullable, no default) | ✅ Yes | Catalog-only since PG 11 |
ADD COLUMN ... DEFAULT <non-volatile> | ✅ Yes (PG 11+) | Stored in pg_attribute.attmissingval |
ADD COLUMN ... DEFAULT now() | ❌ No | Table rewrite — add nullable, backfill, then set default |
ALTER COLUMN TYPE | ❌ No | New column + dual-write + swap |
RENAME COLUMN / RENAME TABLE | ❌ No | Add new name, dual-write, drop old later |
DROP COLUMN | ❌ Until N-1 is gone | Contract phase only |
ADD CONSTRAINT (plain) | ❌ Full scan under ACCESS EXCLUSIVE | NOT VALID → VALIDATE CONSTRAINT |
SET NOT NULL | ⚠️ Only with a validated CHECK | PG 12+ skips the scan if a matching validated CHECK exists |
CREATE INDEX | ❌ Blocks writes | CREATE INDEX CONCURRENTLY |
CREATE INDEX CONCURRENTLY | ✅ Yes | Cannot run inside a transaction block |
Lock Hygiene: Turn Outages Into Retryable Errors
Wrap every DDL statement in a harness that sets lock_timeout and retries on lock_not_available (55P03) and deadlock_detected (40P01). A migration that fails fast and retries is strictly safer than one that blocks the world for 40 minutes.
import type { Client } from 'pg';
const ADVISORY_LOCK_KEY = 917_236_451; // fixed per database
export interface Migration {
readonly id: string;
readonly statements: readonly string[];
}
export async function runMigration(client: Client, migration: Migration): Promise<void> {
await client.query('SELECT pg_advisory_lock($1)', [ADVISORY_LOCK_KEY]);
try {
for (const [index, statement] of migration.statements.entries()) {
const label = `${migration.id}#${index}`;
await retryOnContention(async () => {
// set_config(..., true) is the parameterizable SET LOCAL.
await client.query(`SELECT set_config('lock_timeout', '2500ms', true)`);
await client.query(`SELECT set_config('statement_timeout', '30s', true)`);
await client.query(statement);
}, label);
}
} finally {
await client.query('SELECT pg_advisory_unlock($1)', [ADVISORY_LOCK_KEY])
.catch(() => undefined);
}
}
async function retryOnContention(
fn: () => Promise<void>,
label: string,
attempts = 6,
): Promise<void> {
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
await fn();
return;
} catch (err: unknown) {
const code = (err as { code?: string }).code;
const retryable = code === '55P03' || code === '40P01';
if (!retryable || attempt === attempts) {
throw new Error(
`migration step failed: ${label} (sqlstate=${code ?? 'unknown'})`,
{ cause: err },
);
}
const backoff = 250 * 2 ** attempt + Math.floor(Math.random() * 100);
await new Promise<void>((r) => setTimeout(r, backoff));
}
}
}Index builds are the exception: CREATE INDEX CONCURRENTLY needs statement_timeout = 0 and a dedicated connection, because it cannot share a transaction with anything else.
Coordinating Migrations Across Services and Shards
- Order by artifact, not by wall-clock. Schema change → code change → cleanup. Each is a separately versioned release; never bundle DDL and the code that depends on it in one deploy.
- Sharded fleets. Run a coordinator per shard with a persistent ledger (
schema_migrations(shard_id, version, applied_at)), stagger execution, and abort the whole run if any shard's replica lag crosses threshold. - Event-driven contracts. Schema evolution does not stop at the database. Emit a
schema_versionin every event envelope and make consumers tolerate v1 and v2 for your full retention window. Avro/Protobuf with a schema registry inBACKWARDcompatibility mode catches incompatible changes in CI instead of in production. - Single-writer guarantee. Use a distributed lock — a Kubernetes Lease, a DynamoDB conditional write, or a Postgres advisory lock — so two autoscaled migration jobs can never race.
Operational Checklist Before You Press Enter
- Migration is categorized: expand / migrate / contract (separate PRs).
lock_timeoutis set on every DDL session.CREATE INDEXusesCONCURRENTLYand runs outside a transaction.- Constraints are added
NOT VALID, validated in a separate step. - Backfill is keyset-paginated, idempotent, and checks replica lag.
- Feature flags exist for both the read path and the write path.
- Rollback plan is a code rollback, not a reverse DDL.
pg_stat_statementsshows zero straggler references before contract.- Runbook documents the exact metric that means abort.
Pitfalls That Will Bite You
- ORM auto-migration in production.
Hibernate ddl-auto=update,GORM AutoMigrate, andprisma migrate devare development accelerators. They generate non-concurrent indexes, unboundedALTERs, and destructive diffs. Useprisma migrate deploy, Flyway, Liquibase, or Atlas with reviewed, hand-audited SQL. - *`SELECT ` in application code.** It silently couples your code to the column list, and adding a wide column can double payload sizes overnight.
- Long-lived idle transactions.
idle_in_transaction_session_timeoutis not optional — a leaked pool connection holds locks indefinitely and turns your DDL into a 100% error rate. - Ignoring bloat. A 400M-row backfill leaves dead tuples; schedule
VACUUM (ANALYZE)afterward or watch autovacuum fall permanently behind. - Assuming replica lag is small. Backfills on the primary can push replicas minutes behind, so your read-switch deploy will serve stale data unless lag is a first-class gate.
Sources & Technical References
- PostgreSQL Documentation —
ALTER TABLE(lock levels,NOT VALID,VALIDATE CONSTRAINT): https://www.postgresql.org/docs/current/sql-altertable.html - PostgreSQL Documentation —
CREATE INDEXandCONCURRENTLY: https://www.postgresql.org/docs/current/sql-createindex.html - PostgreSQL Documentation — Explicit Locking and lock compatibility: https://www.postgresql.org/docs/current/explicit-locking.html
- PostgreSQL Documentation — System Administration Functions (
set_config,pg_advisory_lock): https://www.postgresql.org/docs/current/functions-admin.html - PostgreSQL Documentation —
pg_stat_statements: https://www.postgresql.org/docs/current/pgstatstatements.html - PostgreSQL 11 Release Notes — fast default column addition: https://www.postgresql.org/docs/11/release-11.html
- PostgreSQL Wiki — Lock dependency information and monitoring: https://wiki.postgresql.org/wiki/Lock_dependency_information
- Martin Fowler — Parallel Change (expand/contract) pattern: https://martinfowler.com/bliki/ParallelChange.html
- Braintree Engineering — PostgreSQL at scale: schema changes without downtime: https://medium.com/braintree-product-technology/postgresql-at-scale-database-schema-changes-without-downtime-20d3749ed680
- GitHub — gh-ost, online schema migration for MySQL: https://github.com/github/gh-ost
- Percona Toolkit —
pt-online-schema-change: https://docs.percona.com/percona-toolkit/pt-online-schema-change.html - Kubernetes Documentation — Rolling updates and Deployment strategy: https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#rolling-update-deployment
- Confluent Schema Registry — Avro schema compatibility modes: https://docs.confluent.io/platform/current/schema-registry/fundamentals/avro.html
- Google SRE Workbook — Canarying releases: https://sre.google/workbook/canarying-releases/
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.