Locks and Lock Queues

Topics Covered

Table Level Lock Modes

Why tables need locks

The eight modes

Reading the conflict table

Locks are held until commit

ALTER TABLE lock levels

Fast and slow ALTER TABLE

Explicit LOCK TABLE

Lock levels of common maintenance commands

Locks on indexes and sequences

How many locks a query takes

The fast path for weak locks

Locks in subtransactions and savepoints

Checking the lock a statement takes

MVCC lets readers and writers proceed without blocking each other, but Postgres still uses locks to protect table definitions, coordinate DDL and order conflicting writes to the same row. Most production lock incidents come from a small number of patterns: DDL waiting behind a long transaction while everything else queues behind the DDL, row lock contention on hot rows, and deadlocks. Understanding the lock modes and their conflicts is the foundation for avoiding all of them. This section covers the eight table level lock modes and which commands take them.

Why tables need locks

Every query takes a lock on each table it touches, even a plain SELECT, so that the table cannot be dropped or have its structure changed while the query is running. These locks are held until the end of the transaction, not the end of the statement. Most of them are weak and conflict only with schema changes, so they never block ordinary traffic. The trouble starts when a command needs a strong lock, because it must wait for every weaker conflicting lock to be released.

The eight modes

From weakest to strongest, the table lock modes are ACCESS SHARE, taken by SELECT; ROW SHARE, taken by SELECT FOR UPDATE and FOR SHARE; ROW EXCLUSIVE, taken by INSERT, UPDATE, DELETE and MERGE; SHARE UPDATE EXCLUSIVE, taken by VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY and some ALTER TABLE forms; SHARE, taken by CREATE INDEX without CONCURRENTLY; SHARE ROW EXCLUSIVE, taken by CREATE TRIGGER and some constraints; EXCLUSIVE, taken by REFRESH MATERIALIZED VIEW CONCURRENTLY; and ACCESS EXCLUSIVE, taken by DROP, TRUNCATE, most ALTER TABLE forms, VACUUM FULL, CLUSTER and LOCK TABLE by default.

Reads and writes take weak locks that coexist. Schema changes take strong locks that conflict with them and must wait.

Reading the conflict table

The documentation conflict table is the reference, but a few rules cover most cases. ACCESS EXCLUSIVE conflicts with everything, including plain SELECT. ACCESS SHARE conflicts only with ACCESS EXCLUSIVE. ROW EXCLUSIVE, taken by every write, conflicts with SHARE and stronger, so a non concurrent CREATE INDEX blocks writes but not reads. SHARE UPDATE EXCLUSIVE conflicts with itself, so two vacuums or a vacuum and a concurrent index build on the same table cannot run together, but it does not conflict with reads or writes.

Locks are held until commit

A lock taken by any statement in a transaction stays held until the transaction commits or rolls back. A transaction that runs a quick SELECT on a table and then sits idle for an hour keeps ACCESS SHARE on that table for the whole hour, and any ALTER TABLE must wait for it. This is why idle in transaction sessions are dangerous beyond holding back vacuum: they hold locks invisibly. idle_in_transaction_session_timeout terminates such sessions after a limit and is one of the most valuable safety settings.

ALTER TABLE lock levels

Not every ALTER TABLE needs ACCESS EXCLUSIVE. Adding a foreign key takes SHARE ROW EXCLUSIVE on both tables, validating a constraint added with NOT VALID takes SHARE UPDATE EXCLUSIVE, setting statistics targets or storage parameters take SHARE UPDATE EXCLUSIVE, and attaching a partition takes SHARE UPDATE EXCLUSIVE on the parent since version 12. Adding a column, dropping a column, changing a type and renaming take ACCESS EXCLUSIVE. Knowing the level of each form is essential for planning migrations, and the documentation lists it for each subcommand.

Fast and slow ALTER TABLE

The lock level is only half of the risk; the other half is how long the lock is held. Adding a nullable column or a column with a constant default since version 11 only updates the catalog and finishes in milliseconds under ACCESS EXCLUSIVE. Changing a column type in a way that requires rewriting every row, such as int to bigint, holds ACCESS EXCLUSIVE for the full rewrite, which can take hours on a large table and block all traffic. Migrations must avoid long operations under strong locks, covered in the zero downtime migrations lesson.

Explicit LOCK TABLE

LOCK TABLE takes a chosen mode explicitly, defaulting to ACCESS EXCLUSIVE, and holds it until the end of the transaction. It is occasionally useful, for example to take SHARE ROW EXCLUSIVE before a batch that must not run concurrently with another copy of itself, but it is easy to misuse. LOCK TABLE with the NOWAIT option fails immediately rather than waiting, which is safer for scripts that should give up rather than queue behind long transactions.

Lock levels of common maintenance commands

Maintenance commands differ widely in how disruptive they are. VACUUM and ANALYZE take SHARE UPDATE EXCLUSIVE, so they run alongside reads and writes. VACUUM FULL and CLUSTER rewrite the table under ACCESS EXCLUSIVE and block everything for the whole rewrite. REINDEX without CONCURRENTLY takes a lock that blocks writes and, for the index itself, reads that would use it, while REINDEX CONCURRENTLY since version 12 uses weaker locks. TRUNCATE takes ACCESS EXCLUSIVE but finishes quickly because it swaps in new empty files. Choosing the concurrent variant whenever one exists is a basic rule of production maintenance.

Locks on indexes and sequences

Locks are taken on indexes as well as tables. A query that uses an index takes ACCESS SHARE on it, and an index build or drop takes stronger locks on both the index and its table. DROP INDEX takes ACCESS EXCLUSIVE on the table, which can queue like any other DDL, while DROP INDEX CONCURRENTLY waits for existing transactions to finish using the index without blocking them. Sequences are protected by their own lightweight mechanism for nextval, so concurrent inserts that draw ids do not block each other.

How many locks a query takes

A query on a partitioned table with hundreds of partitions may take a lock on every partition and every index of each partition that the planner considers, which can mean thousands of locks for one statement. Each lock acquisition costs time, and the shared lock table has a fixed size set by max_locks_per_transaction times max_connections. Partition pruning at planning time reduces the number of locks taken, which is one reason queries on partitioned tables should include the partition key in their conditions.

The fast path for weak locks

Taking a lock in the shared lock table requires a lightweight lock on one of its partitions, which becomes a point of contention when many sessions lock the same table at high rates. Postgres avoids this for the common weak modes with a fast path: each backend records up to a small number of weak relation locks in its own slots, and only strong lock requests check those slots. Queries that touch many relations overflow the fast path and fall back to the shared table, which shows up as LWLock waits on lock manager under heavy load. Version 18 increased the number of fast path slots to reduce this.

Locks in subtransactions and savepoints

Locks acquired after a savepoint are released if the transaction rolls back to that savepoint, but locks acquired before it remain. Releasing a savepoint does not release its locks; they pass to the parent transaction and last until the end. Drivers and ORMs that wrap each statement in a savepoint to emulate statement level rollback therefore still hold every lock until commit. Understanding this matters when reasoning about how long a long batch with many savepoints holds its locks.

Checking the lock a statement takes

The most reliable way to know which lock a statement takes is to test it. In one session, begin a transaction, run the statement and leave the transaction open; in another, query pg_locks for the relation, which shows the mode that was granted. Rolling back afterwards leaves no trace. Doing this for each new kind of migration statement, on a test database, replaces guesswork about lock levels with facts, and the results can be recorded in the team migration guidelines.

Know the lock each command takes

Reads and writes take weak table locks that only conflict with schema changes. ACCESS EXCLUSIVE blocks everything including SELECT. Locks last until commit, so idle transactions hold them invisibly. Check the lock level and duration of every ALTER TABLE before running it in production.