Row locks and deadlocks
A sale goes live, requests start hanging, and a few fail with deadlock detected. Both come from row locks. Here is where Postgres keeps a row lock, what a waiting session is actually waiting for, and how two transactions end up stuck on each other.
01 Read, decide, write needs a lock
MVCC lets a plain SELECT read without waiting, which is exactly the problem when your code reads, decides, then writes. Two requests can both read “1 left” and both sell it. Transactions and what isolation levels stop showed the fix: take the row lock when you read.
FOR UPDATE returns the same row a plain SELECT would, and also locks it until the transaction ends. Any other transaction that tries to lock, update or delete that row waits. Plain reads still do not wait. Every UPDATE and DELETE also takes a row lock on each row it changes, whether you asked or not.
02 Where a row lock lives
Postgres has no table of row locks in memory. A lock is written on the row version itself: the locker’s xid goes into xmax, with a flag that says “locked only”. That is why a transaction can lock a million rows without running out of lock memory. Here session A holds FOR UPDATE on account 1 and has not committed:
Account 1 shows xmax 764 though nobody deleted it. A waiting session reads that stamp, and if 764 is still running, it waits on transaction 764 to end. Below, the same idea on the last seat of a giveaway. Both runs are real on Postgres 16; the trace’s xids are examples.
- just written or sent
- waiting
- checked by B
- old or meaningless
- not written yet
Seat 1 is the last one left: holder is empty. Two people press “Claim” at the same moment, and each request runs SELECT … FOR UPDATE on the seat, then decides.
When several transactions hold FOR SHARE on one row, one xmax cannot hold them all. Postgres then stores a MultiXact id, which points to a list of lockers kept in pg_multixact.
03 See who is waiting, and on whom
While B is stuck in the trace above, pg_stat_activity shows it waiting on a lock of type transactionid, and pg_blocking_pids names A:
Read the first row carefully: the blocker is idle in transaction. It is not busy; it is waiting for its app to send the next statement. Most long lock waits in production look like this: an app that opened a transaction, took a lock, and then made a slow network call. In pg_locks the same moment shows B’s ShareLock on transaction 759 with granted = f, plus a tuple lock B holds to keep its place at the front of the queue for that row.
04 Four strengths of row lock
FOR UPDATE is the strongest of four. The weaker ones exist so that common operations do not block each other more than they must:
| Requested | FOR KEY SHARE | FOR SHARE | FOR NO KEY UPDATE | FOR UPDATE |
|---|---|---|---|---|
| FOR KEY SHARE | waits | |||
| FOR SHARE | waits | waits | ||
| FOR NO KEY UPDATE | waits | waits | waits | |
| FOR UPDATE | waits | waits | waits | waits |
Read a row across: an empty cell means the two can be held at once. A plain UPDATE takes FOR NO KEY UPDATE unless it changes a key column (one with a unique index), in which case it takes FOR UPDATE, as DELETE does. A foreign key check on insert takes FOR KEY SHARE on the parent row, so adding order items does not block someone updating the customer’s address.
05 Deadlock: two transactions stuck on each other
A lock wait ends when the holder commits. A deadlock is a wait that can never end, because the holder is itself waiting for you. The classic shape is two transactions that lock the same two rows in opposite orders:
- just locked or run
- waiting
- waits for
- the cycle
- cancelled
- no lock
Two transfers run at once. A moves 10 from account 1 to account 2; B moves 10 from account 2 to account 1. Each transaction updates its “from” row first.
This is the error session A got in the real run. Each process is named by its pid, and each wait by the transaction it is waiting for:
Here the session that ran the check was the one cancelled, but the Postgres documentation says not to rely on which side loses. Treat 40P01 like a serialization failure: roll back and run the whole transaction again. pg_stat_database.deadlocks counts them per database.
06 Lock in one order, and bound the wait
A cycle needs two transactions that lock rows in different orders. Lock them in the same order everywhere, and the second transaction waits at the first row instead of grabbing the other one. ORDER BY with FOR UPDATE locks rows in sorted order, because Postgres places the lock step above the sort in the plan.
-- transfer(from, to)UPDATE accounts SET balance = balance - 10WHERE id = :from;UPDATE accounts SET balance = balance + 10WHERE id = :to;
-- transfer(from, to)SELECT id FROM accountsWHERE id IN (:from, :to)ORDER BY id FOR UPDATE;UPDATE accounts SET balance = balance - 10WHERE id = :from;UPDATE accounts SET balance = balance + 10WHERE id = :to;
Waiting itself can also be the bug. When thousands of requests want one hot row, they queue on it one at a time. Postgres gives you three ways not to wait. These errors are from the real run, with A holding the seat:
07 When it bites
A migration’s ALTER TABLE needs an ACCESS EXCLUSIVE table lock. If one long transaction is using the table, the ALTER waits, and every new query on that table queues behind the ALTER, including plain reads. Set lock_timeout before running migrations, and retry.
BEGIN; SELECT … FOR UPDATE; -- then call the payment APIHolding a lock across a network callEvery other request for that row waits for the slowest call you make. Do the slow work before the transaction, or record intent and finish in a second short transaction.UPDATE prizes SET stock = stock - 1 WHERE id = 7;One hot row for everyoneCorrect, but every claim queues on one row lock, so throughput is one transaction at a time. Split stock into several rows and pick one with SKIP LOCKED, or hand out claims from a queue.INSERT INTO order_items (order_id, …) VALUES (42, …);Foreign keys take locks tooInserting a child row takes FOR KEY SHARE on the parent row, so it waits behind anyone deleting the parent or changing its key. Ordinary updates of the parent take FOR NO KEY UPDATE and do not block it.SELECT … FOR UPDATE; -- REPEATABLE READWaiting, then failingAt REPEATABLE READ, if the holder changed the row and committed, your locking statement fails with 40001 after the wait instead of reading the new version. Retry the whole transaction.deadlock_timeout = 1sLogging lock waitsTurn on log_lock_waits and Postgres logs every wait longer than deadlock_timeout, with both queries. It is the cheapest way to find which code holds locks too long.