●CC 2.1.332 — No new Claude Code release over the weekend. 2.1.332 (11/25) is still current●ANALYTICS — A fix to search counts in the Enterprise Analytics API may raise numbers from 11/17 onward●SONNET 4.5 — Today, 11/30, is Sonnet 4.5's last day on the Claude API. Move to claude-sonnet-5-5●USAGE — Some users report weekly usage jumping right after upgrading to a higher plan●NEW — New: Does what a Project remembers carry over into your everyday chats?●BILLING — More readers are looking for what to check when a payment won't go through●CC 2.1.332 — No new Claude Code release over the weekend. 2.1.332 (11/25) is still current●ANALYTICS — A fix to search counts in the Enterprise Analytics API may raise numbers from 11/17 onward●SONNET 4.5 — Today, 11/30, is Sonnet 4.5's last day on the Claude API. Move to claude-sonnet-5-5●USAGE — Some users report weekly usage jumping right after upgrading to a higher plan●NEW — New: Does what a Project remembers carry over into your everyday chats?●BILLING — More readers are looking for what to check when a payment won't go through
Designing Zero-Downtime Database Migrations with Claude Code: A Production Operations Guide
A production guide to designing zero-downtime database migrations with Claude Code. Covers Expand-Contract, NOT NULL additions, renames, backfills, and subagent reviews — practical patterns that survive real production traffic.
Database migrations are the quiet kind of work most days, but on the rare day they break in production, they break everything. I once shipped an ALTER TABLE ... ADD COLUMN ... NOT NULL at 2 AM on a PostgreSQL instance that hadn't yet upgraded past version 10, and the full-table rewrite locked out our API for thirty minutes. Application retries amplified the lock contention, and by the time I rolled back, dashboards were lit up red. I've never forgotten the sweat of that night.
The hard part is that the danger of a migration isn't visible from reading the SQL alone. Whether one line of DDL takes a millisecond or scans every row depends entirely on the database engine, the version, and the table size. In my experience, Claude Code is good at spotting these invisible landmines and rewriting migrations into safer multi-step shapes. What follows are the patterns I now use to evolve schemas without taking the system offline, paired with how I drive Claude Code through each step.
The SQL below assumes PostgreSQL 12 or later (checked against the official docs as of November 2026). Where 11 and earlier behave differently, I say so in place.
Why Migrations Take Down Production
In my own incident reviews, the migrations that take a system down almost always fall into one of three categories. The first is running long-locking DDL directly against production. Statements like ALTER TABLE ... ADD COLUMN ... NOT NULL DEFAULT 'foo' are instant on PostgreSQL 11 and later, but they trigger a full table rewrite on older versions and on certain managed services. On a hundred-million-row table, that translates to minutes of locked tables and a flood of timeouts.
The second category is shipping the application code and the schema in the wrong order. If the new schema reaches production while old replicas still serve traffic, the old code starts referencing columns that no longer exist and returns 500s. Reverse the order and the new code can't find columns it expects. There's no path through this except careful sequencing.
The third category is launching a migration without a rollback plan. The moment a DROP COLUMN lands, the data is gone. By the time you realize something downstream broke, restoring from backup means losing every write that happened in between. The Expand-Contract pattern exists precisely to make these three categories impossible.
Three Principles That Make Zero Downtime Possible
Expand-Contract works because it enforces three principles. The first principle is that you always pass through a state where both the old code and the new code can run. You create a window — sometimes hours, sometimes weeks — where the application can read and write either shape, and you advance the deploys through that window step by step.
The second principle is that you only run DDL that completes in a fraction of a second on production. Anything longer gets decomposed into smaller DDL, or handed to an online schema-change tool. Those tools are engine-specific: gh-ost is for MySQL, while on PostgreSQL the usual name is pg_repack — and pg_repack exists to rebuild bloated tables, not to run arbitrary ALTER TABLE statements for you. If a single statement might lock a hot table for more than about a second, it doesn't go to production as-is.
The third principle is that every migration has a real reverse direction, and the reverse direction doesn't lose data. You write down migrations that you'd actually run if production caught fire, not toy ones that satisfy a linter.
I make these explicit to Claude Code by keeping a section in my project's CLAUDE.md like this:
# Migration Operations Rules## Mandatory- DDL applied to production must complete in under 1 second- New columns are added as NULLable, then promoted to NOT NULL in a later migration- Column drops follow: remove all code references → deploy → DROP COLUMN- Renames follow: add new column → dual-write → switch reads → drop old column- Every migration ships with a real, tested down migration## Required Review Items- Estimated affected row count (verified with EXPLAIN or COUNT)- Predicted lock time (measured against a realistic test database)- Compatibility with the previous deployment (does old code keep running?)
Once that's in place, Claude Code naturally generates migrations that respect the rules instead of taking the dangerous shortcut.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦If you've ever broken up a sweat watching a production migration stall mid-deploy, you'll learn the Expand-Contract patterns to ship without downtime starting today
✦You'll get concrete SQL and code for the riskiest changes — NOT NULL additions, column renames, type changes — broken into safe five-step deploys
✦You'll learn how to delegate migration reviews to a Claude Code subagent so production landmines get caught before they reach a real database
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Expand-Contract splits a schema change into two phases — Expand, where the new shape is added; Contract, where the old shape is removed — and threads a deploy of both-old-and-new-coexist code in between. As a concrete example, suppose I want to rename email to email_address on the users table. Running ALTER TABLE users RENAME COLUMN email TO email_address outright would break every old replica the moment it executed. Expand-Contract turns that single risky operation into a sequence:
-- 1. Expand: add the new column (nullable for now)ALTER TABLE users ADD COLUMN email_address VARCHAR(255);CREATE INDEX CONCURRENTLY idx_users_email_address ON users(email_address);-- 2. Backfill: copy data into the new column in batches-- Application now dual-writes to both columns and reads from the old oneUPDATE users SET email_address = emailWHERE email_address IS NULL AND id BETWEEN 1 AND 10000;-- 3. Switch: deploy a version that reads from email_address-- but still writes to both, so we can roll back-- 4. Contract: drop the old column once we're confidentALTER TABLE users DROP COLUMN email;
When I ask Claude Code, "I want to rename email to email_address. Walk me through Expand-Contract," it produces the four migrations above as separate files. The discipline that matters is making each step deployable on its own and reversible until the very last drop.
The pattern took me a while to internalize. The mental gap between "I want to rename a column" and "this is a four-stage deploy" is wide enough that I used to talk myself out of doing it properly. With Claude Code in the loop, that cognitive cost largely disappeared. I name the files numerically — 001_add_email_address.sql, 002_backfill_email_address.sql, 003_switch_email_reads.sql, 004_drop_email.sql — and Claude Code reliably constructs the next file in the sequence with full awareness of what the previous ones did.
Adding a NOT NULL Column Safely — A Five-Stage Deploy
Adding a NOT NULL column is one of the most accident-prone migrations, even within Expand-Contract. The naive form, ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'active', completes instantly on PostgreSQL 11+ via a metadata-only change, but on older versions and certain managed services it rewrites every row. On a million-row table, that's minutes of production lock.
The five-stage deploy I recommend is as follows.
In stage one, add a NULL-able column.
ALTER TABLE orders ADD COLUMN status VARCHAR(20);
In stage two, deploy an application version where new inserts always supply status, and existing reads tolerate NULL.
// orders.ts — guarantee status on insert from the application sideasync function createOrder(input: OrderInput) { return db.insert(orders).values({ ...input, status: input.status ?? 'active', // defaulted in app code, not DB });}
In stage three, run a backfill against existing rows. The non-negotiable rule is that batches stay small (1,000 to 10,000 rows) and yield with a sleep between them.
-- backfill in 10k-row batches with 100ms pausesDO $$DECLARE batch_size INT := 10000; rows_updated INT;BEGIN LOOP UPDATE orders SET status = 'active' WHERE status IS NULL AND id IN ( SELECT id FROM orders WHERE status IS NULL LIMIT batch_size ); GET DIAGNOSTICS rows_updated = ROW_COUNT; EXIT WHEN rows_updated = 0; COMMIT; -- commit each batch so locks and WAL don't pile up PERFORM pg_sleep(0.1); END LOOP;END $$;
The single COMMIT is easy to miss. A DO block is one transaction, so without it the small batches still hold their row locks until the very end, and pg_sleep just stretches how long you hold them. I nearly shipped it that way, and only noticed on staging the day before. COMMIT inside DO works on PostgreSQL 11 and later, and fails if the block is called from inside BEGIN ... COMMIT. If your migration tool wraps every file in a transaction, move the backfill into its own script.
In stage four, add a CHECK constraint as NOT VALID first. This is the trick that unlocks zero-downtime NOT NULL: NOT VALID adds the constraint immediately without scanning existing rows, and a separate VALIDATE CONSTRAINT step then verifies the data under a much weaker lock.
-- add the constraint instantly, without scanning existing rowsALTER TABLE orders ADD CONSTRAINT orders_status_not_null CHECK (status IS NOT NULL) NOT VALID;-- validate later, under SHARE UPDATE EXCLUSIVE (allows reads/writes)ALTER TABLE orders VALIDATE CONSTRAINT orders_status_not_null;
In stage five, you finally promote the column to a real NOT NULL. Because the validated CHECK constraint already proved every row complies, PostgreSQL 12 and later skips the full scan and finishes instantly. On 11 and earlier the scan still runs here, so check your version before this stage.
ALTER TABLE orders ALTER COLUMN status SET NOT NULL;ALTER TABLE orders DROP CONSTRAINT orders_status_not_null;
Communicating this five-stage flow to Claude Code is as simple as recording the rule in CLAUDE.md and adding "follow the NOT NULL five-stage deploy" to the initial prompt. From there, Claude Code generates the migrations in the right order without further coaxing.
The Hard Cases — Renames and Type Changes
Renames and type changes are the trickiest Expand-Contract operations because they require a window where the same logical value lives in two places. The technique I rely on most is dual-write enforced by a database trigger.
-- mirror writes from the old column into the new oneCREATE OR REPLACE FUNCTION sync_email_to_email_address()RETURNS TRIGGER AS $$BEGIN IF TG_OP = 'INSERT' OR NEW.email IS DISTINCT FROM OLD.email THEN NEW.email_address := NEW.email; END IF; RETURN NEW;END;$$ LANGUAGE plpgsql;CREATE TRIGGER trg_sync_emailBEFORE INSERT OR UPDATE ON usersFOR EACH ROW EXECUTE FUNCTION sync_email_to_email_address();
I branch on TG_OP = 'INSERT' because OLD isn't assigned for inserts, and touching it raises an error. My first version tested OLD IS NULL instead, and it failed on every insert in staging.
Note that the trigger is one-directional: writes to the old column propagate to the new one, but not vice versa. Once application code has fully switched to the new column, the trigger is dropped — by then the old column should already be unused.
Type changes are even nastier. Changes like integer to bigint or text to jsonb make ALTER TABLE ... ALTER COLUMN ... TYPE rewrite the whole table under an exclusive lock, which is unacceptable on a large production table. Widening a length, such as varchar(50) to varchar(255), needs no rewrite on PostgreSQL 9.2 and later, so check first whether your change rewrites at all. When it does, the solution is the same Expand-Contract pattern, applied to types instead of names.
-- 1. add the new-type columnALTER TABLE products ADD COLUMN price_v2 BIGINT;-- 2. dual-write from application code-- async function updatePrice(id, price) {-- await db.update(products).set({ price, price_v2: price }).where(...);-- }-- 3. backfill in batchesUPDATE products SET price_v2 = price WHERE price_v2 IS NULL AND id BETWEEN 1 AND 10000;-- 4. switch reads to price_v2-- 5. drop the old column and renameALTER TABLE products DROP COLUMN price;ALTER TABLE products RENAME COLUMN price_v2 TO price;
The final RENAME COLUMN is itself fast, but it does take a brief lock. I run it during off-peak hours just to keep risk close to zero.
Breaking the Lock Queue — lock_timeout and Retries
Tracing that first bad night again later, I finally saw what had stopped the API. It wasn't how long the DDL ran. It was how long the DDL stood in line.
An ALTER TABLE waits for an exclusive lock whenever a long transaction is still open on the table. While it waits, every SELECT and INSERT that arrives afterwards queues up behind it. A statement that should take milliseconds ends up freezing everything behind it.
The fix is to refuse to wait. If the lock can't be had within a few seconds, back out and try again later.
BEGIN;SET LOCAL lock_timeout = '3s'; -- give up on the lock after 3 secondsSET LOCAL statement_timeout = '30s'; -- cap the statement itself tooALTER TABLE orders ADD COLUMN status VARCHAR(20);COMMIT;
CREATE INDEX CONCURRENTLY can't run inside a transaction, so set lock_timeout at the session level before it instead. After backing out, retry with growing gaps.
for i in 1 2 3 4 5; do psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f 001_add_status.sql && break echo "lock timeout, retry ${i}" sleep $((i * 5))done
Always put a ceiling on the retries. After five failures, go look for the session holding a long transaction in pg_stat_activity instead. I ask Claude Code to add the timeout and retry wrapper, then check the numbers it picked myself.
A DDL should only wait as long as it can afford to. Since adopting that rule, my stomach has had far fewer late-night deploys to complain about.
Run It Directly, Split It Up, or Hand It to a Tool?
With all these options on the table, it's fair to wonder which one a given change needs. This is the table I decide with.
Option
Fits these changes
Lock behavior
Effort
Direct DDL (with lock_timeout)
Nullable column adds, column adds with a non-volatile DEFAULT, widening a varchar, adding constraints as NOT VALID
A brief strong lock — the danger is the queue, not the runtime
Small. One file, one deploy
Expand-Contract
Renames, type changes, NOT NULL, dropping columns or tables
Each step is short DDL, at the cost of several deploys
Large. You design a window where old and new code coexist
Online schema-change tool
Any ALTER on MySQL (gh-ost and friends); table bloat on PostgreSQL (pg_repack)
Works on a copy, then swaps under a short lock
Medium. Tool operations plus free disk for a copy of the table
First find out whether the change rewrites the table. If it doesn't, run it directly; if it does, use Expand-Contract; reach for a tool only when one table is too big even for that. On a test database you can check by comparing SELECT pg_relation_filenode('orders'); before and after the DDL — if the value changed, the table was rebuilt from scratch.
Backfill Strategy for Online Migrations
Backfills are usually the longest stage of a zero-downtime migration. On a hundred-million-row table, a careless backfill produces replication lag, and reads against replicas suddenly return stale data. Three strategies keep this under control in practice.
The first is tuning batch size and sleep adaptively. I update 1,000 to 10,000 rows per batch and adjust the inter-batch sleep based on observed replica lag. Asking Claude Code for "an adaptive backfill script that doubles its sleep when replica lag exceeds 100 ms" produces something like the following:
// backfill.ts — replica-lag-aware backfill (assumes Drizzle ORM + node-postgres)import { sql } from 'drizzle-orm';import { db } from './db';async function backfillEmailAddress() { let sleepMs = 100; let lastId = 0; const batchSize = 5000; while (true) { const start = Date.now(); const result = await db.execute(sql` WITH batch AS ( SELECT id FROM users WHERE email_address IS NULL AND id > ${lastId} ORDER BY id LIMIT ${batchSize} ) UPDATE users u SET email_address = u.email FROM batch WHERE u.id = batch.id RETURNING u.id `); if (result.rows.length === 0) break; lastId = Math.max(...result.rows.map(r => r.id)); const lag = await getReplicaLagMs(); if (lag > 100) { sleepMs = Math.min(sleepMs * 2, 5000); console.log(`Lag ${lag}ms detected, increasing sleep to ${sleepMs}ms`); } else if (lag < 50 && sleepMs > 100) { sleepMs = Math.max(sleepMs / 2, 100); } const elapsed = Date.now() - start; console.log(`Batch updated ${result.rows.length} rows in ${elapsed}ms, sleeping ${sleepMs}ms`); await new Promise(r => setTimeout(r, sleepMs)); }}// Read replay lag for every replica from the primary (PostgreSQL 10+)async function getReplicaLagMs(): Promise<number> { const result = await db.execute(sql` SELECT COALESCE(MAX(EXTRACT(EPOCH FROM replay_lag)) * 1000, 0) AS lag_ms FROM pg_stat_replication `); return Number(result.rows[0]?.lag_ms ?? 0);}backfillEmailAddress().catch(console.error);
The lag function is where an earlier version of this script was quietly wrong. pg_last_xact_replay_timestamp() only means something on a replica; called on the primary — which is where the backfill is connected — it returns NULL. The ?? 0 then reads lag as zero forever, and the adaptive throttle never kicks in. From the primary, the right source is replay_lag in pg_stat_replication. That column can drop back to NULL once a replica has caught up and gone idle, so COALESCE treats it as zero. And because node-postgres hands numeric values back as strings, Number() turns it into something you can compare. Note too that PostgreSQL's UPDATE has no ORDER BY or LIMIT of its own, which is why the batch is picked in a CTE first.
The second strategy is deferring index creation. Indexes fragment quickly during a backfill, so I use CREATE INDEX CONCURRENTLY after the backfill completes. CONCURRENTLY is slower than a regular CREATE INDEX but doesn't block writes, which is the constraint that actually matters in production.
The third strategy is making backfills idempotent. Every UPDATE carries a WHERE email_address IS NULL (or equivalent) clause so that a script can be safely killed and restarted. I learned this the hard way after a non-idempotent backfill died at an unknown row count and I had no clean way to resume.
Reverse Migrations Are Part of the Design
Rollback isn't an emergency parachute — it's a constraint that shapes how you write the original migration. Three rules I follow without exception.
First, never write a down that destroys data. If up adds a column and inserts rows, a corresponding DROP COLUMN in down deletes everything that was written in between. For at least a week after I ship a destructive change, my down migrations only flip application reads back to the old column; they don't drop anything until I'm confident.
Second, test the rollback in CI. My migration pipeline runs up, then down, then up again, and asserts the row counts and shape match. I ask Claude Code for "a Vitest test that runs up→down→up three times and verifies row preservation," and the resulting test catches subtle data-losing rollbacks before they ever reach production.
Third, always take a targeted backup before destructive operations. pg_dump can carve out a table but not a single column, so before a DROP COLUMN I export just the primary key and the doomed column:
# before DROP COLUMN email, keep id + email somewhere safepsql "$DATABASE_URL" -v ON_ERROR_STOP=1 \ -c "\copy (SELECT id, email FROM users) TO 'users_email_$(date +%Y%m%d).csv' WITH (FORMAT csv, HEADER)"wc -l users_email_*.csv # should be SELECT count(*) FROM users, plus one header line
Restoring is a \copy ... FROM into a temp table and an UPDATE ... FROM. When I ask Claude Code to write that restore, I ask it to start with a row-count check.
Reviewing Migrations with a Claude Code Subagent
Migrations written alone tend to develop blind spots. The single highest-value habit I've adopted is running a Claude Code subagent as a reviewer before any production migration ships. I keep a migration-reviewer agent definition in .claude/agents/migration-reviewer.md and route every migration through it.
---name: migration-reviewerdescription: Reviews DB migration files and flags risks of production incidents---You are a senior DBA with 20 years of PostgreSQL production experience.For each migration file you receive, evaluate against:1. Lock duration: how long could this DDL hold a lock on a hot table?2. Downtime: would the previous deploy break against this schema?3. Rollback: does down lose real user data?4. Performance: are batched backfills, replica lag, and index strategy sound?5. Idempotency: can this script be safely killed and restarted?Reply with PASS / WARN / FAIL per item plus a specific suggested fix.A single FAIL means we do not ship.
My first version of this lived in .claude/hooks/pre-migrate.ts and blocked whenever the output contained the string FAIL. Looking back, that was wrong twice over. Claude Code hooks are commands registered under hooks in settings.json that fire on events such as tool calls — dropping a file into a folder runs nothing. And the reviewer's reply naturally echoes "PASS / WARN / FAIL" while explaining its rubric, so includes('FAIL') blocked every single run.
These days it's a plain script I run before pnpm migrate:plan, and the verdict is pinned to the last line:
#!/usr/bin/env bash# scripts/review-migration.sh — run before planning any migrationset -euo pipefailFILE="${1:?pass a migration file}"OUT=$(timeout 300 claude -p \ "Use the migration-reviewer subagent to review ${FILE}. End with exactly one line: VERDICT: PASS, VERDICT: WARN, or VERDICT: FAIL." \ --allowedTools "Read" "Agent" < /dev/null) || { echo "review could not run (exit $?)"; exit 2; }echo "$OUT"VERDICT=$(printf '%s\n' "$OUT" | grep -Eo '^VERDICT: (PASS|WARN|FAIL)$' | tail -1 || true)case "$VERDICT" in "VERDICT: PASS") exit 0 ;; "VERDICT: WARN") echo "⚠️ WARN: read the notes before going on"; exit 0 ;; *) echo "❌ FAIL or no verdict — stopping here"; exit 1 ;;esac
I chain it as bash scripts/review-migration.sh migrations/0042_add_status.sql && pnpm migrate:plan. A missing verdict line also stops the run; on the day a timeout or an expired login returns empty output, I don't want that read as a pass.
One more detail: the tool Claude Code uses to launch subagents was renamed from Task to Agent in v2.1.63 (confirmed in GitHub issue #29677). If any of your PreToolUse hooks match on Task, update them to Agent, or they'll silently stop firing.
What this reviewer is good at is asking, every time, the question I tend to skip — will the previous deploy still run against this schema? What it can't do is measure lock time. I'll come back to that line in the misconceptions section. The deeper subagent patterns are covered in the Claude Code Subagent Parallel Execution Guide, and most of those techniques apply just as well to non-migration work.
Working With Modern ORMs — Drizzle, Prisma, and Beyond
Modern ORMs introduce their own migration semantics, and each one has friction points worth understanding before you trust them with production schema changes. The patterns above translate directly, but the surface area looks different in each tool.
Drizzle ORM (drizzle-kit) generates migrations from schema diffs, which is convenient — but a diff tool reasons about the end state, not about whether old code can keep running in between. A text to varchar(255) change looks like one harmless line in the generated SQL. I always inspect the generated SQL before running it, and I ask Claude Code to "compare this Drizzle migration against the Expand-Contract rules in CLAUDE.md and flag anything risky." That review step has caught bugs the diff tool was happy to let through.
Prisma's migrate dev workflow is friendlier in development but more dangerous in production because it tends to generate single-step migrations for renames. Generating the file with prisma migrate dev --create-only and rewriting the SQL by hand into Expand-Contract form before applying it keeps you in control. The migrations Claude Code generates here are more conservative than the auto-diff output, so this is one place where letting an AI rewrite the auto-generated SQL into Expand-Contract form pays for itself within a few migrations.
Outside the JavaScript ecosystem, Rails has the strong_migrations gem, which detects and blocks dangerous operations, and Django ships lock-friendly operations such as AddIndexConcurrently in django.contrib.postgres.operations. The pattern is the same: trust the framework for the easy cases, but write or rewrite anything risky by hand using the principles in this guide.
Common Pitfalls — Mistakes That Reach Production
Even with Expand-Contract internalized, three classes of mistakes still find their way into production. Knowing them in advance is most of the defense.
The first pitfall is forgetting that adding a foreign key takes a SHARE ROW EXCLUSIVE lock on both the child table and the referenced parent. Adding REFERENCES other_table(id) makes writes to both tables wait until every row has been validated. On a hot table, this is enough to stall production. The fix is the same NOT VALID trick used for CHECK constraints — add the foreign key as NOT VALID, then validate it later under a weaker lock.
-- avoid the long lock by deferring validationALTER TABLE orders ADD CONSTRAINT orders_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) NOT VALID;ALTER TABLE orders VALIDATE CONSTRAINT orders_user_id_fkey;
The second pitfall is partial index creation that fails halfway and leaves the database in an awkward state. CREATE INDEX CONCURRENTLY does not run inside a transaction, so a failed run leaves an INVALID index that still consumes disk and confuses the query planner. The remedy is to detect and clean up these stale indexes as part of the migration runner:
-- find and drop any invalid indexes left behind by failed CONCURRENTLY runsSELECT indexrelid::regclass AS invalid_indexFROM pg_index WHERE NOT indisvalid;-- drop them explicitly, also CONCURRENTLYDROP INDEX CONCURRENTLY IF EXISTS idx_users_email_address;
I keep a small Claude Code skill that scans for invalid indexes after every migration run and surfaces them in the logs.
The third pitfall is ignoring how connection pools interact with schema changes. A prepared statement assumes the table shape it was created against. After a column is added or dropped, a statement built on SELECT * can fail with cached plan must not change result type; after a rename, one that names the old column returns column ... does not exist. PgBouncer only supports prepared statements in transaction pooling from 1.21 onward, with max_prepared_statements set.
The catch is that issuing DEALLOCATE ALL from the application doesn't reach every server connection behind the pool. Right after a migration I run RECONNECT <dbname> on the PgBouncer admin console, which rebuilds each server connection as it's released (per the PgBouncer usage docs). Without PgBouncer, recycling the application's own pool is the reliable route. Trimming SELECT * out of production queries makes the whole class of error rarer.
Diagnosing by Symptom
When something goes wrong in production, this is the table I open first. Error strings are exactly what PostgreSQL prints.
Symptom
Likely cause
How to confirm
Fix
API requests time out en masse right after an ALTER starts
The ALTER is queued behind a long transaction and everything else is queued behind the ALTER
Find rows with wait_event_type = 'Lock' in pg_stat_activity; use pg_blocking_pids(pid) to find the blocker
Cancel the ALTER with pg_cancel_backend, retry with lock_timeout
ERROR: invalid transaction termination
A COMMIT inside a DO block is running inside an outer transaction — usually one your migration tool opened
Check whether the tool wraps each file in a transaction
Move the backfill into its own file or script
column "email" does not exist right after a deploy
Contract ran while old code was still serving, or a prepared statement still holds the old definition
Check deployed versions and application_name in pg_stat_activity
Delay the DROP until old code is fully gone; behind a pool, RECONNECT
cached plan must not change result type
A SELECT * prepared statement survived a column add or drop
See whether errors cluster on particular connections
Rebuild server connections; stop using SELECT * in that query
CREATE INDEX CONCURRENTLY never finishes
It's waiting for transactions that started before it
Check phase in pg_stat_progress_create_index and xact_start in pg_stat_activity
End the long transaction; avoid the nightly batch window
An index isn't used, yet disk keeps growing
A failed CONCURRENTLY build left an INVALID index
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;
DROP INDEX CONCURRENTLY, then rebuild
Replicas return stale values during a backfill
Replay can't keep up with the WAL volume
replay_lag in pg_stat_replication on the primary
Smaller batches, longer sleeps; route reads to the primary for the window
Three Misconceptions Worth Correcting
"CONCURRENTLY means no locks at all."CREATE INDEX CONCURRENTLY takes SHARE UPDATE EXCLUSIVE, which doesn't block writes. But it waits for transactions that were already running, it can't run alongside a VACUUM or another concurrent index build on the same table, and it can't run inside a transaction block — which is where it collides with migration tools.
"On PostgreSQL 11+, ADD COLUMN with a DEFAULT is always instant." Only when the default is non-volatile (per the ALTER TABLE docs). now() is STABLE, so it's instant; clock_timestamp(), random(), or gen_random_uuid() as a default forces a full rewrite. If you need per-row values, add the column as nullable and backfill.
"If the subagent says PASS, it's safe." The reviewer reads the SQL text and nothing else. It doesn't know the row count, the long transactions running at that hour, or which PostgreSQL version production is on. I treat PASS as "nothing in the text breaks the pattern" and make timing decisions from numbers measured on a test database.
Observing the Migration in Real Time
A migration that runs blind is a migration that fails silently. The three signals I always watch live during a production run are query latency at the application edge, lock wait time at the database, and replica lag at the read fleet. Together they reveal the difference between a migration that's progressing normally and one that's about to overload the system.
The PostgreSQL view pg_stat_activity is the single most useful real-time tool. A query like the one below surfaces sessions blocked on the migration and tells you whether to keep going or abort:
SELECT pid, state, wait_event_type, wait_event, now() - xact_start AS xact_duration, LEFT(query, 80) AS query_previewFROM pg_stat_activityWHERE state != 'idle'ORDER BY xact_duration DESC NULLS LASTLIMIT 20;
I ask Claude Code to generate a small terminal dashboard that polls this view every two seconds, color-coding rows by transaction duration. During a migration window I keep that dashboard open in one pane and the migration progress log in another. If a session goes red — meaning it's been blocked for more than thirty seconds — I have a decision to make in seconds, not minutes.
For replica lag, read replay_lag from pg_stat_replication on the primary, or pg_last_xact_replay_timestamp() when connected to the replica itself (it returns NULL on the primary). A small wrapper script that emits a metric to your monitoring stack every five seconds is enough to catch lag spikes early. Claude Code generates this kind of glue code reliably; the trick is to keep the metric ingestion path independent of the database being migrated, so a database hiccup doesn't blind the dashboard right when you need it most.
Migration Culture — Habits That Compound
Most migration disasters I've seen, including my own incident that night, were not caused by lack of knowledge. The right pattern was usually documented somewhere. The disasters happened because the engineer running the migration didn't have a habit that forced them to check.
Three habits compound the most over time. The first is writing the rollback before writing the forward migration. If the rollback is hard, that's information about the forward migration — usually that it's destroying data or violating Expand-Contract. Writing it first surfaces the problem early.
The second habit is announcing the migration in advance, even for small ones. A short post in a team channel that says "I'm running migration 0042 against production at 14:00 JST, expected duration 45 seconds, rollback in pinned thread" creates accountability and gives the rest of the team a chance to flag conflicts.
The third habit is treating the migration log like an artifact, not throwaway output. After the migration completes, I have Claude Code summarize what happened, what the lock times actually were, and whether anything needed manual intervention. That summary lives in the repo alongside the migration file. Six months later when someone runs into a similar pattern, the log is the most valuable reference they could ask for.
These habits look like overhead at first. They become invisible after a few weeks, and the migrations they protect against are exactly the kind that would have ended up as an incident report.
A Pre-Production Checklist
Here is the ten-item checklist I run through every time before applying a migration to production. Including it in your prompt to Claude Code is an effective way to keep nothing slipping through the cracks.
The first check is whether you've actually measured the migration on a test database with a comparable amount of data — not ten thousand rows, but ten million. The second is whether the predicted lock time is within your SLA. The third is whether the rollback procedure is written down in language a half-asleep on-call engineer can follow.
The fourth is whether replica-lag tuning and sleep tuning for any backfill have been finalized. The fifth is whether the application deploy sequence is written as a timeline that names which version is running at each Expand-Contract stage. The sixth is whether monitoring is ready: query latency, lock waits, and replica lag must all be on a dashboard during execution.
The seventh is whether stakeholders who care about the affected surface are notified ahead of time. The eighth is whether you have an emergency stop procedure already in your terminal — pg_cancel_backend(pid) ready to paste at a moment's notice. The ninth is whether a working log is set up for the operation; I create .claude/logs/migration-YYYYMMDD.md and have Claude Code record progress as the migration runs.
The tenth is whether a post-mortem is scheduled. Every production migration gets a post-mortem regardless of outcome, and asking Claude Code to draft the first version into _documents/postmortems/ makes the writeup happen instead of getting deferred forever.
The Next Thing You'll Trip On: Who Actually Runs the Migration
Once the process is in place, the next worry is whether Claude Code, mid-task, might run the production command itself. I found that writing "never run migrations against production" in CLAUDE.md wasn't enough, so I removed the ability with permission rules instead:
In .claude/settings.json, matching Bash calls are refused without a prompt. Patterns are string matches, though, so a differently phrased shell command can slip past. The firmest line is simply not having the production connection string in the Claude Code session's environment at all. Claude Code drafts and reviews; I apply to production by hand. I wrote up why removing a capability beat strengthening an instruction in the morning git log had one more commit than I'd allowed, and how to draw the same line with hooks in the Claude Code hooks field guide.
For your first concrete step tomorrow, take a recent migration from your project and ask Claude Code, "if we rewrote this in Expand-Contract, what would change?" The ten minutes that takes will surface more weaknesses in your usual approach than a week of theoretical reading. That's where the muscle memory starts.
Share
Thank You for Reading
Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.