A request fails with ERROR: deadlock detected, the driver reports SQLSTATE 40P01, and the retry succeeds, so nobody looks further until it happens fifty times an hour. Two transactions were each waiting for a lock the other held, and PostgreSQL aborted one of them. The hard part is finding the code paths that formed the cycle, because the error names only process and transaction IDs, and the server log shows only each process's last statement. This guide covers reading the error and its log entry on PostgreSQL 16 to 19, the settings that make the log useful, the common patterns, and the fixes: consistent lock order, shorter transactions, NOWAIT or SKIP LOCKED, and a retry loop.
- SQLSTATE
40P01means PostgreSQL found a lock cycle and rolled back one transaction. Retry the whole transaction, not the last statement. - The deadlock check runs only after a lock wait reaches
deadlock_timeout(default1s), so a deadlock costs at least that long before the error. - The server log entry lists each process and its current statement only. Add
%a,%cand%xtolog_line_prefixso you can trace the earlier statements that took the locks. - Most deadlocks come from rows locked in different orders. Lock them in one order with
SELECT ... ORDER BY ... FOR UPDATE, and useFOR NO KEY UPDATEwhen you do not change keys. log_lock_waitsis on by default from PostgreSQL 19; turn it on yourself on 16, 17 and 18.
Scope and review date: November 2026. This post covers PostgreSQL 16, 17 and 18 (current minors 16.16, 17.12 and 18.7) and PostgreSQL 19.0, released on November 19, 2026. Error formats were checked against the PostgreSQL 18 source and settings against the PostgreSQL documentation. The SQL and code were not run in a lab, and all output shown is illustrative. Finding the session that blocks an ordinary lock wait is covered in PostgreSQL lock waits: how to find the blocking query; this post covers deadlocks only.
What does "ERROR: deadlock detected" mean in PostgreSQL?
A deadlock is a cycle of lock waits: transaction A waits for a lock held by B, and B waits for a lock held by A. Neither can finish, so PostgreSQL aborts one of them. The documentation notes that which transaction is aborted "is difficult to predict and should not be relied upon". The aborted transaction gets the condition deadlock_detected, SQLSTATE 40P01, in class 40, transaction rollback, the same class as serialization failures (40001).
The classic example from the documentation is two transfers between the same pair of accounts that update the rows in opposite orders:
-- Session 1
BEGIN;
UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 11111;
-- Session 2
BEGIN;
UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 22222;
UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 11111; -- waits for session 1
-- Session 1
UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 22222; -- waits for session 2: cycleInterpretation: each session holds a row lock the other needs. About one second after the last statement starts waiting, one session receives the error and its whole transaction is rolled back; the other proceeds. The client sees the message, a DETAIL line per process in the cycle, the hint "See server log for query details." and a CONTEXT line such as while updating tuple (0,2) in relation "accounts".
Each DETAIL line reads Process N waits for MODE on OBJECT; blocked by process M. (format from deadlock.c). The object names the lock type:
ShareLock on transaction 918204: a row lock. Row locks live on disk, so a waiter waits on the holder's transaction ID (pg_locks).relation 16402 of database 16384: a table-level lock, usually fromLOCK TABLEor DDL.advisory lock [...]: an application-defined advisory lock.
The CONTEXT line names the operation and table: while updating tuple, while locking tuple for SELECT ... FOR UPDATE, or while checking uniqueness of tuple for concurrent inserts of one unique key. Resolve relation OIDs with SELECT 16402::regclass;.
How does PostgreSQL detect a deadlock, and what does deadlock_timeout do?
PostgreSQL does not check for cycles on every lock wait, because the check is expensive. A waiting backend sleeps for deadlock_timeout, which defaults to 1s, and only then runs the deadlock check. If it finds a cycle that it cannot resolve by reordering the wait queue, it raises the error in its own transaction. With no cycle, it keeps waiting.
So every deadlock costs at least deadlock_timeout of waiting, and the same timer controls log_lock_waits, which logs any wait longer than it. On busy servers the documentation suggests a value above your typical transaction time. Do not tune it to make deadlocks fail faster; fix the lock order.
SHOW deadlock_timeout; -- 1s by default
SHOW log_lock_waits; -- off on 16, 17 and 18; on by default from 19
SHOW log_min_error_statement; -- error by default, so the failing statement is logged
-- Turn on lock-wait logging (superuser, or a role granted SET on the parameter)
ALTER SYSTEM SET log_lock_waits = on;
SELECT pg_reload_conf();Interpretation: both settings need a superuser or a role with SET privilege on them. On managed services, use the parameter group instead of ALTER SYSTEM.
From lock wait to deadlock error
The check runs once, after deadlock_timeout; most waits end before it
Cost: a deadlocked request always waits at least deadlock_timeout before it fails, and then has to be retried from the start.
How do I read the deadlock entry in the PostgreSQL server log?
The client gets the cycle but not the queries; the hint says "See server log for query details." The server log gets the same DETAIL lines plus one Process N: statement line per process in the cycle. With log_lock_waits on, the losing backend also logs a detected deadlock while waiting line first.
A deadlock in the server log with log_lock_waits on
Illustrative output; line formats from the PostgreSQL 18 source, prefix '%m [%p] %a xid=%x '
What is missing: the statements that took the locks first. Each "Process N:" line is that backend's current statement only (proc.c and deadlock.c).
Read it in three passes: the LOG line names the loser and its wait; the DETAIL lines give the cycle, PID by PID, with the lock type on each edge; the Process N: lines give the statement each process was waiting in. The winner's statement (41907) completes once the loser rolls back.
Check whether it is a one-off or a trend:
SELECT datname, deadlocks, xact_rollback, stats_reset
FROM pg_stat_database
WHERE datname = current_database();Interpretation: deadlocks is the number of deadlocks detected in the database since stats_reset. Sample it every few minutes in your monitoring and alert on the rate, not the total.
Why does the log show only the final statement of each transaction?
The report prints the statement each backend is running when the check fires. Session 1 locked row 11111 with an earlier UPDATE that had already finished, so the log shows only half the story. In real applications the first lock often comes from another code path, a trigger, or a foreign key check. To rebuild the transaction, log the earlier statements and make them joinable:
log_line_prefixwith%p(process ID),%c(session ID),%x(transaction ID, 0 if none) and%a(application_name). The default is only'%m [%p] '.log_statement = 'mod', which logs DDL and data-modifying statements such asINSERT,UPDATEandDELETE. It does not log plainSELECT ... FOR UPDATE.log_min_duration_statement, which logs statements slower than a threshold. A0logs everything, which is usually too much for a busy primary.
# postgresql.conf (or the parameter group on a managed service)
log_line_prefix = '%m [%p] %q%a %u@%d xid=%x session=%c '
log_lock_waits = on
log_statement = 'mod' # temporary, while you trace the cycle
log_min_duration_statement = 250ms # catches slow SELECT ... FOR UPDATEInterpretation: grep for the two PIDs or session IDs and read backwards to each BEGIN. %x matches the transaction numbers in the DETAIL lines. log_statement = 'mod' is noisy, so turn it off after a few captures. Set application_name in each service's connection string: it appears in %a and pg_stat_activity and turns "process 41907" into "the billing worker".
Which patterns cause most PostgreSQL deadlocks?
Most deadlocks are one of these five shapes. Identify yours from the log before you change code.
Rows updated in different orders
The accounts example, or a batch job and an API touching the same rows in different orders. A multi-row UPDATE ... WHERE id IN (...) locks rows in plan order, not list order, so overlapping batches can collide too.
Foreign key checks that take FOR KEY SHARE
Inserting or updating a child row makes PostgreSQL run an internal check against the parent table. In the source it is SELECT 1 FROM ONLY parent x WHERE id = $1 FOR KEY SHARE OF x. That lock blocks DELETE, key-changing updates and SELECT ... FOR UPDATE on the parent row, so the parent row is locked by a statement that never names it:
-- Session A
BEGIN;
INSERT INTO orders (customer_id, total) VALUES (1, 50); -- FOR KEY SHARE on customer 1
-- Session B
BEGIN;
INSERT INTO orders (customer_id, total) VALUES (2, 75); -- FOR KEY SHARE on customer 2
-- Session A
SELECT * FROM customers WHERE id = 2 FOR UPDATE; -- waits for B
-- Session B
SELECT * FROM customers WHERE id = 1 FOR UPDATE; -- waits for A: deadlockInterpretation: if the code only changes non-key columns of the customer, it should lock with FOR NO KEY UPDATE. According to the row-lock documentation, that mode does not conflict with FOR KEY SHARE, and a plain UPDATE of non-key columns already takes it. Both locks are then compatible and this cycle cannot form.
SELECT ... FOR UPDATE without a stable order
Two workers run SELECT ... WHERE status = 'pending' FOR UPDATE over overlapping rows. Without ORDER BY, each locks rows in the order its plan returns them, and that order can differ between queries and plans.
LOCK TABLE in a weak mode, then a write
From the LOCK documentation: two transactions take SHARE mode, then both write, which needs ROW EXCLUSIVE, and each SHARE lock blocks the other's write:
BEGIN;
LOCK TABLE inventory IN SHARE MODE; -- both sessions get this
UPDATE inventory SET qty = qty - 1 WHERE sku = 'A-100'; -- needs ROW EXCLUSIVE: deadlock
-- Fix: take the most restrictive mode you will need, first
BEGIN;
LOCK TABLE inventory IN SHARE ROW EXCLUSIVE MODE; -- self-exclusive: one writer at a time
UPDATE inventory SET qty = qty - 1 WHERE sku = 'A-100';
COMMIT;Interpretation: the report names relation ... objects. The docs' rule: lock objects in the same order everywhere, and take the most restrictive mode first.
Advisory locks taken in different orders
Advisory locks live in the same lock manager, so they deadlock like anything else. The report shows them as advisory lock [...]:
-- Worker 1 -- Worker 2
SELECT pg_advisory_xact_lock(1001); SELECT pg_advisory_xact_lock(1002);
SELECT pg_advisory_xact_lock(1002); SELECT pg_advisory_xact_lock(1001); -- deadlock
-- Fix: always take keys in ascending order, or use the try form
SELECT pg_try_advisory_xact_lock(1002); -- returns false instead of waitingInterpretation: the ordering rule is yours to enforce. Session-level advisory locks outlive transactions, so they can join a cycle long after the code that took them returned; see advisory locks: patterns and pitfalls.
How do I fix deadlocks with a consistent lock order?
The documentation calls a consistent lock order "the best defense against deadlocks". In practice that means locking every row the transaction will touch, up front, in one sorted order, before making changes. ORDER BY in a SELECT ... FOR UPDATE does this: the SELECT documentation explains that the sort is applied first and the rows are then locked as they are returned.
BEGIN;
-- 1. Lock both rows in key order, whatever the direction of the transfer
SELECT acctnum
FROM accounts
WHERE acctnum IN (22222, 11111)
ORDER BY acctnum
FOR NO KEY UPDATE;
-- 2. Now make the changes; the locks are already held
UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 22222;
UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 11111;
COMMIT;Interpretation: concurrent transfers now both lock 11111 first; the second waits holding nothing the first needs, so there is a wait but no cycle. FOR NO KEY UPDATE suffices because balance is not a key column, and it does not block foreign key checks. For batches, sort input by primary key, or lock with an ordered SELECT ... FOR UPDATE before a set-based update. The docs warn that under READ COMMITTED such a query can return rows out of order if a sort column changed while it waited; ordering by an unchanging primary key avoids that.
The same transfer, deadlock-prone and ordered
Switch tabs to see what changes when locks are taken in key order
Lock as you go
| Aspect | Behaviour |
|---|---|
| First lock taken | The source account, which depends on transfer direction |
| Lock order across sessions | Differs between A to B and B to A transfers |
| Row lock mode | FOR NO KEY UPDATE, taken implicitly by each UPDATE |
| Concurrent opposite transfers | Can form a cycle; one gets 40P01 after deadlock_timeout |
| Retry still needed | Yes, often |
Lock in key order first
| Aspect | Behaviour |
|---|---|
| First lock taken | The lower account number, always |
| Lock order across sessions | Identical: ORDER BY acctnum |
| Row lock mode | FOR NO KEY UPDATE, taken explicitly before any change |
| Concurrent opposite transfers | The second waits at the first lock; no cycle |
| Retry still needed | Yes, as a safety net for other code paths |
Rule: every code path that touches the same rows must use the same order. One path that still locks as it goes is enough to bring the deadlocks back.
How do shorter transactions, NOWAIT and SKIP LOCKED reduce deadlocks?
The longer transactions hold locks, the wider the window for a cycle. Keep network calls and user think time outside the transaction and commit as soon as the writes are done; PostgreSQL 17's transaction_timeout caps the worst case. For work queues, use SKIP LOCKED: workers take only rows nobody else has locked. The docs note it gives an inconsistent view of the data, fine for a queue and wrong for general reads.
-- Queue consumer: claim up to 10 jobs nobody else holds
BEGIN;
SELECT id, payload
FROM jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 10
FOR UPDATE SKIP LOCKED;
-- process, then:
UPDATE jobs SET status = 'done' WHERE id = ANY($1);
COMMIT;Interpretation: with LIMIT, locking stops once enough rows are returned. NOWAIT is stricter: a locked row makes the statement fail at once with lock_not_available (SQLSTATE 55P03), so no cycle can form through it, and the application retries later.
-- Fail fast instead of queueing behind another writer
SELECT * FROM customers WHERE id = 42 FOR NO KEY UPDATE NOWAIT;
-- Or bound every lock wait in this transaction
SET LOCAL lock_timeout = '2s';
-- PostgreSQL 18 and later: log why a NOWAIT lock failed
ALTER SYSTEM SET log_lock_failures = on;
SELECT pg_reload_conf();Interpretation: lock_timeout cancels a statement that waits longer than the limit, also with SQLSTATE 55P03. If every transaction in a cycle uses a lock_timeout shorter than deadlock_timeout, a waiter is cancelled before the deadlock check runs, so you see lock timeouts instead of deadlock errors. That is acceptable if your retry handles both codes. log_lock_failures, added in PostgreSQL 18, currently logs only SELECT ... NOWAIT failures.
How do I retry a transaction after a deadlock?
Some deadlocks survive careful ordering: a forgotten trigger, a new code path, a migration. The documentation's fallback is to retry. Three rules make that safe:
- Retry the whole transaction from
BEGIN; after a 40P01 every statement in it is rolled back. - Retry only on
40P01and40001, with a short random back-off. - Cap the attempts and log each retry, so retries show in monitoring instead of hiding a growing problem.
import logging
import random
import time
import psycopg
from psycopg import errors
log = logging.getLogger(__name__)
RETRYABLE = (errors.DeadlockDetected, errors.SerializationFailure) # 40P01, 40001
def transfer(conn: psycopg.Connection, src: int, dst: int, amount, attempts: int = 5):
for attempt in range(1, attempts + 1):
try:
with conn.cursor() as cur:
# Lock both rows in key order before changing anything
cur.execute(
"SELECT acctnum FROM accounts WHERE acctnum = ANY(%s) "
"ORDER BY acctnum FOR NO KEY UPDATE",
([src, dst],),
)
cur.execute(
"UPDATE accounts SET balance = balance - %s WHERE acctnum = %s",
(amount, src),
)
cur.execute(
"UPDATE accounts SET balance = balance + %s WHERE acctnum = %s",
(amount, dst),
)
conn.commit()
return
except RETRYABLE as exc:
conn.rollback()
log.warning("retry %s after %s", attempt, exc.sqlstate)
if attempt == attempts:
raise
time.sleep(random.uniform(0, min(1.0, 0.05 * 2 ** attempt)))Interpretation: psycopg 3 maps 40P01 to errors.DeadlockDetected and 40001 to errors.SerializationFailure; other drivers expose the same SQLSTATE. The body must be safe to run twice, so keep emails and payment calls out of it.
How do I investigate a deadlock while it is happening?
Usually you cannot: a cycle is broken about deadlock_timeout after it forms. What you can catch live are the long lock chains that make deadlocks likely. pg_blocking_pids() returns the PIDs blocking a backend, and pg_locks shows what each waits for:
SELECT w.pid AS waiting_pid,
a.application_name,
w.locktype, w.mode, w.transactionid, w.relation::regclass,
now() - w.waitstart AS waited,
pg_blocking_pids(w.pid) AS blocked_by,
left(a.query, 80) AS waiting_query
FROM pg_locks w
JOIN pg_stat_activity a ON a.pid = w.pid
WHERE NOT w.granted
ORDER BY w.waitstart;Interpretation: two PIDs that appear in each other's blocked_by are a cycle not yet checked. Row-lock waits usually show as transactionid with ShareLock, as in the DETAIL lines. The documentation warns that frequent pg_blocking_pids() calls can affect performance. Blocking trees and cancel versus terminate are in the lock waits guide.
What changed for deadlocks in PostgreSQL 16, 17, 18 and 19?
None of these release notes lists a change to deadlock detection or the error format; the changes are in the tooling around it. From the release notes for 17, 18 and 19:
| Version | Change relevant to deadlock work |
|---|---|
| 16 | No deadlock-specific changes; log_lock_waits is off by default |
| 17 | transaction_timeout caps the length of a transaction |
| 18 | log_lock_failures logs SELECT ... NOWAIT lock failures (off by default) |
| 19 | log_lock_waits is on by default; new pg_stat_lock view counts lock waits per lock type; max_locks_per_transaction default raised from 64 to 128 |
On PostgreSQL 19, check whether your configuration management sets log_lock_waits = off explicitly; an old template would hide the new default. pg_stat_lock does not count deadlocks; keep using pg_stat_database.deadlocks for that.
Frequently asked questions
What is SQLSTATE 40P01 in PostgreSQL?
SQLSTATE 40P01 is the deadlock_detected error. PostgreSQL found transactions waiting on each other's locks in a cycle and aborted one, rolling it back in full so the others could continue. Retry the whole transaction, then fix the lock order that caused the cycle.
Should I increase deadlock_timeout to reduce deadlocks?
No. deadlock_timeout only sets how long a waiting backend sleeps before checking for a cycle. Raising it makes real deadlocks take longer to fail; it does not prevent them. The documentation suggests raising it on busy servers, ideally above your typical transaction time, so fewer harmless waits pay for the check.
Why does the PostgreSQL deadlock log not show the query that took the first lock?
The report prints each backend's current statement, the one that is waiting. The statement that took the conflicting lock earlier has already finished. Log statements with log_statement = 'mod' or log_min_duration_statement, and add %x, %c and %a to log_line_prefix to join them to the deadlock entry.
Can foreign keys cause deadlocks in PostgreSQL?
Yes. Inserting a child row runs an internal SELECT ... FOR KEY SHARE on the parent row, which conflicts with DELETE, key-changing updates and SELECT ... FOR UPDATE on that parent. Two transactions that insert children and then lock each other's parents can deadlock. Lock parents with FOR NO KEY UPDATE when keys do not change.
Key takeaways
- 40P01 means a lock cycle; PostgreSQL detects it after
deadlock_timeoutand rolls back one transaction, chosen unpredictably. - The server log adds each process's current statement, never the earlier ones that took the locks; log those and join them with
%x,%cand%a. - Most deadlocks come from inconsistent ordering: rows, foreign key parents, unordered
FOR UPDATE, weakLOCK TABLEmodes, or advisory keys. - Fix the order with
ORDER BY ... FOR NO KEY UPDATEup front, keep transactions short, and useSKIP LOCKEDorNOWAITfor queues. - Keep a capped, jittered retry on 40P01 and 40001, and alert on the rate of
pg_stat_database.deadlocks.
Trace and fix PostgreSQL deadlocks with JusDB
JusDB's PostgreSQL performance tuning team can review your deadlock and lock wait logs, set up logging that captures the full transactions behind a cycle, and help you change lock ordering, transaction scope and retry handling in the code paths involved.
Bring your PostgreSQL version, a few deadlock entries from the server log and the application_name of each service. Your team approves every production change.