Zero-Downtime PostgreSQL Schema Migrations: Expanding Columns and Adding Constraints Without Table Locks
Shafikul Islam
Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

How a 50-Millisecond DDL Statement Freezes an Entire Database
In PostgreSQL, most ALTER TABLE operations require an ACCESS EXCLUSIVE lock, which conflicts with every other lock mode (including plain SELECT queries).
Even if the ALTER TABLE itself only takes 20 milliseconds, if a 10-second reporting query is currently reading that table, the ALTER TABLE waits in the lock queue. While it waits, every new SELECT, INSERT, and UPDATE on that table is blocked behind the waiting ALTER TABLE, causing a complete production outage in seconds.
1. Rule 1: Never Run DDL Without a Strict lock_timeout
Every migration script in our pipeline begins with an explicit lock_timeout so that if a lock cannot be acquired within 2 seconds, the migration aborts cleanly and retries instead of blocking live customer traffic:
SET lock_timeout = '2000ms';
SET statement_timeout = '60000ms';
2. Rule 2: Two-Step Foreign Keys and Check Constraints (NOT VALID)
Adding a normal FOREIGN KEY or CHECK constraint scans the entire table while holding an ACCESS EXCLUSIVE / SHARE ROW EXCLUSIVE lock.
Instead, split the migration into two non-blocking steps:
-- Step 1: Metadata-only constraint enforcement for new writes (instant, <5ms)
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id)
NOT VALID;
-- Step 2: Validate existing historical rows using SHARE UPDATE EXCLUSIVE
-- (Does NOT block live SELECT, INSERT, UPDATE, or DELETE queries!)
ALTER TABLE orders
VALIDATE CONSTRAINT fk_orders_customer;
3. Rule 3: Adding NOT NULL Safely in PostgreSQL 12+
Instead of running a blocking full-table scan with ALTER TABLE ... SET NOT NULL on a 100-million-row table, add a CHECK (col IS NOT NULL) NOT VALID constraint first, run VALIDATE CONSTRAINT, and then execute ALTER TABLE ... SET NOT NULL - PostgreSQL recognizes the validated check constraint and completes the SET NOT NULL instantaneously without re-scanning the table.