Sub topic 12
Running schema changes without blocking traffic
This chapter assumes you know the table-level lock modes and which ones conflict, how the lock queue works, and how lock_timeout behaves. It applies them to one job: changing a live table's structure while the application keeps running.
Why a quick ALTER TABLE can stop an application
Most ALTER TABLE forms need an ACCESS EXCLUSIVE lock. That mode conflicts with every other mode, including the ACCESS SHARE lock that a plain SELECT takes. The change itself may take milliseconds. The danger is the time spent waiting for the lock.
Lock requests are served in queue order. If your ALTER TABLE waits behind one long-running transaction, every query that arrives afterwards queues behind your ALTER TABLE. This happens even when those queries would have been compatible with the transaction you are waiting for. A migration that was only waiting becomes an outage for the whole table.
The transaction you wait behind does not have to be doing real work. A session that ran one SELECT and then sat "idle in transaction" holds its ACCESS SHARE lock until it ends.
Step 1: bound the wait with lock_timeout
Set lock_timeout for the migration so it gives up quickly instead of queueing indefinitely.
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE accounts ADD COLUMN note text;
COMMIT;SET LOCAL lasts until the end of the transaction, so the setting cannot leak into a pooled connection. If the lock is not granted within two seconds, the statement fails with canceling statement due to lock timeout (SQLSTATE 55P03) and the transaction is aborted. Nothing has changed, and you can retry later.
lock_timeout applies to each lock acquisition separately. It is not a limit on the total time of the statement. A migration that takes many locks, or runs for a long time once it has them, needs statement_timeout as well. Set it to a value above the expected run time of the work done under the lock.
Choose a lock timeout below the delay your users would notice. One to five seconds is typical. The cost of a failed attempt is a retry. The cost of an unbounded wait is a queue of blocked requests.
Step 2: retry instead of waiting
A migration that fails on a lock timeout should usually try again after a pause. A short shell loop around psql does this without extra tooling.
#!/usr/bin/env bash
# Retry a lock-sensitive migration until it gets the lock.
set -u
for attempt in 1 2 3 4 5 6 7 8 9 10; do
if psql "$DATABASE_URL" -v ON_ERROR_STOP=1 <<'SQL'
BEGIN;
SET LOCAL lock_timeout = '2s';
SET LOCAL statement_timeout = '30s';
ALTER TABLE accounts ADD COLUMN note text;
COMMIT;
SQL
then
echo "migration applied on attempt $attempt"
exit 0
fi
echo "attempt $attempt failed, retrying in 5 seconds"
sleep 5
done
echo "migration did not get its lock after 10 attempts" >&2
exit 1Between attempts, the queued queries drain and the long transaction has a chance to finish. If every attempt fails, look for the blocker with pg_blocking_pids() as in the previous chapter. Do not raise the timeout.
Step 3: choose operations that hold strong locks briefly
Whether a change is safe depends on how long it holds its lock, not only on which lock it takes. Some changes hold ACCESS EXCLUSIVE only for a catalog update. Others hold it while the server scans or rewrites the whole table. Your goal is to split risky changes into steps that each hold a strong lock only briefly.
| Change | Lock taken | Holds the lock for |
|---|---|---|
| `ADD COLUMN` with no default, or a constant default (PostgreSQL 11 and later) | `ACCESS EXCLUSIVE` | A catalog update only |
| `ADD COLUMN` with a volatile default such as `random()` | `ACCESS EXCLUSIVE` | A full table rewrite |
| `ALTER COLUMN ... TYPE` | `ACCESS EXCLUSIVE` | A rewrite for most type changes |
| `ALTER COLUMN ... SET NOT NULL` | `ACCESS EXCLUSIVE` | A full scan, unless a valid `CHECK` proves it (PostgreSQL 12 and later) |
| `CREATE INDEX` | `SHARE` | The whole build, and writes are blocked |
| `CREATE INDEX CONCURRENTLY` | `SHARE UPDATE EXCLUSIVE` | The whole build, but reads and writes continue |
| `ADD CONSTRAINT ... CHECK ... NOT VALID` | `ACCESS EXCLUSIVE` | A catalog update only |
| `VALIDATE CONSTRAINT` | `SHARE UPDATE EXCLUSIVE` | A full scan, with reads and writes continuing |
Two details in the table matter in practice. A default such as now() is stable, not volatile, so it is evaluated once and does not force a rewrite. Increasing the length limit of a varchar(n) column does not rewrite the table either.
Adding an index without blocking writes
A plain CREATE INDEX takes a SHARE lock. That lock conflicts with INSERT, UPDATE and DELETE, so writes to the table stop for the whole build. Use CONCURRENTLY instead.
SET lock_timeout = '2s';
CREATE INDEX CONCURRENTLY accounts_balance_idx ON accounts (balance);CREATE INDEX CONCURRENTLY has three restrictions:
- It cannot run inside a transaction block, so you cannot use
BEGINandSET LOCALaround it. Use a session-levelSET. - It makes more than one pass over the table and waits for transactions that started before each pass. A long-running transaction elsewhere in the database can stall it.
- If it fails, it leaves an index marked invalid. An invalid index is still maintained on every write but is never used by queries, so it only costs you time.
Look for leftovers after a failed build, then drop them and retry.
SELECT indexrelid::regclass AS index_name
FROM pg_index
WHERE NOT indisvalid;
DROP INDEX CONCURRENTLY accounts_balance_idx;DROP INDEX CONCURRENTLY also cannot run in a transaction block.
Adding constraints in two steps
Adding a CHECK constraint normally scans the table while holding ACCESS EXCLUSIVE. Split it into two statements. The first only records the constraint and applies it to new writes. The second checks the existing rows with a weaker lock.
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE accounts
ADD CONSTRAINT accounts_balance_nonneg CHECK (balance >= 0) NOT VALID;
COMMIT;
-- Separate transaction: scans the table but does not block reads or writes
ALTER TABLE accounts VALIDATE CONSTRAINT accounts_balance_nonneg;Foreign keys work the same way. ADD FOREIGN KEY ... NOT VALID takes a SHARE ROW EXCLUSIVE lock on both tables, briefly. VALIDATE CONSTRAINT then scans without blocking normal traffic.
The same trick makes SET NOT NULL cheap on PostgreSQL 12 and later. If a valid CHECK (note IS NOT NULL) constraint already exists, SET NOT NULL skips its own scan.
ALTER TABLE accounts
ADD CONSTRAINT accounts_note_present CHECK (note IS NOT NULL) NOT VALID;
ALTER TABLE accounts VALIDATE CONSTRAINT accounts_note_present;
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE accounts ALTER COLUMN note SET NOT NULL;
COMMIT;
ALTER TABLE accounts DROP CONSTRAINT accounts_note_present;Run this only after every existing row has a non-null note, or the validation fails.
Backfilling data in batches
Updating every row of a large table in one statement holds row locks on all of them until commit and generates a lot of write-ahead log. Backfill in small batches, each in its own transaction, so locks are short and other sessions rarely collide with them.
UPDATE accounts
SET note = ''
WHERE id IN (
SELECT id
FROM accounts
WHERE note IS NULL
ORDER BY id
LIMIT 1000
FOR UPDATE SKIP LOCKED
);Run this repeatedly from a script until it reports zero rows updated. SKIP LOCKED skips rows that another session is holding, and a later pass picks them up. Sorting by id keeps the lock order consistent between batches, which avoids the deadlocks described earlier in this tutorial.
Common mistakes
- Running DDL inside a long transaction. The
ACCESS EXCLUSIVElock lasts until commit. If the migration tool wraps many statements in one transaction, the strong lock is held while the later statements run. Keep lock-heavy statements in short transactions of their own. - Setting
lock_timeoutin the wrong place. A plainSETin a pooled connection can affect the next client that uses it. PreferSET LOCALin a transaction, or reset the value afterwards. - Starting a migration while a long report is running. Check
pg_stat_activityfor old transactions first, including sessions that are idle in transaction. - Assuming a foreign key is cheap. Adding one without
NOT VALIDscans the referencing table under a lock that blocks writes to both tables. - Forgetting that
CONCURRENTLYcan fail. Always check for invalid indexes afterwards.
A checklist before running a migration
- Look up the lock the statement takes and whether it holds it for a catalog change, a scan or a rewrite.
- Check
pg_stat_activityfor long-running or idle-in-transaction sessions on the table. - Set
lock_timeoutwithSET LOCAL(or a sessionSETforCONCURRENTLYstatements). - Split scans and rewrites into separate steps, using
NOT VALID,CONCURRENTLYor batches. - Run the migration with retries, and watch for blocked sessions while it runs.
Exercise
A migration runs ALTER TABLE orders ADD COLUMN shipped_at timestamptz; with no timeout. A reporting session opened a transaction two hours ago, ran one SELECT on orders, and has been idle since. Describe what happens to other queries on orders, and give two changes that make the migration safe.
Show answer
The reporting session still holds an ACCESS SHARE lock on orders. The ALTER TABLE needs ACCESS EXCLUSIVE, so it waits. Every query that arrives on orders afterwards queues behind the ALTER TABLE, even plain reads, so the table appears frozen until the reporting session ends or the migration is cancelled. Two changes: run the migration in a transaction with SET LOCAL lock_timeout = '2s' and retry on failure, so it never queues for long. Also set idle_in_transaction_session_timeout on application roles, or end the idle session found with pg_stat_activity, so the blocker disappears.
Exercise
You need an index on orders (customer_id) and a CHECK (total >= 0) constraint on a table that takes writes all day. Write the statements, and say why each avoids blocking writes.
Show answer
For the index, run CREATE INDEX CONCURRENTLY orders_customer_idx ON orders (customer_id); outside a transaction block. It takes SHARE UPDATE EXCLUSIVE, which does not conflict with writes. For the constraint, run ALTER TABLE orders ADD CONSTRAINT orders_total_nonneg CHECK (total >= 0) NOT VALID; in a short transaction with SET LOCAL lock_timeout, then run ALTER TABLE orders VALIDATE CONSTRAINT orders_total_nonneg; in a separate transaction. The first step holds ACCESS EXCLUSIVE only for a catalog update. The second scans the table under SHARE UPDATE EXCLUSIVE, so reads and writes continue. Afterwards, check pg_index for invalid indexes.