Postgres "deadlock detected": how to read the error, reproduce it, and fix the four patterns behind it

What ERROR: deadlock detected (SQLSTATE 40P01) means in PostgreSQL, how to read the DETAIL and CONTEXT lines, and how to fix the four common deadlock patterns: rows updated in opposite order, unique keys inserted in opposite order, FOR SHARE followed by UPDATE, and SELECT FOR UPDATE on a parent row after inserting children. Every example reproduced with two sessions on Postgres 17.11.

Ripley15 min read
On this page

Sooner or later every busy Postgres app logs ERROR: deadlock detected. It usually shows up under load, disappears when you try to reproduce it, and the message talks about process IDs and transaction numbers, while the statements involved only appear in the server log. The good news is that the error contains more clues than it seems, and the fix usually comes down to one rule from the manual: take locks in a consistent order. In this post we read the error line by line, explain what Postgres does before it raises it, and then reproduce four common patterns with two psql sessions, each with a fix you can apply: rows updated in opposite order, unique keys inserted in opposite order, a shared lock that is later upgraded, and a SELECT ... FOR UPDATE on a parent row after inserting child rows. Every example and every output below comes from scripted replays on PostgreSQL 17.11, the major version Relyt One runs.

The short version

What you see in CONTEXTLikely patternFix
while updating tupleTwo transactions update the same rows in a different orderLock rows in one order: SELECT ... ORDER BY id FOR NO KEY UPDATE first
while inserting index tupleTwo transactions insert the same unique keys in a different orderSort the keys and insert them in one statement
while updating tuple, both statements on the same rowBoth read with FOR SHARE, then both try to UPDATETake the lock you will need from the start: FOR NO KEY UPDATE
while locking tuple, on a parent tableBoth inserted child rows, then both SELECT ... FOR UPDATE the parentUse FOR NO KEY UPDATE on the parent

And in every case: retry the whole transaction on SQLSTATE 40P01. A deadlock is not data corruption; Postgres has already rolled back one transaction so that the other can finish.

What a deadlock is

A deadlock is a cycle of waits. Transaction A holds a lock that B needs, and B holds a lock that A needs. Neither can continue, and neither will give up on its own: without deadlock detection, the PostgreSQL manual says a transaction "will wait indefinitely for conflicting locks to be released".

Transaction A holds row id = 1 and waits for row id = 2; transaction B holds row id = 2 and waits for row id = 1. After deadlock_timeout Postgres cancels one of them with ERROR: deadlock detected (SQLSTATE 40P01).

You do not need explicit LOCK statements to get there. Every UPDATE and DELETE locks the rows it changes until the transaction ends, so two ordinary transactions that touch the same rows in a different order are enough.

Reading the error

Here is the error from the first example below, exactly as psql printed it:

ERROR:  deadlock detected
DETAIL:  Process 96 waits for ShareLock on transaction 749; blocked by process 97.
Process 97 waits for ShareLock on transaction 748; blocked by process 96.
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,2) in relation "accounts"

Line by line:

  • DETAIL describes the cycle. Each line is one edge: a backend process, what it waits for, and who is in the way. Two lines means two sessions; you can see three or more in longer cycles.
  • ShareLock on transaction 749 looks odd, because nobody asked for a share lock on a transaction. This is how Postgres waits for a row. Row locks are stored in the row itself, not in the lock manager, so a session that finds a row locked by another transaction waits for that transaction to end. The pg_locks documentation describes it: a process that needs to wait for another transaction "does so by attempting to acquire share lock on the other transaction's ID". So ShareLock on transaction N means "waiting for transaction N to finish": usually because it has locked a row this session needs, or, as in pattern 2 below, because it has inserted a unique key that is not committed yet.
  • CONTEXT is the most useful line for the client. It names the table and what the statement was doing when it was cancelled: updating a row, inserting into an index, or locking a row. (0,2) is the physical location of the row (page 0, item 2), which changes on every update, so do not try to look it up later.
  • HINT: See server log for query details. The client only gets the error. The server log gets the statements of every process in the cycle:
ERROR:  deadlock detected
DETAIL:  Process 96 waits for ShareLock on transaction 749; blocked by process 97.
	Process 97 waits for ShareLock on transaction 748; blocked by process 96.
	Process 96: UPDATE accounts SET balance = balance + 10 WHERE id = 2;
	Process 97: UPDATE accounts SET balance = balance + 20 WHERE id = 1;
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,2) in relation "accounts"
STATEMENT:  UPDATE accounts SET balance = balance + 10 WHERE id = 2;

If you can read your server log, start there: the two Process N: lines usually tell you the pattern straight away. Keep in mind that they show the statement each process was running at that moment, not the earlier statements in the same transaction that took the other locks.

What Postgres does before raising it

Postgres does not check for deadlocks every time a session waits for a lock. The check is relatively expensive, so a waiting session first sleeps for deadlock_timeout (default 1s) and only then looks for a cycle. If it finds one, one transaction in the cycle gets the error and is rolled back; its locks are released, and the others continue.

You can see the timer in our first replay. With \timing on, session A's blocked UPDATE failed after about 1,007 ms, which is deadlock_timeout. Session B started waiting half a second later than A, and its UPDATE succeeded after about 496 ms, as soon as A's locks were gone.

Two things follow from this:

  • Which transaction is cancelled is not something to design around. In our replays it was always the session that had been waiting longer (its timer fired first). The manual is explicit that "exactly which transaction will be aborted is difficult to predict and should not be relied upon". Both sides need to be able to retry.
  • Changing deadlock_timeout does not prevent deadlocks. It only changes how long the sessions wait before one is cancelled. The documentation suggests that the setting "should exceed your typical transaction time", and changing it needs superuser or the appropriate SET privilege.

The lab

All four patterns use the same three small tables:

CREATE TABLE accounts (
  id      bigint PRIMARY KEY,
  owner   text   NOT NULL,
  balance numeric NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 'alice', 100), (2, 'bob', 100);

CREATE TABLE tags (name text PRIMARY KEY);

CREATE TABLE orders (
  id    bigint PRIMARY KEY,
  total numeric NOT NULL DEFAULT 0
);
CREATE TABLE order_lines (
  id       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_id bigint NOT NULL REFERENCES orders (id),
  amount   numeric NOT NULL
);
INSERT INTO orders VALUES (1, 0);

To make the timing deterministic, each example runs two psql sessions at the same time. Session A starts immediately, session B starts half a second later, and each sleeps for one second between its two steps with SELECT pg_sleep(1). That forces this order: A takes its first lock, B takes its first lock, A asks for its second lock and waits, B asks for its second lock and closes the cycle. The data is reset before each example. In a real app the sleep is whatever your code does between two statements: a network round trip, a call to another service, or just load.

Pattern 1: the same rows in opposite order

The classic case, and the one the manual uses as its example: a transfer from alice to bob runs at the same time as a transfer from bob to alice. Each updates the sender first.

-- Session A: alice pays bob 10
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
SELECT pg_sleep(1);
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;

-- Session B, half a second later: bob pays alice 20
BEGIN;
UPDATE accounts SET balance = balance - 20 WHERE id = 2;
SELECT pg_sleep(1);
UPDATE accounts SET balance = balance + 20 WHERE id = 1;
COMMIT;

Session A's second UPDATE fails with the error shown above (while updating tuple (0,2) in relation "accounts"), its COMMIT turns into a ROLLBACK, and session B commits.

Fix: lock the rows in one global order before changing them. The manual calls this "the best defense against deadlocks": make sure every transaction acquires locks "on multiple objects in a consistent order". The simplest consistent order is the primary key:

BEGIN;
SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR NO KEY UPDATE;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;

Session B does the same with WHERE id IN (2, 1); the list order does not matter, the ORDER BY does. With a locking clause, Postgres sorts the rows first and then locks them in that order (the SELECT documentation notes that "ORDER BY is applied first"). Now B blocks on row 1 until A commits, then continues. In the replay there was no error and the balances ended at 110 and 90.

Why FOR NO KEY UPDATE and not FOR UPDATE? An UPDATE that does not change a key column takes the FOR NO KEY UPDATE row lock, so locking ahead with the same mode is enough, and it does not block foreign key checks from other transactions (more on that in pattern 4).

The same applies when you change many rows in one statement. UPDATE ... WHERE id IN (...) locks rows in whatever order the plan visits them, not the order of your list, so two batch jobs with overlapping rows can still deadlock. Locking first with ORDER BY ... FOR NO KEY UPDATE gives you a predictable order.

Pattern 2: unique keys inserted in opposite order

Deadlocks are not only about updates. When two transactions insert the same value into a unique index, the second one has to wait to find out whether the first commits. If they insert two keys in opposite order, that wait becomes a cycle. ON CONFLICT DO NOTHING does not help, because it still has to wait for the first transaction to decide:

-- Session A
BEGIN;
INSERT INTO tags VALUES ('postgres') ON CONFLICT DO NOTHING;
SELECT pg_sleep(1);
INSERT INTO tags VALUES ('sql') ON CONFLICT DO NOTHING;
COMMIT;

-- Session B, half a second later
BEGIN;
INSERT INTO tags VALUES ('sql') ON CONFLICT DO NOTHING;
SELECT pg_sleep(1);
INSERT INTO tags VALUES ('postgres') ON CONFLICT DO NOTHING;
COMMIT;
ERROR:  deadlock detected
DETAIL:  Process 137 waits for ShareLock on transaction 759; blocked by process 138.
Process 138 waits for ShareLock on transaction 758; blocked by process 137.
HINT:  See server log for query details.
CONTEXT:  while inserting index tuple (0,2) in relation "tags"

The giveaway is while inserting index tuple. You see this in apps that upsert a batch of rows (tags, counters, "get or create" lookups) in whatever order they arrived.

Fix: sort the keys and insert them together. Sort in your application, or let the statement do it:

-- Session A
INSERT INTO tags
SELECT unnest(ARRAY['sql', 'postgres', 'locks']) ORDER BY 1
ON CONFLICT DO NOTHING;

-- Session B
INSERT INTO tags
SELECT unnest(ARRAY['postgres', 'sql', 'mvcc']) ORDER BY 1
ON CONFLICT DO NOTHING;

In the replay we kept session A's transaction open for a second after its insert. Session B inserted mvcc, waited at postgres until A committed, skipped the two keys that now existed, and reported INSERT 0 1. No deadlock: both sessions met the shared keys in the same order, so one could only ever wait for the other.

Pattern 3: reading with a shared lock, then updating

This one surprises people because both sessions touch only one row. Each reads the row with FOR SHARE (to make sure it does not change while the code decides what to do), then updates it:

-- Both sessions, B starting half a second after A
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR SHARE;
SELECT pg_sleep(1);
UPDATE accounts SET balance = balance - 5 WHERE id = 1;
COMMIT;
ERROR:  deadlock detected
DETAIL:  Process 179 waits for ShareLock on transaction 769; blocked by process 180.
Process 180 waits for ShareLock on transaction 768; blocked by process 179.
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,1) in relation "accounts"

Shared locks do not conflict with each other, so both sessions get one. Then each needs an exclusive lock for the UPDATE, which conflicts with the other session's shared lock. Each is waiting for the other to let go. The server log shows the same UPDATE on both sides, which is how you recognize this pattern.

Fix: take the strongest lock you will need first. The manual says it directly: "the first lock acquired on an object in a transaction" should be "the most restrictive mode that will be needed for that object".

BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR NO KEY UPDATE;
UPDATE accounts SET balance = balance - 5 WHERE id = 1;
COMMIT;

Now B's SELECT waits until A commits and then reads A's result. In the replay A read 100, B read 95, and the balance ended at 90. If you use an ORM, check which locking clause its lock option generates: a shared lock is the wrong choice when you intend to write.

If the change is just arithmetic, you may not need the read at all: UPDATE accounts SET balance = balance - 5 WHERE id = 1 AND balance >= 5 does the check and the change in one statement, and reports UPDATE 0 when the balance is too low.

Pattern 4: foreign keys and SELECT FOR UPDATE on the parent

The last pattern involves a lock you never asked for. When you insert a row that references a parent row, Postgres locks the parent row so that it cannot be deleted, or its key changed, before your transaction commits. That lock is FOR KEY SHARE. You can see it with the pgrowlocks contrib extension (by default usable by superusers, members of pg_stat_scan_tables and users with SELECT on the table) while a transaction with an uncommitted insert is open:

-- Session A (still open): INSERT INTO order_lines (order_id, amount) VALUES (1, 30);
-- Session B:
CREATE EXTENSION IF NOT EXISTS pgrowlocks;
SELECT locked_row, multi, modes FROM pgrowlocks('orders');
 locked_row | multi |       modes
------------+-------+-------------------
 (0,1)      | f     | {"For Key Share"}

Now consider a common way to keep an order total: insert the line, then lock the order and update the total.

-- Both sessions, B starting half a second after A
BEGIN;
INSERT INTO order_lines (order_id, amount) VALUES (1, 30);  -- B adds 12
SELECT pg_sleep(1);
SELECT total FROM orders WHERE id = 1 FOR UPDATE;
UPDATE orders SET total = total + 30 WHERE id = 1;
COMMIT;
ERROR:  deadlock detected
DETAIL:  Process 223 waits for ShareLock on transaction 779; blocked by process 222.
Process 222 waits for ShareLock on transaction 778; blocked by process 223.
HINT:  See server log for query details.
CONTEXT:  while locking tuple (0,1) in relation "orders"

Both inserts take FOR KEY SHARE on order 1, and those don't conflict. But FOR UPDATE conflicts with FOR KEY SHARE, so each session's SELECT ... FOR UPDATE waits for the other's foreign key lock. The clue is while locking tuple on the parent table, in a transaction that inserted into a child table.

Fix: use FOR NO KEY UPDATE on the parent. It is the right lock here: it "will not block SELECT FOR KEY SHARE commands", so it does not conflict with foreign key checks, while still conflicting with other FOR NO KEY UPDATE and FOR UPDATE locks. We confirmed it directly with lock_timeout = '200ms' while another transaction held the foreign key lock: FOR UPDATE gave up with canceling statement due to lock timeout, and FOR NO KEY UPDATE returned at once. With that one change, the replay had no deadlock: A locked the order while B's foreign key lock was still there, updated the total from 0 to 30 and committed, and B then updated it to 42.

FOR UPDATE is only needed if you are going to delete the row or change a column that a foreign key can reference. Plain UPDATEs of other columns already use the weaker lock, so here it was the explicit FOR UPDATE that turned two harmless foreign key locks into a deadlock. Locking the parent before inserting the children also works, because then both sessions take their locks in the same order.

Finding deadlocks before users do

  • Count them. pg_stat_database has a running count per database. After our four examples:

    SELECT datname, deadlocks FROM pg_stat_database WHERE datname = current_database();
     datname  | deadlocks
    ----------+-----------
     postgres |         4

    A counter that grows is a signal even if no one reports an error, for example when your code already retries.

  • See who is waiting right now. Long lock waits that are not deadlocks look the same to users: requests that hang. pg_blocking_pids() shows who blocks whom:

    SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, wait_event,
           now() - xact_start AS xact_age, left(query, 60) AS query
    FROM pg_stat_activity
    WHERE cardinality(pg_blocking_pids(pid)) > 0;
     pid | blocked_by | wait_event_type |  wait_event   |    xact_age     |                          query
    -----+------------+-----------------+---------------+-----------------+---------------------------------------------------------
     270 | {271}      | Lock            | transactionid | 00:00:00.492165 | UPDATE accounts SET balance = balance + 1 WHERE id = 1;

    wait_event = transactionid is the same "waiting for another transaction's row lock" you saw in the deadlock message. The manual warns that frequent calls to this function can affect performance, so run it when investigating, not in a tight loop.

  • Log long waits. log_lock_waits writes a log message when a session waits longer than deadlock_timeout for a lock. It is off by default in Postgres 17 and needs superuser or the appropriate SET privilege to change.

  • Cap waits. lock_timeout aborts a statement that waits longer than the limit for any single lock (default 0, no limit), with SQLSTATE 55P03. It does not prevent deadlocks, but it keeps a stuck request from waiting for a long-running transaction indefinitely.

Retry, but don't rely on retries alone

Even with careful ordering, some deadlocks are hard to rule out, for example when triggers or several services touch the same rows. The manual's advice is to avoid them where you can and, where you cannot, handle them by "retrying transactions that abort due to deadlocks". The rules:

  • Retry the whole transaction from BEGIN, not the failing statement. After the error the transaction is aborted; in pattern 4 the next statement in session A failed with current transaction is aborted, commands ignored until end of transaction block.
  • Match on SQLSTATE 40P01, not on the message text.
  • Back off with a random delay, and cap the number of attempts.

Our transaction isolation post has a small Node.js wrapper that retries 40P01 together with serialization failures (40001). But treat a deadlock you see often as a bug to fix with one of the patterns above: every retry is work done twice, and the cancelled transaction has already waited deadlock_timeout before it gets the error. Keep transactions short, too. The longer a transaction holds locks, for example while it calls another service, the more likely another one arrives in the wrong order.

Try it on a branch

The four patterns and their fixes use only standard PostgreSQL 17 SQL, which is what Relyt One runs (pgrowlocks is only a diagnostic, and it is a separate extension). The difficult part of a real deadlock is usually reproducing it with your schema and your data, not understanding it. On Relyt One you can create a branch from your production database, which starts from the parent's data with copy-on-write storage and runs on its own compute. Run the two transactions from the server log against it in two sessions, try the fix, watch the deadlocks counter, and then delete the branch.

For a one-screen definition, see the deadlock entry in our Postgres glossary. The manual's explicit locking chapter has the full row and table lock conflict tables.

Start for free

TagsPostgressqllockingconcurrency

Written by

Ripley

Follow the blog with RSS

Add the feed to your RSS reader and new articles show up there as soon as they are published.

Subscribe via RSS

Your next database is one branch away.

Create a free project in under a minute. No credit card, no setup.

Back to blog