Shelves / Production Deployment
DP·191
Database Deployment Safety
Changing a live database without downtime, verified on PostgreSQL 16 with a 2-million-row table: why the schema and the code deploy separately, and so must be compatible both ways; PostgreSQL's lock levels and which DDL takes which (measured); the lock-queue trap where a waiting ALTER blocks every reader, reproduced and fixed with lock_timeout and retries; which changes rewrite the table; expand/contract (parallel change) in six steps with a dual-write trigger, verified; safe recipes for columns, NOT NULL, constraints, foreign keys, indexes (CONCURRENTLY and its invalid leftovers), renames and type changes; resumable, throttled backfills; online-migration tools (pgroll, gh-ost, pt-online-schema-change); Flyway, Liquibase, golang-migrate and sqlx; migration linting in CI; rollback strategy; and data validation.
Start here: why changing a database is the risky part of a deploy
Application code is easy to roll back: deploy the previous version. A database change usually isn't: a dropped column is gone, a rewritten table took minutes to rewrite, and while a change runs it may lock the table that every request needs. Most deploy-time outages that "came from nowhere" are database changes.
Locks in one paragraph
To keep data consistent, PostgreSQL makes statements take locks. Ordinary reads and writes take light locks that don't block each other. Many schema changes (ALTER TABLE) need the heaviest lock, which conflicts with everything, including plain reads. And locks queue in order: if an ALTER TABLE is waiting for a lock, every query that arrives after it waits behind it.
The trap, measured
The lab ran a 2-million-row table with steady reads, started a slow report (an open transaction lasting 3 seconds), and then ran an instant change, ALTER TABLE … ADD COLUMN:
| The ALTER | Ordinary reads (normally 0.2 ms) | |
|---|---|---|
| no slow report running | finished instantly | unaffected (max 2 ms) |
| slow report running | waited 3 s for the report | all stalled up to 3 s behind the waiting ALTER |
slow report running, lock_timeout = '200ms' |
gave up after 0.2 s (retry later) | max 201 ms |
A change that takes milliseconds took the site down for 3 seconds, because of what else was running. With a long report or a stuck transaction, that becomes minutes. The fix is one line: set a short lock_timeout for migrations and retry.
The pattern that makes changes safe: expand and contract
Never change a schema in a way the currently running code can't handle. Instead:
- Expand: add the new thing (column, table, index) without removing anything; old code ignores it.
- Migrate: deploy code that writes both old and new; backfill existing rows in small batches.
- Switch: deploy code that reads the new thing.
- Contract: once nothing uses the old thing, remove it in a later release.
Each step can be deployed and rolled back on its own.
How deep to go in database deployment safety
Volume 17 defines six mastery levels; for database deployment safety they look like this:
| Level | You can… |
|---|---|
| L1 | explain why schema changes are risky and what expand/contract means |
| L2 | write migrations with a tool, lock timeouts and concurrent index builds |
| L3 | explain PostgreSQL lock modes, the lock queue, table rewrites and backfill mechanics |
| L4 | diagnose a migration-induced outage from pg_locks and pg_stat_activity |
| L5 | design a migration process: linting, review, staged rollouts, validation and rollback |
| L6 | run schema changes safely at scale across many services and large tables |
Why database changes are the dangerous part
Application deploys are easy to make safe: run new instances beside old ones, shift traffic, roll back by shifting it back (chapter 192). The database is shared state that both old and new versions use at the same time, can't be "rolled back" by switching pointers once data has been written in a new shape, and holds locks that can stall the whole application. Most "deploy caused an outage" stories at mature companies are database stories: a migration that locked a hot table, a column dropped while old code still read it, a backfill that saturated I/O and replication.
Two facts shape every technique in this chapter:
- Schema and code deploy at different moments. During a rolling deploy, version N and N+1 run simultaneously against one schema. After a rollback, version N runs against the schema N+1 migrated. So every schema change must be compatible with both the old and the new code.
- DDL takes locks. Most
ALTER TABLEforms take PostgreSQL's strongest lock,ACCESS EXCLUSIVE, which conflicts with everything including plainSELECT. Holding it for milliseconds is fine; holding it, or waiting for it, for seconds is an outage.
PostgreSQL locks from first principles
PostgreSQL has eight table-level lock modes. Each statement acquires one; two transactions conflict when their modes conflict, and the later one waits (in a FIFO queue) until the earlier commits or rolls back. The ones that matter for migrations:
| Mode | Taken by | Conflicts with (blocks) |
|---|---|---|
| ACCESS SHARE | SELECT |
ACCESS EXCLUSIVE only |
| ROW EXCLUSIVE | INSERT, UPDATE, DELETE |
SHARE and stronger |
| SHARE UPDATE EXCLUSIVE | VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY, VALIDATE CONSTRAINT |
itself and stronger; not reads or writes |
| SHARE | CREATE INDEX (non-concurrent) |
writes (ROW EXCLUSIVE) |
| SHARE ROW EXCLUSIVE | ADD FOREIGN KEY, CREATE TRIGGER |
writes |
| ACCESS EXCLUSIVE | most ALTER TABLE, DROP, TRUNCATE, VACUUM FULL |
everything, including SELECT |
Measured on PostgreSQL 16 against a 2,000,000-row delivery table (158 MB), recording the lock mode each statement held (from pg_locks) and whether the table's file changed (a rewrite, detected via pg_relation_filenode):
operation time rewrite lock
ADD COLUMN channel text 4ms no AccessExclusiveLock
ADD COLUMN source text DEFAULT 'app' 2ms no AccessExclusiveLock
ADD COLUMN seen_at timestamptz DEFAULT clock_timestamp() 5161ms yes AccessExclusiveLock,ShareLock
rider_code varchar(20) -> varchar(40) 2ms no AccessExclusiveLock
subscription_id int -> bigint 4401ms yes AccessExclusiveLock,ShareLock
SET NOT NULL on rider_code (full scan) 206ms no AccessExclusiveLock
ADD CHECK ... NOT VALID 3ms no AccessExclusiveLock
VALIDATE CONSTRAINT 176ms no ShareUpdateExclusiveLock
DROP COLUMN note 2ms no AccessExclusiveLock
CREATE INDEX 1027ms no ShareLock
CREATE INDEX CONCURRENTLY (outside a transaction) 1014ms no ShareUpdateExclusiveLock
Read it as: almost everything takes ACCESS EXCLUSIVE, and what makes a change safe is how long it's held. Metadata-only changes (adding a nullable column, adding a column with a constant default since PostgreSQL 11, widening a varchar, dropping a column, adding a constraint as NOT VALID) hold it for milliseconds. Rewrites (volatile defaults, most type changes) hold it for the time to copy the table: 5 s here, hours on a 500 GB table. Scans (SET NOT NULL, adding a validated constraint) hold it for a full read of the table.
A table-scale note: those timings scale roughly linearly with table size. The 206 ms scan becomes about 2 minutes on a 100× larger table; that's 2 minutes during which no query can touch delivery.
The lock-queue trap
The most surprising outage mode: a fast DDL statement takes the whole table down because it waits. Locks are granted in queue order, so once an ALTER TABLE is waiting for ACCESS EXCLUSIVE (because some long transaction holds even a weak lock), every later query on the table queues behind the ALTER, even plain SELECTs that don't conflict with the long transaction. Reproduced with three sessions:
--- migration with lock_timeout = none (default 0 = wait forever) ---
t= 0.11s report holds AccessShareLock in an open transaction
t= 0.11s migration ALTER TABLE delivery ADD COLUMN eta time … (needs AccessExclusiveLock)
t= 1.44s observer migration waiting on Lock; blocked by pids {report}
t= 1.44s observer app waiting on Lock; blocked by pids {migration}
t= 5.44s report commits
t= 5.45s migration done
t= 5.45s app simple SELECT by id returned after 4.82s
--- migration with lock_timeout = 1s ---
t= 0.09s report holds AccessShareLock in an open transaction
t= 0.10s migration ALTER TABLE delivery ADD COLUMN eta time … (needs AccessExclusiveLock)
t= 1.10s migration gave up: canceling statement due to lock timeout → retry later
t= 1.10s app simple SELECT by id returned after 0.50s
t= 1.90s report commits
In the first run, a primary-key lookup that normally takes under a millisecond took 4.8 s, blocked not by the report but by the migration waiting behind the report. In production that's every request to the table piling up, connection pools exhausting, and health checks failing for as long as the longest open transaction lasts (an analytics query, a stuck idle-in-transaction session: potentially hours).
The fix, applied to every migration:
-- Every migration session: bound the wait for locks and the total runtime of each statement
SET lock_timeout = '2s'; -- give up quickly if a lock isn't available (then retry)
SET statement_timeout = '15s'; -- no single DDL statement may run long (use batched work instead)
-- Optional: refuse to run while long transactions exist
SELECT pid, now() - xact_start AS age, state, left(query, 60)
FROM pg_stat_activity
WHERE datname = current_database() AND xact_start < now() - interval '1 minute'
ORDER BY age DESC;
Run the migration in a loop that retries a few times with backoff on lock_not_available (SQLSTATE 55P03). Also set idle_in_transaction_session_timeout on application roles, so forgotten transactions can't hold locks indefinitely, and keep analytics on replicas.
Expand and contract
Expand/contract (also called parallel change) turns one breaking change into a sequence of compatible ones. Renaming rider_code to rider_ref, which in one step would break every running instance:
- Expand (migration): add
rider_ref(metadata-only); install a trigger (or application dual-write) keeping both columns in sync for writes from either code version. - Backfill: copy existing rows in batches (next section).
- Deploy code v2: reads and writes
rider_ref(the trigger still updatesrider_codefor v1 instances during the rollout and for a rollback). - Verify: no reads of the old column (query stats, logs), data matches.
- Deploy code v3 (optional): stops referencing the old column entirely, in code and ORM mappings.
- Contract (migration, a release or more later): drop trigger and old column.
Verified on PostgreSQL 16, with old-version and new-version writes interleaved:
-- EXPAND (migration V7): new column + trigger keeping both in sync for old and new app versions
SET lock_timeout = '2s';
ALTER TABLE delivery ADD COLUMN rider_ref text;
CREATE OR REPLACE FUNCTION delivery_sync_rider() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
NEW.rider_ref := coalesce(NEW.rider_ref, NEW.rider_code);
NEW.rider_code := coalesce(NEW.rider_code, NEW.rider_ref);
ELSIF NEW.rider_ref IS DISTINCT FROM OLD.rider_ref THEN
NEW.rider_code := NEW.rider_ref; -- new app wrote the new column
ELSIF NEW.rider_code IS DISTINCT FROM OLD.rider_code THEN
NEW.rider_ref := NEW.rider_code; -- old app wrote the old column
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER delivery_sync_rider BEFORE INSERT OR UPDATE ON delivery
FOR EACH ROW EXECUTE FUNCTION delivery_sync_rider();
-- old app (v1) writes rider_code; new app (v2) writes rider_ref; both read consistent values
INSERT INTO delivery(subscription_id, delivery_date, kitchen_id, rider_code) VALUES (7, '2027-02-01', 1, 'R-OLD') RETURNING id, rider_code, rider_ref;
-- id | rider_code | rider_ref
-- 2000203 | R-OLD | R-OLD
INSERT INTO delivery(subscription_id, delivery_date, kitchen_id, rider_ref) VALUES (7, '2027-02-02', 1, 'R-NEW') RETURNING id, rider_code, rider_ref;
-- 2000204 | R-NEW | R-NEW
UPDATE delivery SET rider_code = 'R-77' WHERE id = 1 RETURNING id, rider_code, rider_ref;
-- 1 | R-77 | R-77
UPDATE delivery SET rider_ref = 'R-88' WHERE id = 2 RETURNING id, rider_code, rider_ref;
-- 2 | R-88 | R-88
-- CONTRACT (migration V9, only after no running version reads/writes rider_code)
DROP TRIGGER delivery_sync_rider ON delivery;
DROP FUNCTION delivery_sync_rider();
ALTER TABLE delivery DROP COLUMN rider_code;
Expand/contract costs more steps and calendar time, and that is the point: every intermediate state is safe to stop at, and rollback of code is always possible.
Backfills
Updating millions of rows in one statement holds row locks on all of them for the duration, generates a burst of WAL (replication lag on replicas and standbys), bloats the table with dead tuples, and can run for a long time under the migration tool's transaction. Backfill instead in small batches, keyset-paginated by primary key, each its own transaction, with a pause between, resumable from where it stopped, and separate from schema migrations (run as a job, not inside Flyway):
# Batched, resumable, throttled backfill: rider_ref := upper(rider_code), keyset-paginated by primary key
import psycopg, time
DSN = "host=/tmp port=5433 user=app dbname=mig"
BATCH, PAUSE_S = 10_000, 0.02
with psycopg.connect(DSN, autocommit=True) as c:
c.execute("ALTER TABLE delivery ADD COLUMN IF NOT EXISTS rider_ref text") # expand (metadata only)
c.execute("SET lock_timeout = '2s'; SET statement_timeout = '30s'")
last_id = c.execute("SELECT coalesce(max(id), 0) FROM delivery WHERE rider_ref IS NOT NULL").fetchone()[0] # resume point
hi = c.execute("SELECT max(id) FROM delivery").fetchone()[0]
t0, batches, rows, worst = time.time(), 0, 0, 0.0
while last_id < hi:
t = time.time()
cur = c.execute("""UPDATE delivery SET rider_ref = upper(rider_code)
WHERE id > %s AND id <= %s AND rider_ref IS NULL""", (last_id, last_id + BATCH))
worst = max(worst, time.time() - t)
rows += cur.rowcount; batches += 1; last_id += BATCH
time.sleep(PAUSE_S) # leave room for production traffic, replication, vacuum
print(f"backfilled {rows:,} rows in {batches} batches, {time.time()-t0:.1f}s total, slowest batch {worst*1000:.0f} ms")
left = c.execute("SELECT count(*) FROM delivery WHERE rider_ref IS NULL AND rider_code IS NOT NULL").fetchone()[0]
print("rows still missing rider_ref:", left)
first run: backfilled 2,000,202 rows in 201 batches, 28.2s total, slowest batch 421 ms
rows still missing rider_ref: 0
second run: backfilled 0 rows in 0 batches, 0.0s total, slowest batch 0 ms ← resumable and idempotent
Refinements for production: size batches so each takes well under 100–200 ms on the real hardware (the 421 ms worst batch above suggests 5,000 rows would be gentler); watch replication lag (pg_stat_replication.replay_lag) and pause when it exceeds a threshold; run in quiet hours (not 06:30–07:00 for TiffinBox); log progress; let the job be paused and resumed; VACUUM (or let autovacuum) after large backfills. Keyset ranges over id work even with gaps; OFFSET pagination gets slower each batch and should be avoided.
Recipes for common changes
Each verified on PostgreSQL 16 unless noted.
Add a column
Nullable or with a constant default: metadata only, safe (milliseconds of ACCESS EXCLUSIVE; still set lock_timeout). With a volatile default (clock_timestamp(), gen_random_uuid()): rewrites the table (5.2 s above). Instead add it without a default, set the default for new rows separately (ALTER COLUMN … SET DEFAULT, metadata only), and backfill existing rows.
Make a column NOT NULL
SET NOT NULL scans the whole table under ACCESS EXCLUSIVE. The safe route: add a CHECK (col IS NOT NULL) NOT VALID (instant), VALIDATE it (scan, but under SHARE UPDATE EXCLUSIVE, which doesn't block reads or writes), then SET NOT NULL, which PostgreSQL 12+ skips scanning because the valid check already proves it, then drop the check:
a) SET NOT NULL directly (scans 2M rows under AccessExclusiveLock): 234 ms
ADD CONSTRAINT kitchen_nn CHECK (kitchen_id IS NOT NULL) NOT VALID: 3 ms
VALIDATE CONSTRAINT (scan, but only ShareUpdateExclusiveLock): 173 ms
SET NOT NULL now skips the scan (proved by the valid CHECK): 2 ms
PostgreSQL 18 adds ALTER TABLE … ADD CONSTRAINT … NOT NULL … NOT VALID directly, making the dance shorter on 18+.
Add CHECK and FOREIGN KEY constraints
Add as NOT VALID (new rows are checked immediately; existing rows aren't), then VALIDATE CONSTRAINT in a separate transaction. For a foreign key, measured: ADD … NOT VALID takes SHARE ROW EXCLUSIVE on both tables briefly (blocks writes for milliseconds); VALIDATE takes SHARE UPDATE EXCLUSIVE on the referencing table and only ROW SHARE on the referenced one, so writes continue during the 3-second scan.
ALTER TABLE delivery ADD CONSTRAINT delivery_sub_fk
FOREIGN KEY (subscription_id) REFERENCES subscription(id) NOT VALID; -- instant
ALTER TABLE delivery VALIDATE CONSTRAINT delivery_sub_fk; -- scans; reads and writes continue
Indexes
Plain CREATE INDEX takes SHARE, which blocks writes for the whole build. CREATE INDEX CONCURRENTLY doesn't, at the cost of being slower (two table scans) and not runnable inside a transaction block. Measured with a writer inserting every 10 ms during each build:
b) CREATE INDEX d_kitchen took 1222 ms; concurrent INSERTs: 41, worst insert latency 1219 ms
b) CREATE INDEX CONCURRENTLY d_kitchen took 1564 ms; concurrent INSERTs: 161, worst insert latency 12 ms
If a concurrent build fails or is cancelled, it leaves an INVALID index, which isn't used by queries but is still maintained on every write:
c) build cancelled: QueryCanceled
leftover: ('d_kitchen', False) → DROP INDEX CONCURRENTLY d_kitchen; then rebuild
Check for leftovers with SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid. Drop indexes with DROP INDEX CONCURRENTLY. A unique constraint is added online by building a unique index concurrently, then ALTER TABLE … ADD CONSTRAINT … UNIQUE USING INDEX … (instant). Migration tools need to be told not to wrap these in a transaction (Flyway: separate migration with executeInTransaction=false via a script config file; Liquibase: runInTransaction="false"; golang-migrate: one statement per file; Rails: disable_ddl_transaction!).
Change a column's type
Widening varchar(n) or converting varchar to text is metadata-only. Most other changes (int → bigint, text → jsonb, changing timestamp to timestamptz (only free when the session time zone is UTC)) rewrite the table under ACCESS EXCLUSIVE (4.4 s for 2 M rows above). Do it with expand/contract: add a new column of the new type, sync with a trigger, backfill, switch reads, swap (rename in a single fast transaction or switch code to the new name), drop the old. The classic case is a primary key running out of int range (2,147,483,647): monitor sequences approaching the limit long before.
Rename a column or table
A rename is instant, but it breaks every running instance that uses the old name. Use expand/contract (above). For tables, an updatable view with the old name pointing at the renamed table can bridge versions.
Drop a column or table
Make the code stop using it first (deploy), then drop it in a later release. Dropping is instant, but irreversible: take a backup or keep the data (rename the table to _deprecated_… for a cooling-off period) before dropping things that might be needed.
Summary
| Change | Unsafe form | Safe form |
|---|---|---|
| Add column with volatile default | ADD COLUMN x DEFAULT now_fn() |
add nullable → set default → backfill |
| NOT NULL | SET NOT NULL on a big table |
CHECK NOT VALID → VALIDATE → SET NOT NULL (or 18+: NOT NULL NOT VALID) |
| CHECK / FK | add validated | add NOT VALID → VALIDATE separately |
| Index | CREATE INDEX |
CREATE INDEX CONCURRENTLY, check for invalid leftovers |
| Unique | ADD UNIQUE (cols) |
unique index CONCURRENTLY → ADD CONSTRAINT … USING INDEX |
| Type change | ALTER COLUMN TYPE (rewrite) |
new column + sync + backfill + switch + drop |
| Rename | RENAME COLUMN with code still using old name |
expand/contract |
| Drop | drop while code reads it | stop using → later release drops |
| Big UPDATE/DELETE | one statement | batched, throttled job |
| Any DDL | no timeouts | lock_timeout + retries + statement_timeout |
Migration tooling
Migrations are versioned scripts applied in order, recorded in a history table so each runs once per database. They live with the code, are reviewed in pull requests, and run as a deploy step.
-- Flyway (Java ecosystem; used by Spring Boot automatically when on the classpath)
-- src/main/resources/db/migration/V7__add_rider_ref.sql (versioned; runs once)
-- src/main/resources/db/migration/R__delivery_views.sql (repeatable; reruns when checksum changes)
SET lock_timeout = '2s';
ALTER TABLE delivery ADD COLUMN rider_ref text;
-- V8__index_rider_ref.sql must run outside a transaction; add V8__index_rider_ref.sql.conf with:
-- executeInTransaction=false
CREATE INDEX CONCURRENTLY IF NOT EXISTS delivery_rider_ref ON delivery (rider_ref);
# Liquibase changelog (Java; also CLI) — changesets with ids, authors, preconditions, rollbacks
databaseChangeLog:
- changeSet:
id: 7-add-rider-ref
author: kitchen-team
changes:
- sql: { sql: "SET lock_timeout = '2s'" }
- addColumn:
tableName: delivery
columns: [{ column: { name: rider_ref, type: text } }]
rollback:
- dropColumn: { tableName: delivery, columnName: rider_ref }
- changeSet:
id: 8-index-rider-ref
author: kitchen-team
runInTransaction: false
changes:
- sql: { sql: "CREATE INDEX CONCURRENTLY IF NOT EXISTS delivery_rider_ref ON delivery (rider_ref)" }
// golang-migrate: paired up/down files; run from CI/CD or a Kubernetes Job before the rollout
// migrations/000007_add_rider_ref.up.sql ALTER TABLE delivery ADD COLUMN rider_ref text;
// migrations/000007_add_rider_ref.down.sql ALTER TABLE delivery DROP COLUMN rider_ref;
package main
import (
"log"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/pgx/v5"
_ "github.com/golang-migrate/migrate/v4/source/file"
)
func main() {
m, err := migrate.New("file://migrations", "pgx5://app@db:5432/tiffinbox?x-lock-timeout=2000")
if err != nil {
log.Fatal(err)
}
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
log.Fatal(err) // a failed migration leaves the version "dirty": fix forward, then `force`
}
}
// sqlx (Rust): migrations/20261101090000_add_rider_ref.sql, embedded at compile time
// A file whose first line is `-- no-transaction` runs outside a transaction (for CONCURRENTLY).
#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(2)
.connect(&std::env::var("DATABASE_URL").expect("DATABASE_URL"))
.await?;
sqlx::migrate!("./migrations").run(&pool).await?; // records applied versions in _sqlx_migrations
Ok(())
}
Where migrations run. Options: at application startup (Spring Boot's default with Flyway; simple, but every replica races to migrate, startup gets slow, and the app role needs DDL rights), as a separate step before the rollout (a Kubernetes Job, an Argo CD PreSync hook, or a pipeline step; preferred), or by a dedicated tool/operator. Migrations run with a migration role that has DDL privileges; the application role doesn't (least privilege: a SQL injection in the app can't DROP TABLE).
Online schema-change tools handle the expand/contract mechanics for you:
- pgroll (Xata, PostgreSQL): you describe a change (rename, type change, add NOT NULL) and it creates the new column, triggers and backfill, and exposes both schema versions at once through versioned schemas of views, so old and new app versions each see their shape;
completecontracts,rollbackundoes. - Reshape (PostgreSQL): similar idea.
- gh-ost (GitHub) and pt-online-schema-change (Percona) for MySQL: build a shadow copy of the table with the new schema, copy rows in chunks while capturing changes (gh-ost from the binlog, pt-osc via triggers), then atomically swap tables. MySQL's own
ALGORITHM=INSTANT/INPLACEcovers some changes natively. - Managed: PlanetScale (Vitess) deploy requests with schema reverts; some Postgres platforms offer branching for testing migrations against copies.
Linting migrations in CI
Encode the recipes as rules so reviewers aren't the only line of defence. Squawk is a PostgreSQL migration linter (rules like require-concurrent-index-creation, adding-not-nullable-field, changing-column-type, require-timeout-settings); strong_migrations (Rails) and Atlas lint do similar. A minimal version of the idea:
# migration_lint.py — flag unsafe PostgreSQL migration patterns (a toy version of Squawk)
import re
RULES = [
(r"create\s+(unique\s+)?index\s+(?!concurrently)", "CREATE INDEX without CONCURRENTLY blocks writes"),
(r"alter\s+column\s+\w+\s+(set\s+data\s+)?type", "type change usually rewrites the table under ACCESS EXCLUSIVE"),
(r"set\s+not\s+null", "SET NOT NULL scans under ACCESS EXCLUSIVE; validate a CHECK NOT VALID first"),
(r"add\s+column\s+\w+\s+[\w\s()]*default\s+(now|clock_timestamp|random|gen_random_uuid)\(", "volatile default rewrites the table"),
(r"add\s+constraint\s+\w+\s+(foreign\s+key|check)(?![^;]*not\s+valid)", "add constraints NOT VALID, then VALIDATE separately"),
(r"rename\s+(column|to)\b", "rename breaks running code; use expand/contract"),
(r"drop\s+column", "drop only after no deployed version uses the column"),
]
def lint(name, sql):
s = re.sub(r"--[^\n]*", "", sql.lower())
out = [f"{name}: {msg}" for pat, msg in RULES if re.search(pat, s)]
if re.search(r"\balter\s+table\b", s) and "lock_timeout" not in s:
out.append(f"{name}: ALTER TABLE without SET lock_timeout (lock-queue risk)")
return out
migrations = {
"V10__kitchen.sql": "ALTER TABLE delivery ADD COLUMN kitchen_id int; CREATE INDEX d_k ON delivery(kitchen_id);",
"V11__ids.sql": "SET lock_timeout='2s'; ALTER TABLE delivery ALTER COLUMN subscription_id TYPE bigint;",
"V12__fk.sql": "SET lock_timeout='2s'; ALTER TABLE delivery ADD CONSTRAINT fk FOREIGN KEY (subscription_id) REFERENCES subscription(id) NOT VALID;",
"V13__seen.sql": "SET lock_timeout='2s'; ALTER TABLE delivery ADD COLUMN seen_at timestamptz DEFAULT clock_timestamp();",
}
for name, sql in migrations.items():
print("\n".join(lint(name, sql)) or f"{name}: ok")
V10__kitchen.sql: CREATE INDEX without CONCURRENTLY blocks writes
V10__kitchen.sql: ALTER TABLE without SET lock_timeout (lock-queue risk)
V11__ids.sql: type change usually rewrites the table under ACCESS EXCLUSIVE
V12__fk.sql: ok
V13__seen.sql: volatile default rewrites the table
Pair linting with a CI job that applies all migrations to a database restored from a production-sized (masked or synthetic, chapter 190) snapshot and records duration and locks, so "fast on my laptop's 1,000 rows" can't reach production.
Rollback strategy
"Rolling back a migration" usually means one of three different things:
- Roll back the code, keep the schema. The most common and the reason for expand/contract: if every schema state is compatible with the previous code version, app rollback (seconds) never needs a database change.
- Roll forward. Write a new migration that fixes the problem. For anything that touched data, this is usually safer than running a "down" script.
- Down migrations. Reverse scripts (Liquibase
rollback, golang-migrate.down.sql). Useful in development and for pure-structure changes; dangerous for destructive ones (a down migration forDROP COLUMNcan recreate the column but not the data). Many teams don't write down migrations for production at all and rely on 1 and 2.
And for data disasters (a bad backfill overwrote values): point-in-time recovery to a separate instance and copy the affected rows back (chapter 193), or keep an audit/history table for critical columns. Before any destructive data change, snapshot the affected rows (CREATE TABLE _backup_2026_11_01_delivery AS SELECT … WHERE …).
Data validation
After a backfill, a type change, or a migration between systems, prove the data is right rather than assuming it:
-- 1. Completeness: nothing left behind
SELECT count(*) AS missing FROM delivery WHERE rider_code IS NOT NULL AND rider_ref IS NULL;
-- 2. Equivalence: old and new columns agree (on every row, or a large random sample)
SELECT count(*) AS mismatches FROM delivery WHERE rider_ref IS DISTINCT FROM upper(rider_code);
-- 3. Aggregate checksums by partition: cheap to compare across two databases (old system vs new)
SELECT date_trunc('month', delivery_date) AS month, count(*) AS n,
sum(hashtext(id::text || ':' || coalesce(rider_ref, ''))::bigint) AS checksum
FROM delivery GROUP BY 1 ORDER BY 1;
-- 4. Invariants from the domain: credits never negative (chapter 185)
SELECT subscription_id, sum(delta) AS balance
FROM credit_entry GROUP BY 1 HAVING sum(delta) < 0;
Run validation queries as part of the migration job, emit results as metrics, and gate the contract step on them. For migrations between databases or services, run shadow reads (read from both, compare, serve the old, log differences) until mismatches reach zero.
Lab: locks, rewrites and backfills on PostgreSQL
Setup. PostgreSQL 16 on the lab machine; a subs table with 2,000,000 rows (158 MB); Python with psycopg 3 driving background traffic from 4 connections (one query every ~10 ms each) while each change runs. All measurements are real; the "slow report" is an open transaction held for exactly 3 seconds.
Experiment 1: the lock-queue trap
ALTER TABLE subs ADD COLUMN note text (a metadata-only change) with reads running:
| Situation | DDL outcome | Read p50 | Read max | Reads > 500 ms |
|---|---|---|---|---|
| a 3 s transaction is open on the table | completed after 3.01 s | 0.20 ms | 3,003 ms | all 4 readers stalled |
same, migration session has lock_timeout = '200ms' |
cancelled after 0.20 s (lock timeout) | 0.24 ms | 201 ms | 0 |
| no long transaction | completed in 0.00 s | 0.19 ms | 2 ms | 0 |
While the ALTER waited for its ACCESS EXCLUSIVE lock, every new SELECT queued behind it. The report wasn't blocking the reads; the waiting migration was. In production the long transaction is often a forgotten BEGIN in a console, a slow analytics query, or a stuck job, and the stall lasts until it ends. Every migration should run with a short lock_timeout (and a statement_timeout), with retries.
Experiment 2: building an index under write traffic
| Statement | Duration | Insert latency max (normally ~0.6 ms) |
|---|---|---|
CREATE INDEX |
0.48 s | 477 ms: inserts waited for the whole build |
CREATE INDEX CONCURRENTLY |
0.60 s | 121 ms |
At 2 M rows the build is short; at 200 M rows the plain version blocks writes for minutes. CONCURRENTLY is slower, can't run inside a transaction block, and can leave an INVALID index if it fails (check and drop it), which is why migration tools need explicit support for it.
Experiment 3: when "add a column" rewrites the table
| Statement | Time |
|---|---|
ADD COLUMN region text DEFAULT 'south' |
0.01 s (default stored as metadata) |
ADD COLUMN token uuid DEFAULT gen_random_uuid() |
4.51 s (volatile default: every row rewritten under an exclusive lock) |
Same syntax, 450× the time, all of it under the strongest lock. Linters (squawk, strong_migrations-style rules) flag volatile defaults, type changes that rewrite, NOT NULL without a prior CHECK … NOT VALID, and non-concurrent indexes.
Experiment 4: backfilling 2 million rows
Setting a new column on every row while 4 connections update random rows:
| Backfill | Duration | App updates completed | App update p99 | App update max |
|---|---|---|---|---|
one UPDATE of all rows |
9.0 s | 442 | 5.1 ms | 8,659 ms |
| batches of 20,000 rows by id range, each committed | 8.4 s | 2,633 | 44.7 ms | 300 ms |
The single statement held a row lock on every row until it committed, so any request touching a row it had already updated waited up to 8.7 s, and the application completed one-sixth as many updates in the same time. Batches finished as fast, kept every wait under a third of a second, and in production also limit WAL bursts and replica lag, and let you pause or throttle. (A first attempt batched with WHERE skips IS NULL LIMIT 20000 without an index got slower with every batch: the "find next batch" query rescanned the table. Batch by key range.)
Try it yourself
- While Experiment 1's ALTER waits, query
pg_locksjoined topg_stat_activityand identify the blocker withpg_blocking_pids(). - Make a column
NOT NULLsafely: addCHECK (col IS NOT NULL) NOT VALID,VALIDATE CONSTRAINT, thenSET NOT NULL, and time each step under writes. - Run squawk (or write a regex linter) over a folder of migrations and fail CI on the unsafe patterns from Experiments 2 and 3.
- Rename a column with expand/contract across three deploys of a small app, keeping it serving throughout.
Revision sheet: database deployment safety
Key ideas
- Schema changes are the least reversible and most locking part of a deploy.
- Lock modes: reads take ACCESS SHARE; many
ALTER TABLEforms take ACCESS EXCLUSIVE; locks queue FIFO, so a waiting DDL blocks everyone behind it. - Always set
lock_timeout(andstatement_timeout) for migrations; retry with back-off. - Expand → migrate (dual-write, backfill) → switch → contract, each step a separate deploy compatible with the previous code.
- Backfills in key-range batches, committed, throttled, resumable; watch replica lag and WAL volume.
- Safe recipes:
CREATE INDEX CONCURRENTLY; constant defaults;NOT VALIDconstraints thenVALIDATE; new tables instead of risky type changes. - Migration tools (Flyway, Liquibase, Alembic, Atlas, sqitch) plus linters in CI.
- Rollback: forward fixes usually; backups and PITR for data loss; validate data after migrations (counts, checksums, invariants).
Numbers to remember
- Lab: a 3 s open transaction turned an instant ALTER into a 3 s stall for all reads;
lock_timeout=200mscapped it at 0.2 s. - Lab:
CREATE INDEXblocked inserts for 477 ms on 2 M rows;CONCURRENTLYdidn't. - Lab: volatile default rewrote 2 M rows in 4.5 s vs 0.01 s for a constant default.
- Lab: single-statement backfill stalled updates up to 8.7 s; batches capped stalls at 0.3 s.
Pitfalls
- Migrations without lock timeouts.
- Renames and drops in the same release as the code change.
- Volatile defaults or type changes that rewrite large tables.
- One-shot backfills.
- Leaving
INVALIDindexes after a failed concurrent build.
Glossary
- ACCESS EXCLUSIVE: the lock mode that conflicts with every other mode.
- Expand/contract (parallel change): staged, backward-compatible schema evolution.
- Backfill: populating new columns or tables for existing rows.
- NOT VALID constraint: added without checking existing rows; validated later with a weaker lock.
- Lock queue: the FIFO line of sessions waiting for conflicting locks.