PostgreSQL · Databases

ERROR: deadlock detected in PostgreSQL: Read the Log, Fix the Order

The error names two processes and says almost nothing else. Here is how to find the statements behind it, and the three shapes it usually has.

The alert says ERROR: deadlock detected. It fired once at 03:12, then not again for two days, then twice in an hour. A retry makes it go away, so nobody wants to look at it. But a retry only hides a bug that is still there. Under more load it fires more often.

The error text is short and the client gets none of the SQL. You see two process numbers, two transaction numbers and a hint to go and read the server log. This post reads that error line by line, shows where the two statements are, and covers three common shapes: two rows in opposite order, a foreign key, and a batch statement.

I ran every example here on PostgreSQL 17 in Docker. The output is real, except that I trimmed timestamps.

Short version:

  • The DETAIL lines are a circle of two processes that wait for each other. PostgreSQL rolled one transaction back. The other one carried on.
  • The two statements are in the server log, not in the client error. The log does not show the earlier statements that took the locks. That missing half is the usual reason a deadlock is hard to read.
  • Fix it with one lock order in every code path. Retry on 40P01 as a safety net, not as the cure.

The error, line by line

This is what the client got when I ran two transfers in opposite order:

ERROR:  deadlock detected
DETAIL:  Process 93 waits for ShareLock on transaction 741; blocked by process 100.
Process 100 waits for ShareLock on transaction 740; blocked by process 93.
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,2) in relation "accounts"
How to read the DETAIL lines of a deadlock error. Process 93 runs transaction 740 and waits for transaction 741. Process 100 runs transaction 741 and waits for transaction 740. That circle is the deadlock, and process 93 is the one that got the error. ShareLock on transaction means a row lock wait. Blocked by process N names the holder. The tuple and relation name the table. The statements are only in the server log.

Read it as a sentence with two halves:

  • Process 93 waits for transaction 741, which is process 100’s transaction.
  • Process 100 waits for transaction 740, which is process 93’s transaction.

That is the circle. Nobody can ever finish by waiting. The ShareLock on transaction wording looks odd, but it is normal for row locks. A row lock lives on the row, not in memory, so a session that wants a locked row waits for the transaction that holds it to end. The locks post has the detail.

The CONTEXT line says where the process that got the error was stuck: tuple (0,2) is the row’s position (page 0, slot 2) in accounts.

Two more facts from the PostgreSQL docs:

  • The SQLSTATE is 40P01, deadlock_detected. It is in the same class as 40001, serialization_failure, both named “Transaction Rollback” in the error code list.
  • Which transaction is aborted is, in the docs’ words, “difficult to predict and should not be relied upon”. In all three runs below it was the session that began waiting first, probably because its timer ran out first. Do not build on that.

Find the two statements in the server log

The client error has no SQL, probably because the other session’s statement could hold data you may not see. The statements are in the server log. The setting that puts them there is log_lock_waits.

SHOW log_lock_waits;
SHOW deadlock_timeout;

deadlock_timeout is how long a session waits on a lock before PostgreSQL runs the deadlock check. The default is 1 second. The check is not free, so the server does not run it for every wait. log_lock_waits writes a log line once a wait has lasted that long.

On PostgreSQL 17 and 18, log_lock_waits is off by default. I checked boot_val in pg_settings on 17. Run SHOW log_lock_waits on your server before you trust the log to have the lines below.

Update, November 2026: PostgreSQL 19 turns it on by default, according to its release notes.

This is the log for the deadlock above. I set log_line_prefix to '%m [%p] xid=%x ', which adds the time, the process id and the transaction id to every line:

[93] xid=740 LOG:  process 93 detected deadlock while waiting for ShareLock on transaction 741 after 1000.890 ms
[93] xid=740 DETAIL:  Process holding the lock: 100. Wait queue: .
[93] xid=740 CONTEXT:  while updating tuple (0,2) in relation "accounts"
[93] xid=740 STATEMENT:  UPDATE accounts SET balance = balance + 100 WHERE id = 2;
[93] xid=740 ERROR:  deadlock detected
[93] xid=740 DETAIL:  Process 93 waits for ShareLock on transaction 741; blocked by process 100.
	Process 100 waits for ShareLock on transaction 740; blocked by process 93.
	Process 93: UPDATE accounts SET balance = balance + 100 WHERE id = 2;
	Process 100: UPDATE accounts SET balance = balance + 50 WHERE id = 1;
[93] xid=740 HINT:  See server log for query details.
Four things in the server log around a deadlock. A LOG line saying still waiting means a slow wait that is not a deadlock yet. A LOG line saying detected deadlock means the check ran and found a circle. The ERROR line lists the statement each process was running when it started to wait. What is missing is the earlier statements in each transaction that took the locks they hold.

The two last lines of the DETAIL are the statements you want. Each one is what that process was running when it began to wait.

A wait that is slow but not a deadlock leaves a different trace. I made one session wait about two seconds for a row, and the log said:

[122] xid=754 LOG:  process 122 still waiting for ShareLock on transaction 753 after 1001.523 ms
[122] xid=754 DETAIL:  Process holding the lock: 115. Wait queue: 122.
[122] xid=754 STATEMENT:  UPDATE accounts SET balance = balance + 5 WHERE id = 1;
[122] xid=754 LOG:  process 122 acquired ShareLock on transaction 753 after 2090.218 ms

Lines like that, with no error after them, are only waits. They show where locks are contended before any deadlock does. The locks post shows how to see who is blocking whom while a wait is still going on.

The half the log does not show

Look at the log again. It names UPDATE ... WHERE id = 2 for process 93. But process 93 also holds a lock on row 1, and the statement that took it is not there. Row locks last until the transaction ends. The log only has what each process was running at the moment it began to wait.

Here the second statement gives the game away, because process 100 waits for row 1 and that is the row process 93 must hold. Often it does not. The next example shows the worst case, where the log lists the same statement twice.

To get the missing statements you need the history of the transaction. The options are the application’s own logs (log the statements and the request id inside every transaction), a comment on each query that names the code path, or log_statement = 'all' for a short window on a quiet server. Laurenz Albe’s debugging deadlocks post on the CYBERTEC blog walks through the same gap with a foreign key example.

Count how often it happens before you start. The counter is per database and resets with the statistics:

SELECT datname, deadlocks FROM pg_stat_database WHERE datname = current_database();

Shape 1: two rows, opposite order

This is the one in the PostgreSQL docs. Two transfers touch the same two accounts in opposite directions:

-- Session A                                   -- Session B
BEGIN;                                         BEGIN;
UPDATE accounts SET balance = balance - 100
  WHERE id = 1;
                                               UPDATE accounts SET balance = balance - 50
                                                 WHERE id = 2;
UPDATE accounts SET balance = balance + 100
  WHERE id = 2;   -- waits for B
                                               UPDATE accounts SET balance = balance + 50
                                                 WHERE id = 1;   -- waits for A

The fix is to take both locks first, in one fixed order, before changing anything:

BEGIN;
SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR NO KEY UPDATE;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
The same two transfers in two lock orders. Left, opposite order: A locks row 1, B locks row 2, A wants row 2 and waits, B wants row 1 and waits, so one gets deadlock detected. Right, same order with ORDER BY id: A locks rows 1 and 2, B waits for row 1, A updates both and commits, B then gets rows 1 and 2 and commits. Both finish.

I ran this with the same timing as the failing case: A first, B 0.3 seconds later, and a 1.5 second pause between the lock and the updates. B waited, A finished, B finished. No error, and the deadlock counter did not move.

Three details that matter:

  • The order must be the same in every code path. One path that locks ORDER BY id DESC brings the deadlock back. That is why the ledger post puts the sorted lock in one place that every posting goes through.
  • Use FOR NO KEY UPDATE when you only change non-key columns. A plain UPDATE takes that mode anyway. The docs also say the first lock acquired on an object should be the most restrictive one you will need. My own example: two transactions that each start with FOR SHARE on a row and then update it can deadlock.
  • Order by a column nobody changes. The SELECT docs warn that at READ COMMITTED, ORDER BY with a locking clause can return rows out of order if another transaction changes the ordering column while you wait for a lock. A primary key does not change, so ORDER BY id is safe.

Shape 2: the foreign key you forgot

This one is the hardest to read, because the log makes no sense. Two sessions each add an item to the same order, then recalculate by locking the order row:

BEGIN;
INSERT INTO order_items (order_id, price) VALUES (1, 10);
-- ... some work ...
SELECT id FROM orders WHERE id = 1 FOR UPDATE;
COMMIT;
A deadlock hidden in a foreign key. Both sessions insert an order item for order 1. Each insert takes FOR KEY SHARE on the order row, and two of those do not conflict. Then both run SELECT FOR UPDATE on order 1. FOR UPDATE conflicts with the other session’s FOR KEY SHARE, so each waits for the other and PostgreSQL reports deadlock detected. The log shows two identical SELECT statements. The fix is FOR NO KEY UPDATE, which does not conflict with FOR KEY SHARE.

The insert has to check that order 1 exists, so it takes a FOR KEY SHARE lock on that row and keeps it to the end of the transaction. Two key shares do not conflict, so both inserts pass. Then each FOR UPDATE needs a lock that conflicts with the other session’s key share. Each waits for the other. The conflict table is in the docs: FOR UPDATE conflicts with all four row modes, FOR NO KEY UPDATE with all but FOR KEY SHARE.

This is the log I got:

[136] xid=758 ERROR:  deadlock detected
[136] xid=758 DETAIL:  Process 136 waits for ShareLock on transaction 759; blocked by process 143.
	Process 143 waits for ShareLock on transaction 758; blocked by process 136.
	Process 136: SELECT id FROM orders WHERE id = 1 FOR UPDATE;
	Process 143: SELECT id FROM orders WHERE id = 1 FOR UPDATE;
[136] xid=758 CONTEXT:  while locking tuple (0,1) in relation "orders"

Two identical statements on one row, and neither blocks the other on its own. The INSERT that holds the key share is not in the log. Without it, you would think PostgreSQL has a bug.

There are two fixes. I ran both with two sessions and both finished:

-- Fix A: ask for the weaker lock. It does not conflict with a key share.
SELECT id FROM orders WHERE id = 1 FOR NO KEY UPDATE;

-- Fix B: take the parent lock first, before the insert.
BEGIN;
SELECT id FROM orders WHERE id = 1 FOR UPDATE;
INSERT INTO order_items (order_id, price) VALUES (1, 10);
COMMIT;

Fix A is smaller. Use FOR UPDATE only when you delete the row or change its key, because that is the only time you need it. Fix B is the “strongest lock first” rule from the docs, and it makes the two transactions queue on the parent row.

Shape 3: a batch statement

A single statement can deadlock with itself in another session, because it locks rows one at a time in the order it reads them. I used an upsert, with a pg_sleep in the WHERE to slow each row down so the overlap is easy to hit:

-- Session A: ids 1, 2                        -- Session B: ids 2, 1
INSERT INTO counters
SELECT x, 1 FROM unnest(ARRAY[1,2]) AS x
WHERE pg_sleep(1) IS NOT NULL
ON CONFLICT (id)
DO UPDATE SET hits = counters.hits + 1;
ERROR:  deadlock detected
DETAIL:  Process 186 waits for ShareLock on transaction 766; blocked by process 193.
Process 193 waits for ShareLock on transaction 765; blocked by process 186.
CONTEXT:  while inserting index tuple (0,2) in relation "counters"

Each batch holds the id it did first and wants the id the other did first. Real code has no pg_sleep, but it has the same shape: a worker that upserts a list of ids from a queue, and another worker with the same ids in a different order.

Batch upserts in different orders. Top: batch A writes id 1 then id 2, and batch B writes id 2 then id 1. A holds 1 and wants 2, B holds 2 and wants 1, so there is a deadlock. Bottom: both batches sorted by id. Both write id 1 first, so B waits for A at the first row and no circle can form.

Sort the rows. For an INSERT ... SELECT, add ORDER BY to the SELECT. For a VALUES list, sort it in code before you send it. I added ORDER BY x to both statements above and reran them. Both finished, and the table had hits = 2 for both ids.

UPDATE has no ORDER BY, so a bulk UPDATE ... WHERE locks rows in whatever order the plan reads them. To control the order, lock in a subquery:

UPDATE jobs SET state = 'done'
WHERE id IN (
  SELECT id FROM jobs
  WHERE state = 'pending' AND id <= 50
  ORDER BY id
  FOR UPDATE
);

EXPLAIN on PostgreSQL 17 shows a LockRows node inside the subquery, which is where the locks are taken, in the subquery’s order. Plans can change, so look at yours. If workers should split the work and not queue behind each other, FOR UPDATE SKIP LOCKED is the other tool. The job queue post builds on it.

Retry, as the last step

If you cannot be sure every path locks in the same order, catch 40P01 and run the whole transaction again. The docs say the same. A retry cannot save a path that does the wrong thing twice, so two rules apply:

  • Retry the whole transaction from BEGIN, not the one failed statement. The server already rolled everything back.
  • The transaction must be safe to run twice. If it sends an email or calls a payment API, the retry sends it twice. That is the problem idempotency keys solve, and the outbox pattern keeps side effects out of the transaction.

A wrapper in Python with psycopg 3:

import random, time
import psycopg
from psycopg import errors

def run_in_transaction(dsn, work, attempts=4):
    for attempt in range(1, attempts + 1):
        try:
            with psycopg.connect(dsn) as conn:  # commits on exit, rolls back on error
                work(conn)
            return
        except errors.DeadlockDetected:
            if attempt == attempts:
                raise
            time.sleep(random.uniform(0, 0.05 * 2 ** attempt))

I ran two opposite transfers through it in two threads. One got the deadlock error, retried, and both finished. The balances were right and the counter went up by one. The random wait matters: without it, two sessions that retry at the same moment can meet again. A real service would take the connection from a pool, not open a new one per attempt.

Keep the attempt count small. A retry is a second try, not a loop to hide a bug. If the metric deadlocks keeps climbing, the retry is hiding a lock order bug that you still need to fix.

Which fix should you use?

The fixes for a deadlock, in the order to try them. Step 1: lock rows in one fixed order, with ORDER BY id FOR NO KEY UPDATE. Step 2: take the weakest row lock that does the job, so FOR NO KEY UPDATE instead of FOR UPDATE. Step 3: keep transactions short, with no network calls inside. Step 4: retry the whole transaction on error 40P01, as a safety net. Raising deadlock_timeout is not a fix, it only delays the error.
What the log showsLikely shapeFix
Two UPDATEs on the same table, different idsOpposite orderORDER BY id FOR NO KEY UPDATE in every path
Two identical SELECT ... FOR UPDATE on a parent tableForeign key key shareFOR NO KEY UPDATE, or lock the parent first
One multi-row INSERT ... ON CONFLICT or UPDATE twiceBatch orderSort the rows, or lock in a sorted subquery
Different tables in each statementTables in opposite orderOne table order for every transaction

The docs say a higher deadlock_timeout reduces wasted checks but slows the report of real deadlocks, and suggest it should exceed your typical transaction time on a loaded server. It does not remove a deadlock. If you raise it, do it to cut checks, not to make the error rarer.

Questions people ask

What causes “ERROR: deadlock detected” in PostgreSQL? Two or more transactions each hold a lock the other wants, so none can go on. PostgreSQL finds the circle after deadlock_timeout and rolls one transaction back with error 40P01. The usual cause is the same rows, or the same tables, locked in a different order by two code paths.

How do I find which queries deadlocked? Read the server log, not the client error. The ERROR entry lists the statement each process was running when it began to wait. Turn on log_lock_waits, and put %p and %x in log_line_prefix so you can join lines. The earlier statements that took the locks are not logged, so look at the application’s own logs for that.

Which transaction does PostgreSQL abort? The docs say it is difficult to predict and should not be relied upon. In my runs it was the session that began waiting first. Write the retry so that either side can be the victim.

Can I turn deadlocks off? No, but you can make them rare. One lock order for every code path removes the common cases. Retry on 40P01 handles the rest. The docs call consistent lock order the best defence.

Is a deadlock the same as a lock timeout? No. A lock timeout (55P03) means a statement waited longer than lock_timeout for a lock that someone was still holding. A deadlock is a circle, and no amount of waiting would end it. The locks post covers the timeouts.

Cheat sheet

Deadlock detected cheat sheet. Error: 40P01, one transaction is rolled back. Read: the two DETAIL lines form a circle of two processes. Log: turn on log_lock_waits and put %p and %x in log_line_prefix. Missing: the earlier statements that took the locks. Order: ORDER BY id FOR NO KEY UPDATE in every code path. Foreign keys: inserts take FOR KEY SHARE on the parent, so use FOR NO KEY UPDATE. Batches: sort the rows before the upsert. Retry: the whole transaction, with a small random wait. Do not: raise deadlock_timeout.

Further reading

Written by Rafi Loom

Backend engineer who builds high-volume systems that move money. More about Rafi