Skip to content

Row locks and deadlocks

Deep diveUnder the hood

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.

SQL
BEGIN;
SELECT stock FROM prizes WHERE id = 7 FOR UPDATE; -- lock now
-- the app checks stock > 0
UPDATE prizes SET stock = stock - 1 WHERE id = 7;
COMMIT; -- lock released

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:

Text
SELECT ctid, xmin, xmax, * FROM accounts ORDER BY id;
ctid | xmin | xmax | id | balance
-------+------+------+----+---------
(0,1) | 763 | 764 | 1 | 100
(0,2) | 763 | 0 | 2 | 100

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.

Two claims on the last seat
Step 1 of 6
Versions of seat 1 (example xids)
xminxmaxholder
(0,1)7580NULL
(0,4)
Messages, top to bottom in time
Session APostgresSession BNothing sent yet
  • 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:

Text
SELECT pid, state, wait_event_type, wait_event,
pg_blocking_pids(pid) AS blocked_by, left(query, 50) AS query
FROM pg_stat_activity WHERE backend_type = 'client backend';
pid | state | wait_event_type | wait_event | blocked_by | query
-----+---------------------+-----------------+---------------+------------+------------------
82 | idle in transaction | Client | ClientRead | {} | SELECT * FROM seats WHERE id=1 FOR UPDATE
83 | active | Lock | transactionid | {82} | SELECT * FROM seats WHERE id=1 FOR UPDATE

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:

Which row locks conflict (Postgres 16)
RequestedFOR KEY SHAREFOR SHAREFOR NO KEY UPDATEFOR UPDATE
FOR KEY SHAREwaits
FOR SHAREwaitswaits
FOR NO KEY UPDATEwaitswaitswaits
FOR UPDATEwaitswaitswaitswaits

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:

Two transfers that lock each other
Step 1 of 8
Row locks held
locked by
account 1
account 2
Who waits for whom
Axid 765
Bxid 766
Statements, in order
Empty
  • 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:

Text
ERROR: deadlock detected
DETAIL: Process 86 waits for ShareLock on transaction 766; blocked by process 87.
Process 87 waits for ShareLock on transaction 765; blocked by process 86.
HINT: See server log for query details.
CONTEXT: while updating tuple (0,2) in relation "accounts"

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.

Order depends on input
-- transfer(from, to)
UPDATE accounts SET balance = balance - 10
WHERE id = :from;
UPDATE accounts SET balance = balance + 10
WHERE id = :to;
Lowest id first, always
-- transfer(from, to)
SELECT id FROM accounts
WHERE id IN (:from, :to)
ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance - 10
WHERE id = :from;
UPDATE accounts SET balance = balance + 10
WHERE 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:

SQL
SELECT * FROM seats WHERE id = 1 FOR UPDATE NOWAIT;
ERROR: could not obtain lock on row in relation "seats" -- at once, 55P03
SET lock_timeout = '2s';
SELECT * FROM seats WHERE id = 1 FOR UPDATE;
ERROR: canceling statement due to lock timeout -- after 2 s, 55P03
SELECT id FROM seats WHERE holder IS NULL
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
id
----
2 -- seat 1 skipped
NOWAITFail at onceFor “someone else is editing this, try again” screens.
lock_timeoutWait, but not foreverA ceiling on any lock wait in the session, including table locks for migrations.
SKIP LOCKEDTake the next free rowFor job queues and pools of identical items: each worker gets a different row, and nobody queues.

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.

08 Check yourself

Question

Session A holds SELECT … FOR UPDATE on order 5. Session B runs a plain SELECT * FROM orders WHERE id = 5. What happens to B?

Question

Two workers each lock jobs with SELECT … FOR UPDATE LIMIT 1 on the oldest pending job. What do you see?

Question

Transfers sometimes fail with 40P01. Which change stops it at the cause?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?