Why a 5ms ACCESS EXCLUSIVE Lock Causes a 5-Minute Outage
Most PostgreSQL migration outages are triggered not by multi-hour table rewrites, but by metadata-only ALTER TABLE commands that finish in under five milliseconds on an idle staging server. Operations such as ADD COLUMN, DROP COLUMN, RENAME COLUMN, and ADD CONSTRAINT ... CHECK ... NOT VALID acquire ACCESS EXCLUSIVE—PostgreSQL's strictest heavyweight table lock, which conflicts with every lock mode in pg_locks, including the ACCESS SHARE lock acquired by plain SELECT queries, autovacuum workers, and foreign-key lookup checks.
Outages occur through FIFO lock-queue amplification inside ProcSleep. Suppose an analytics query, pg_dump worker, or leaked idle in transaction session holds ACCESS SHARE on orders for 90 seconds. Five seconds in, your runner executes ALTER TABLE orders ADD COLUMN retry_count INT DEFAULT 0 with default lock_timeout = 0. Blocked by ACCESS SHARE, the ALTER TABLE enters the wait queue (granted = false). To prevent writer starvation, PostgreSQL blocks incoming lock requests that conflict with queued waiters, forcing every new SELECT (ACCESS SHARE) and INSERT, UPDATE, or DELETE (ROW EXCLUSIVE) behind the waiting DDL.
At 500 queries per second, a 100-connection PgBouncer or HikariCP pool exhausts in 200 milliseconds. Read-only API endpoints start returning 502 and 504 errors across unrelated application routes that merely join or read from the table, turning a five-millisecond catalog edit into an 85-second outage. Enforcing SET LOCAL lock_timeout = '2s' aborts the DDL attempt with SQLSTATE 55P03 before the queue deepens, immediately releasing queued readers so your migration runner can sleep outside the transaction and retry cleanly.
SELECT blocked.pid, blocked.wait_event,
now() - blocked.query_start AS wait_time,
pg_blocking_pids(blocked.pid) AS blockers,
LEFT(blocked.query, 70) AS query
FROM pg_stat_activity AS blocked
WHERE CARDINALITY(pg_blocking_pids(blocked.pid)) > 0;
Field Note: Never run production DDL with lock_timeout = 0. Combine SET LOCAL lock_timeout = '2s' with idle_in_transaction_session_timeout on app roles.
Fast ADD COLUMN ... DEFAULT in PG 11+ vs Volatile Traps
Before PostgreSQL 11, ALTER TABLE ... ADD COLUMN ... DEFAULT <expr> rewrote every heap page and rebuilt every index on the relation while holding ACCESS EXCLUSIVE. Since PostgreSQL 11, ATExecAddColumn in tablecmds.c inspects the default expression tree using contain_volatile_functions(). When that check returns false—covering literal constants as well as IMMUTABLE and STABLE SQL or C functions—PostgreSQL evaluates the expression once at DDL execution time, stores the serialized binary datum inside pg_attribute.attmissingval, and flips atthasmissing = true. Pre-existing heap tuples remain untouched on disk with their shorter attribute array; sequential and index scans substitute attmissingval in memory during slot tuple deforming, even when NOT NULL is declared alongside DEFAULT.
That optimization vanishes when the default contains any VOLATILE function (provolatile = 'v'), including gen_random_uuid(), uuid_generate_v4(), random(), clock_timestamp(), and nextval() (used by SERIAL, BIGSERIAL, and GENERATED ... AS IDENTITY columns added to populated tables). Because each existing row needs an independently generated datum, PostgreSQL disables attmissingval and invokes ATRewriteTables, holding ACCESS EXCLUSIVE across a full heap and index rebuild on a 200 GB table while doubling peak disk consumption before commit and saturating streaming replication slots with WAL.
Timestamp defaults hide a sharp distinction between now() and clock_timestamp(). In pg_proc, now() and CURRENT_TIMESTAMP alias transaction_timestamp(), marked STABLE (provolatile = 's'). On PG 11–17, ADD COLUMN created_at TIMESTAMPTZ DEFAULT now() avoids a rewrite—but stamps every historical row with the single migration timestamp, skewing historical records, whereas switching to clock_timestamp() (VOLATILE) triggers a full table rewrite. For dynamic defaults, add a nullable column with no default, attach SET DEFAULT for future inserts, and backfill NULLs in batches.
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE invoices ADD COLUMN public_id UUID;
ALTER TABLE invoices ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
COMMIT;
UPDATE invoices SET public_id = gen_random_uuid()
WHERE id >= 1 AND id < 50001 AND public_id IS NULL;
Field Note: pg_proc.provolatile = 'i' or 's' (including now()) uses attmissingval without rewriting; 'v' (gen_random_uuid(), clock_timestamp(), nextval()) rewrites the entire table.
Zero-Downtime SET NOT NULL & FOREIGN KEY via NOT VALID
Adding a constraint combines catalog registration for new writes with a scan verifying historical rows, and lock severity depends on the constraint type. Direct ADD CONSTRAINT ... CHECK and PG 11 SET NOT NULL hold ACCESS EXCLUSIVE across a full sequential scan, blocking reads and writes. Direct ADD CONSTRAINT ... FOREIGN KEY acquires SHARE ROW EXCLUSIVE on both the child table and referenced parent table: SELECTs (ACCESS SHARE) continue, but INSERT, UPDATE, and DELETE (ROW EXCLUSIVE) stall on both tables—so adding a foreign key on audit_logs freezes writes on users.
Appending NOT VALID splits those phases. ALTER TABLE child ADD CONSTRAINT ... FOREIGN KEY ... NOT VALID still takes SHARE ROW EXCLUSIVE on both tables, and CHECK ... NOT VALID takes ACCESS EXCLUSIVE, but PostgreSQL sets pg_constraint.convalidated = false and skips the scan. Once committed in milliseconds, new writes enforce the constraint immediately. Running ALTER TABLE ... VALIDATE CONSTRAINT in a second transaction takes only SHARE UPDATE EXCLUSIVE on the child table (and ROW SHARE on the parent for foreign keys), blocking neither reads nor writes.
PostgreSQL 12–17 applies this exact mechanism to SET NOT NULL. Because native NOT NULL ... NOT VALID catalog syntax was reverted prior to the PostgreSQL 17 GA release, ALTER COLUMN ... SET NOT NULL still acquires ACCESS EXCLUSIVE through PG 17 and offers no inline NOT VALID keyword. However, starting in PostgreSQL 12, SET NOT NULL inspects pg_constraint for an existing convalidated = true CHECK (col IS NOT NULL) clause; finding one, PostgreSQL skips the sequential heap scan entirely, flips pg_attribute.attnotnull = true in milliseconds under SET LOCAL lock_timeout = '2s', and lets you drop the helper CHECK constraint immediately.
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_inv_acct ON invoices (account_id);
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE invoices ADD CONSTRAINT inv_acct_fk
FOREIGN KEY (account_id) REFERENCES accounts (id) NOT VALID;
COMMIT;
ALTER TABLE invoices VALIDATE CONSTRAINT inv_acct_fk;
Field Note: Never run ADD CONSTRAINT ... NOT VALID and VALIDATE CONSTRAINT inside one BEGIN ... COMMIT block, or the initial heavy lock persists through the full scan.
ORM Transaction Wrappers Breaking CONCURRENTLY
CREATE INDEX CONCURRENTLY, DROP INDEX CONCURRENTLY, and REINDEX CONCURRENTLY (PG 12+) fail inside transaction blocks because PostgreSQL commits catalog changes across three internal transactions while waiting on virtual transaction IDs (virtualxid) between two heap scans. Any open BEGIN—or multiple semicolon-separated statements sent in one PostgreSQL simple-query protocol call (PQexec), which creates an implicit transaction block—aborts immediately with SQLSTATE 25001 (cannot run inside a transaction block).
Prisma Migrate and Alembic require explicit isolation. Prisma sends migration.sql over raw simple-query execution and offers no transaction toggle: create the migration with npx prisma migrate dev --create-only and keep strictly one CREATE INDEX CONCURRENTLY statement in the file, as adding a second index or SET command creates an implicit multi-statement transaction. In Alembic, wrap op.create_index(..., postgresql_concurrently=True) inside with op.get_context().autocommit_block():, which commits the active migration transaction before switching the connection to AUTOCOMMIT.
In Flyway, place CONCURRENTLY in a standalone V*__*.sql file containing zero transactional DDL statements, and explicitly set executeInTransaction=false in a companion V4__idx.sql.conf sidecar file (Community/Teams) or a -- flyway:executeInTransaction=false header comment (Teams/Enterprise) so mixed-statement heuristics cannot re-enable BEGIN. Drizzle ORM's drizzle-kit migrate executes migration files inside a single session.transaction() wrapper, and --> statement-breakpoint only splits SQL strings within that same open transaction—so generate a stub with drizzle-kit generate --custom and run CONCURRENTLY from a standalone non-transactional client script. Always precede retries with an autocommit DROP INDEX CONCURRENTLY IF EXISTS step to clear indisvalid = false leftovers that otherwise penalize every write.
# Alembic autocommit_block():
with op.get_context().autocommit_block():
op.create_index("idx_ev_org", "events", ["org_id"], postgresql_concurrently=True)
-- Flyway: V4__idx.sql.conf -> executeInTransaction=false
-- Prisma migration.sql (sole statement in file):
CREATE INDEX CONCURRENTLY "idx_ev_org" ON "events"("org_id");
Field Note: Sending 'SET statement_timeout = 0; CREATE INDEX CONCURRENTLY ...;' in one PQexec string creates an implicit transaction block and fails with SQLSTATE 25001.