Your staging pipeline executes ALTER TABLE orders ADD COLUMN tax_jurisdiction text; in 4.8 ms, so CI promotes the migration to production during business hours. Four seconds later, PgBouncer's cl_waiting gauge climbs past 400, API pods throw HTTP 503 pool timeouts, and direct psql sessions fail with FATAL: sorry, too many clients already (SQLSTATE 53300). The ALTER TABLE statement touched zero heap blocks and needed only one catalog row in pg_attribute, yet it queued behind a 45-second analytics SELECT and froze every read and write on orders.
Staging databases rarely reproduce lock-queue amplification because they lack long analytical snapshots and high-QPS arrival rates. Shipping DDL safely on PostgreSQL 11 through 17 requires accounting for heavyweight lock wait queues, catalog-only metadata updates versus full heap rewrites, and ORM transaction wrappers.
Inside ProcSleep: Why FIFO Lock Queues Block Reads Behind Fast DDL
PostgreSQL coordinates relation locks in shared-memory LOCK and PROCLOCK hash tables. Routine OLTP queries use compatible lock modes: SELECT acquires ACCESS SHARE, while INSERT, UPDATE, and DELETE acquire ROW EXCLUSIVE. Because those two modes do not conflict, thousands of reads and row writes execute concurrently.
Most ALTER TABLE commands request ACCESS EXCLUSIVE, which conflicts with every lock mode including ACCESS SHARE. When Backend A holds ACCESS SHARE for a 45-second reporting SELECT and Backend B issues ALTER TABLE orders ..., Backend B enters ProcSleep inside the table's FIFO wait queue. To prevent writer starvation, PostgreSQL evaluates new lock requests against waiting backends ahead of them in the queue. When Backend C arrives 1 ms later running a primary-key SELECT (ACCESS SHARE), it conflicts with Backend B's queued ACCESS EXCLUSIVE lock and sleeps behind B. Every incoming SELECT, INSERT, UPDATE, and DELETE piles up behind the stalled DDL until Backend A finishes, lock_timeout aborts Backend B with SQLSTATE 55P03 (lock_not_available), or statement_timeout cancels a query with SQLSTATE 57014 (query_canceled):
SELECT a.pid, a.state, now() - a.query_start AS age,
l.mode, l.granted, pg_blocking_pids(a.pid) AS blockers,
left(a.query, 80) AS sql_text
FROM pg_stat_activity a
JOIN pg_locks l ON l.pid = a.pid AND l.relation = 'orders'::regclass
ORDER BY l.granted DESC, a.query_start ASC;
PostgreSQL 11–17 Catalog Flips vs Full Heap Rewrites
Even when a DDL statement acquires its lock immediately, some subcommands update system catalogs in milliseconds while others invoke ATRewriteTables to rewrite every 8 KB heap block and rebuild all indexes under ACCESS EXCLUSIVE.
- In PostgreSQL 11–17,
ADD COLUMN ... DEFAULTwith a constant or non-volatile expression (IMMUTABLEorSTABLE, such as'pending',0, ornow()) evaluates once at DDL time and stores the binary datum inpg_attribute.attmissingval(atthasmissing = true) with zero heap rewrite. AnyVOLATILEdefault—gen_random_uuid(),random(),clock_timestamp(), ornextval()—forcesATRewriteTablesacross the entire table. - Plain
ALTER COLUMN col SET NOT NULLscans the whole heap underACCESS EXCLUSIVEunless PostgreSQL 12–17 finds an existing validatedCHECK (col IS NOT NULL)constraint (convalidated = true). Because nativeSET NOT NULL NOT VALIDsyntax was reverted prior to PostgreSQL 17 GA, PG 12–17 deployments must addCHECK (col IS NOT NULL) NOT VALID, runVALIDATE CONSTRAINTonline underSHARE UPDATE EXCLUSIVE, flipSET NOT NULLinstantaneously, and drop the temporary check constraint. ALTER COLUMN TYPEskips rewrites for binary-coercible widenings (VARCHAR(64)toTEXT, orNUMERIC(10,2)toNUMERIC(14,2)at identical scale without dependent expression indexes), whereas wideningINT4toBIGINTrewrites every tuple from 4 bytes to 8 bytes.CREATE INDEX CONCURRENTLYandDROP INDEX CONCURRENTLYholdSHARE UPDATE EXCLUSIVEso reads and DML continue, but raiseSQLSTATE 25001(active_sql_transaction) insideBEGIN/COMMITor multi-statement simple-query batches. Aborted concurrent builds leave behind an unqueriedpg_index.indisvalid = falseentry that still taxes writes until dropped concurrently.
PostgreSQL 11–17 DDL Lock, SQLSTATE & Zero-Downtime Matrix
| DDL Operation | Lock Mode | Blocked Queries | Table Rewrite | PG 11–17 Nuance & SQLSTATE Risk | Zero-Downtime SQL Pattern |
|---|---|---|---|---|---|
ADD COLUMN ... DEFAULT <const> |
ACCESS EXCLUSIVE |
SELECT & DML |
No (PG 11+) | Uses attmissingval; queues behind slow SELECT (55P03 on lock timeout) |
SET LOCAL lock_timeout = '2s' + external retry loop |
ADD COLUMN ... DEFAULT <volatile> |
ACCESS EXCLUSIVE |
SELECT & DML |
Yes (ATRewriteTables) |
gen_random_uuid(), clock_timestamp(), nextval() rewrite heap; triggers 57014 / 53300 |
ADD COLUMN nullable, SET DEFAULT, backfill in PK batches |
ALTER COLUMN ... SET NOT NULL |
ACCESS EXCLUSIVE |
SELECT & DML |
No (Full Scan) | PG 12–17 skips scan via validated CHECK; native NOT VALID reverted pre-PG 17 GA |
CHECK (col IS NOT NULL) NOT VALID, VALIDATE, then SET NOT NULL |
ALTER COLUMN TYPE |
ACCESS EXCLUSIVE |
SELECT & DML |
Conditional | VARCHAR to TEXT or same-scale NUMERIC skips rewrite; INT4 -> BIGINT rewrites all blocks |
Expand-Contract: add col_v2, trigger dual-write, batched backfill |
ADD CONSTRAINT ... FOREIGN KEY |
SHARE ROW EXCLUSIVE |
DML (both tables) | No (Full Scan) | Direct FK stalls writes on child and parent; VALIDATE runs under SHARE UPDATE EXCLUSIVE |
ADD FOREIGN KEY ... NOT VALID under lock_timeout, then VALIDATE |
CREATE / DROP INDEX CONCURRENTLY |
SHARE UPDATE EXCLUSIVE |
DDL & VACUUM FULL |
No | Fails inside tx with SQLSTATE 25001; failed build leaves indisvalid = false index |
Autocommit single statement; verify pg_index.indisvalid = true |
Worked Example: 800-QPS Pool Saturation on a 65M-Row Orders Table
Consider a worked example on an orders table holding 65,000,000 rows across an 18.4 GB heap plus 6.2 GB in indexes (24.6 GB total). Primary traffic on orders averages 800 QPS (680 QPS SELECT and 120 QPS INSERT/UPDATE) at 2.5 ms mean latency, occupying 800 × 0.0025 s = 2.0 active backends in steady state. PostgreSQL runs with max_connections = 200, fronted by PgBouncer (default_pool_size = 120, query_wait_timeout = 15s) serving 8 API pods with 50 connections each (400 app client slots).
- At
t = 0.000 s, a reportingSELECTstarts a45.000 sscan onorders. Att = 10.000 s(35.000 sremaining), an unguarded migration submitsALTER TABLE orders ADD COLUMN tax_jurisdiction text;withlock_timeout = 0. Arriving queries queue behindProcSleepat800requests/s (0.8/ms). All120PgBouncer server slots pin in120 / 800 = 0.150 s(150 ms,t = 10.150 s), and the remaining280API pod slots fill PgBouncer's wait queue in280 / 800 = 0.350 s(350 ms), exhausting all400app connections in500 ms(t = 10.500 s). Across the35.0 sstall,35.0 × 800 = 28,000requests block or fail past PgBouncer's15 scutoff att = 25.150 s. - Guarding the DDL with
SET LOCAL lock_timeout = '2s'and external backoff sleeps (1 s, 2 s, 4 s, 8 s, 16 s) aborts Attempt 1 att = 12.0 swithSQLSTATE 55P03so queued queries drain in milliseconds without hitting the15 scutoff. Five aborted2.0 sattempts plus1 + 2 + 4 + 8 + 16 = 31.0 sof external sleeps span5 × 2.0 + 31.0 = 41.0 sfromt = 10.0 s, launching Attempt 6 att = 51.000 s(six seconds after the 45-second report finished) and committing in4.8 msatt = 51.0048 s. Tighteninglock_timeoutto100mscaps per-retry buffering to0.100 × 800 = 80server connections (66.7%of the120-slot pool). - For an incompatible type change like
INT4toBIGINT, rewriting24.6 GBat200 MB/ssustained disk throughput holdsACCESS EXCLUSIVEfor24,600 / 200 = 123.0 s. Two-phase Expand-Contract replaces that outage with a< 5 msADD COLUMN id_v2 bigint+ dual-write trigger, followed by6,500autocommit batches of10,000rows holding only row-levelROW EXCLUSIVElocks.
-- Execute per attempt in runner; ROLLBACK and sleep OUTSIDE tx on SQLSTATE 55P03
BEGIN;
SET LOCAL lock_timeout = '2s';
SET LOCAL statement_timeout = '10s';
ALTER TABLE orders ADD COLUMN tax_jurisdiction text;
COMMIT;
Audit raw SQL files before merge in the browser-local PostgreSQL Migration Lock Checker, browse related workflows in developer guides, and check free tool access details on CodexTheme pricing.
Production Boundaries Requiring Manual Verification
Migration frameworks wrap SQL files in transactions differently: Prisma Migrate dispatches multi-statement SQL files via a single PostgreSQL simple-query call that creates an implicit transaction block (raising SQLSTATE 25001 on CONCURRENTLY), Alembic requires with op.get_context().autocommit_block():, Flyway needs executeInTransaction=false, and Drizzle's session.transaction() adds explicit BEGIN/COMMIT.
Inspect live cluster maintenance before running DDL as well. Anti-wraparound autovacuum holds SHARE UPDATE EXCLUSIVE and resists cancellation, blocking ACCESS EXCLUSIVE acquisition until vacuum finishes. On clusters using logical replication slots, full rewrites and unthrottled backfills generate tens of gigabytes of WAL that lag downstream consumers. Even pg_repack requires a primary key or NOT NULL unique index, 2x free disk space, trigger overhead during copy, and a final brief ACCESS EXCLUSIVE catalog swap.