Sub topic 12
Running Schema Changes Without Blocking Traffic
This chapter assumes basic SQL, transactions, primary keys, foreign keys, and the ability to use two concurrent PostgreSQL sessions. The goal is to change a live schema while keeping lock waits short and predictable.
Why DDL can block traffic
Data definition language (DDL) changes the database structure. Examples include ALTER TABLE, CREATE INDEX, and ADD CONSTRAINT. PostgreSQL protects these operations with table-level locks.
Many ALTER TABLE operations request an ACCESS EXCLUSIVE lock. This is the strongest table lock. It conflicts with every other table lock, including locks used by ordinary SELECT statements. If another transaction keeps the table open, the schema change waits. Once the schema change gets the lock, new queries may wait behind it.
A short metadata change can still cause a long outage if it waits in the queue or holds its lock while doing expensive work.
Use a short lock timeout
Set lock_timeout for the migration session. PostgreSQL cancels a statement if it waits longer than this period to acquire a lock. The timeout does not limit the time spent executing the operation after the lock has been acquired.
Use SET LOCAL inside a transaction when possible. The setting then applies only to that transaction.
BEGIN;
SET LOCAL lock_timeout = '2s';
SET LOCAL statement_timeout = '60s';
ALTER TABLE accounts ADD COLUMN note text;
COMMIT;If a transaction is already open for a long time, the ALTER TABLE statement may fail with a lock timeout instead of blocking application traffic. The migration runner can retry later.
A failed statement usually places the transaction in an aborted state. Roll it back before retrying:
ROLLBACK;Split expensive changes into phases
Prefer changes that separate a quick catalog change from later data work.
For a new column, add it without a table-wide rewrite when possible. Avoid adding a volatile default to older PostgreSQL versions because PostgreSQL may need to rewrite the table. Backfill existing rows in small batches, committing between batches.
For a new validation rule, add the constraint as NOT VALID. PostgreSQL records the rule without immediately scanning every existing row. A later validation checks existing data.
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE orders
ADD CONSTRAINT orders_amount_positive
CHECK (amount > 0) NOT VALID;
COMMIT;
ALTER TABLE orders
VALIDATE CONSTRAINT orders_amount_positive;Before validation, application code should ensure that new rows satisfy the rule. Fix any existing invalid rows before running VALIDATE CONSTRAINT.
For indexes, use CREATE INDEX CONCURRENTLY. It allows normal inserts, updates, and deletes to continue, but it takes longer and performs more work. It cannot run inside a transaction block.
SET lock_timeout = '2s';
CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_created_at_idx
ON orders (created_at);If a concurrent index build fails, PostgreSQL can leave an invalid index behind. Remove it in a separate carefully planned operation, then retry.
Check blockers before and during a migration
Inspect active sessions before starting:
SELECT pid,
state,
wait_event_type,
wait_event,
xact_start,
left(query, 100) AS query
FROM pg_stat_activity
WHERE datname = current_database()
ORDER BY xact_start NULLS LAST;After a migration begins, find sessions waiting for another process:
SELECT a.pid,
pg_blocking_pids(a.pid) AS blocked_by,
a.state,
a.wait_event_type,
a.wait_event,
left(a.query, 100) AS query
FROM pg_stat_activity AS a
WHERE cardinality(pg_blocking_pids(a.pid)) > 0;Long-running transactions and sessions that are idle in a transaction are common blockers. End or fix those sessions according to your operational procedures before retrying the migration.
A practical migration sequence
- Test the change against production-sized data.
- Make the application tolerate both the old and new schema.
- Set a small
lock_timeout. - Acquire the lock and perform only the quick schema step.
- Backfill data separately in small, restartable batches.
- Add or validate constraints after the data is correct.
- Build large indexes concurrently.
- Monitor blocked sessions and database load.
Exercise
Why should a migration set lock_timeout before an ALTER TABLE statement?
Show answer
It prevents the statement from waiting indefinitely for a conflicting lock. The migration fails quickly, allowing the runner to retry without leaving normal traffic queued behind it.