Zero Downtime Migrations

Topics Covered

DDL and the Lock Queue

DDL takes table locks

Instant changes still need the lock

The lock queue trap

lock_timeout defuses the trap

Retry with backoff

statement_timeout for the work itself

Long transactions and idle sessions

Transactional DDL

Foreign keys lock two tables

Watching a migration live

Where the danger comes from

Lock levels of common statements

Catalog locks on related objects

Migrations on replicas

Advisory locks around migrations

Cancelling a stuck migration

Schema changes in Postgres take locks, and some take the strongest lock there is. A migration that looks instant in development can freeze a production table for minutes, not because the change itself is slow but because of how locks queue behind each other. Understanding which statements take which locks, and how a single waiting DDL statement blocks every query behind it, is the foundation for changing a live schema safely. This section covers DDL locking, the lock queue trap and the timeouts that defuse it.

DDL takes table locks

Most ALTER TABLE forms take an ACCESS EXCLUSIVE lock, which conflicts with every other lock mode, including the ACCESS SHARE lock that a plain SELECT takes. While it is held, nothing else can read or write the table. Some forms take weaker locks: ADD FOREIGN KEY takes SHARE ROW EXCLUSIVE on both tables, VALIDATE CONSTRAINT takes SHARE UPDATE EXCLUSIVE, and CREATE INDEX takes SHARE, which blocks writes but not reads. Knowing the lock each statement needs is the first step in planning a migration.

Instant changes still need the lock

Many schema changes are metadata only and finish in milliseconds once they hold the lock: adding a nullable column, adding a column with a constant default since version 11, dropping a column, renaming a column or changing a default. The danger is not the work but acquiring the lock. ACCESS EXCLUSIVE must wait for every transaction that currently holds any lock on the table, including a long running SELECT or an idle in transaction session that touched the table an hour ago.

The lock queue trap

Postgres grants locks in queue order. When an ALTER TABLE waits for ACCESS EXCLUSIVE behind a long query, every new query on that table, even a simple SELECT, queues behind the ALTER, because its lock conflicts with the waiting request. So a migration that waits for one slow report blocks all traffic on the table for as long as the report runs. Connection pools fill with blocked queries, and the application appears to be down although the database is idle.

The ALTER only needs a moment, but while it waits for the report, every new query queues behind it.

lock_timeout defuses the trap

Setting lock_timeout before DDL, such as SET lock_timeout to 2 seconds, makes the statement give up if it cannot acquire its lock in time, releasing its place in the queue so blocked queries proceed. The migration fails cleanly instead of causing an outage, and it can be retried a moment later when the long query has finished. Every migration that takes a strong lock on a busy table should run with a short lock_timeout, ideally applied automatically by the migration tool.

Retry with backoff

Because lock_timeout makes migrations fail when they cannot get the lock quickly, migrations need a retry loop: try with a timeout of a second or two, sleep briefly with jitter, and try again, up to a limit. On a busy table with frequent short transactions, the DDL usually succeeds within a few attempts. If it keeps failing, something is holding a lock for a long time, and the right response is to find that session rather than to raise the timeout.

statement_timeout for the work itself

lock_timeout limits waiting for the lock; statement_timeout limits the whole statement, including the work done after acquiring it. A migration that unexpectedly rewrites a large table, for example because a type change is not binary compatible, can hold ACCESS EXCLUSIVE for minutes. A statement_timeout on migrations that are supposed to be instant protects against such surprises by cancelling them before they cause a long outage.

Long transactions and idle sessions

The most common blocker of DDL is a session that is idle in transaction after touching the table, because its locks persist until it commits. Others are long reports, open cursors, analytics queries and stuck background jobs. Before running a migration, checking pg_stat_activity for long running transactions on the target table and setting idle_in_transaction_session_timeout on the server removes most blockers. pg_blocking_pids shows which session blocks a waiting migration.

Transactional DDL

Postgres DDL is transactional: a migration can run several statements in one transaction and roll them all back on error, which is a major advantage over databases that commit DDL implicitly. But every lock taken in the transaction is held until commit, so a migration that alters three tables in one transaction holds ACCESS EXCLUSIVE on all three until the last statement finishes. Grouping only statements that must be atomic, and keeping each transaction short, limits lock duration.

In one transaction, the first table stays locked while every later statement waits and runs. Split migrations that need not be atomic.

Foreign keys lock two tables

Adding a foreign key takes SHARE ROW EXCLUSIVE on both the referencing and the referenced table, and validating it scans the referencing table. A migration that adds a foreign key to a hot parent table, such as users, can block writes on users while it waits or runs. The NOT VALID pattern, covered in the next section, splits the change so the strong lock is held only briefly and the scan happens under a weaker lock.

Watching a migration live

While a migration runs, a second session should watch pg_stat_activity and pg_locks for queries waiting on the target table, with a query that shows wait_event_type of Lock and the blocking pids. If waits grow, cancelling the migration with pg_cancel_backend restores traffic immediately. Teams that run large migrations often have a script that watches waits and cancels automatically above a threshold, as a safety net beyond lock_timeout.

Where the danger comes from

Most migration outages come from a small set of patterns: a strong lock waiting behind a long query, a change that rewrites a large table under ACCESS EXCLUSIVE, an index built without CONCURRENTLY, a constraint validated under a strong lock, and a backfill run as one huge UPDATE. Each has a safe alternative that splits the change into steps holding weaker locks or holding strong locks only for an instant. The rest of this lesson covers those alternatives.

Lock levels of common statements

A short reference helps during review. ACCESS EXCLUSIVE is taken by most ALTER TABLE forms, DROP TABLE, TRUNCATE, plain REINDEX and VACUUM FULL. SHARE is taken by CREATE INDEX. SHARE ROW EXCLUSIVE is taken by ADD FOREIGN KEY and CREATE TRIGGER. SHARE UPDATE EXCLUSIVE is taken by VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY, VALIDATE CONSTRAINT and some ALTER TABLE SET forms. The documentation lists the lock for each ALTER TABLE subcommand, and checking it before writing a migration avoids surprises.

DDL can lock more than the table named in the statement. Adding a foreign key locks the referenced table, creating a trigger can lock the table it watches, and altering a partitioned table can lock every partition. Dropping a table referenced by views or foreign keys touches those objects too. When a migration seems to block unrelated traffic, pg_locks for the migration pid shows every relation it holds or waits for.

Migrations on replicas

On a physical standby, the replay of an ACCESS EXCLUSIVE lock from the primary conflicts with queries reading the table on the standby. Depending on max_standby_streaming_delay, either replay waits, letting the standby lag, or the standby cancels the conflicting queries. A migration that is harmless on the primary can therefore cancel long reports on replicas. Scheduling heavy migrations when replica workloads are light, or accepting short lag, avoids surprises.

Advisory locks around migrations

Migration tools usually take an advisory lock so that only one process runs migrations at a time, which prevents two deploys from applying the same migration concurrently. The lock is held for the whole migration run, so a stuck migration also blocks the next deploy. Knowing which advisory lock the tool uses, and how to see it in pg_locks, helps diagnose deploys that hang before any DDL runs.

Cancelling a stuck migration

If a migration is blocking traffic and has no lock_timeout, pg_cancel_backend on its pid cancels the statement and rolls back its transaction, releasing its queue position at once. pg_terminate_backend ends the whole session if cancellation does not work. Knowing the migration pid in advance, by logging pg_backend_pid at the start, saves precious seconds during an incident.

Bound every lock wait

Most DDL needs ACCESS EXCLUSIVE, and a waiting request blocks every later query on the table. Run migrations with a short lock_timeout and a retry loop, add statement_timeout for supposedly instant changes, keep migration transactions small and clear long transactions before starting.