The Horror of Table Locks on 500M Row Tables
In high-throughput transactional databases, executing naive database migrations is the single most common cause of catastrophic service outages. In PostgreSQL, seemingly innocuous schema modifications—such as adding a non-null column with a default value, modifying a data type, adding a foreign key constraint, or creating a basic B-tree index—require an ACCESS EXCLUSIVE table lock.
When an ALTER TABLE command requests an ACCESS EXCLUSIVE lock, PostgreSQL queues the request behind any ongoing read or write transactions. Crucially, all subsequent queries hitting that table are queued behind the migration lock. On a busy production table processing 15,000 queries per second with 500 million rows, a migration that pauses for just 10 seconds causes connection pools to saturate, application health checks to fail, and the entire platform to cascade into a total outage. In this engineering guide, we walk through the exact battle-tested Expand-and-Contract Pattern we used to migrate 500 million live transaction records without dropping a single customer request.
The Golden Rules of Zero-Downtime PostgreSQL DDL
Before executing any schema modification on a massive table, your migration runner and database connection must enforce strict defensive lock settings:
-- Rule 1: Set strict lock timeouts to avoid transaction queue backlogs
SET lock_timeout = '2s';
SET statement_timeout = '30s';
-- If a migration cannot acquire the lock within 2 seconds, fail fast
-- and retry later rather than starving incoming customer queries!
Phase 1: Safe Schema Expansion (Additive Changes Only)
Never rename columns, alter existing data types, or drop columns in a single transactional step. Instead, follow the phased lifecycle. Suppose we need to split a legacy full_name column into first_name and last_name across 500M user records:
-- Step 1: Add new columns as NULLABLE without table rewrite
ALTER TABLE users ADD COLUMN first_name VARCHAR(128);
ALTER TABLE users ADD COLUMN last_name VARCHAR(128);
-- Step 2: Create synchronous write triggers or dual-writing in application code
CREATE OR REPLACE FUNCTION sync_user_names()
RETURNS TRIGGER AS $$
BEGIN
NEW.first_name := split_part(NEW.full_name, ' ', 1);
NEW.last_name := substr(NEW.full_name, length(split_part(NEW.full_name, ' ', 1)) + 2);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_sync_names
BEFORE INSERT OR UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION sync_user_names();
Phase 2: Asynchronous Chunked Backfill
Never update millions of rows in a single UPDATE users SET ... statement! A single massive update generates massive transaction log (WAL) volume, locks rows, bloats table storage, and starves replication slots. Instead, backfill data in micro-batches using deterministic primary key ranges with sleep intervals:
-- Chunked batched backfill executed by an automated background worker
DO $$
DECLARE
batch_size INT := 10000;
current_min_id BIGINT := 0;
max_id BIGINT;
BEGIN
SELECT MAX(id) INTO max_id FROM users;
WHILE current_min_id < max_id LOOP
UPDATE users
SET first_name = split_part(full_name, ' ', 1),
last_name = substr(full_name, length(split_part(full_name, ' ', 1)) + 2)
WHERE id >= current_min_id
AND id < (current_min_id + batch_size)
AND first_name IS NULL;
COMMIT; -- Release row locks and allow autovacuum to reclaim dead tuples
current_min_id := current_min_id + batch_size;
PERFORM pg_sleep(0.05); -- Jitter pause to keep DB CPU under 40%
END LOOP;
END $$;
Phase 3: Non-Blocking Index and Constraint Creation
Adding indexes to a 500M row table can take hours. Standard CREATE INDEX takes a SHARE lock that blocks all incoming writes. Always use CONCURRENTLY:
-- Builds index without blocking concurrent INSERT, UPDATE, or DELETE operations
CREATE INDEX CONCURRENTLY idx_users_last_name
ON users (last_name);
-- Adding constraints safely: Validate in two phases
ALTER TABLE users
ADD CONSTRAINT check_last_name_not_empty
CHECK (last_name <> '') NOT VALID;
-- Validate constraint without full table lock (only acquires SHARE UPDATE EXCLUSIVE)
ALTER TABLE users
VALIDATE CONSTRAINT check_last_name_not_empty;
Alternative Tooling: When to Deploy pg_repack vs Shadow Table Backfills
While the expand-and-contract pattern is the gold standard for schema additions and column transformations, table bloat reclamation and primary key conversions require different architectural tools. When a 500M row table suffers from 60% dead tuple bloat following aggressive backfills, running standard VACUUM FULL acquires an exclusive table lock that takes hours to complete.
Instead, use pg_repack or shadow table swaps. pg_repack builds a temporary table containing existing row data, establishes a PostgreSQL log trigger to record concurrent live mutations, builds target indexes concurrently, and then performs a sub-second catalog lock swap before dropping the old bloated relation:
# Running pg_repack on 500M row users table with 4 concurrent index workers
pg_repack --dbname=enterprise_core \
--table=public.users \
--no-order \
--jobs=4 \
--wait-timeout=5
Comparative Analysis: Migration Strategies for Massive Datasets
| Migration Strategy | Lock Level | Write Interruption | Rollback Complexity |
|---|---|---|---|
| Naive DDL (Single Transaction) | ACCESS EXCLUSIVE | Total Outage (Hours) | High / Impossible Live |
| pg_repack / pg_squeeze | ACCESS SHARE | Brief Lock Switch (< 2s) | Moderate |
| Expand-Contract with Batched Backfill | Minimal (Lock Timeout 2s) | Zero Downtime (0 ms) | Trivial (Dual-Read/Write) |
Phase 4: Contract and Clean Up
Once all 500M rows are backfilled and verified with zero discrepancy checksums, update the application to read exclusively from first_name and last_name. Drop the trigger, remove the old full_name column, and run a controlled vacuum to reclaim dead row storage:
-- Step 1: Remove synchronization trigger
DROP TRIGGER IF EXISTS trg_sync_names ON users;
DROP FUNCTION IF EXISTS sync_user_names();
-- Step 2: Drop obsolete column safely
ALTER TABLE users DROP COLUMN full_name;
Frequently Asked Questions (FAQ)
What happens if a CONCURRENT index creation fails midway?
If CREATE INDEX CONCURRENTLY is interrupted (e.g., due to deadlock or server timeout), the index remains in an INVALID state. It consumes disk space and is updated on writes, but is ignored by query planners. Always inspect pg_class and drop invalid indexes with DROP INDEX CONCURRENTLY index_name before re-running.
Why should you avoid foreign keys on ultra-high-volume tables?
Foreign keys acquire row-level shared locks on the referenced table on every insert and update. Under high concurrency with distributed microservices, foreign key verification across 500M row parent-child relationships triggers severe lock serialization and deadlocks. Enforce relational integrity at the application or event stream layer instead.
Technical References & Standards
- • PostgreSQL Official Documentation: Explicit Locking Mechanics and Concurrency Control.
- • Fowler, Martin. "Evolutionary Database Design and the Expand-Contract Pattern."
- • GitHub Engineering: Deploying Schema Changes Without Downtime at Scale.
Peer-Reviewed Engineering Article✓ Fact Checked
Authored by senior engineering practitioners. Verified for production reproducibility and accuracy.
Sarah Chen
VP of Database ReliabilityDatabase infrastructure veteran who has orchestrated zero-downtime migrations for top-tier FinTech and SaaS unicorns.
Deploy Intelligence
Synchronize this report with your network
