Error explained
PostgreSQL: deadlock detected
Two transactions each hold a lock the other needs. PostgreSQL detects the cycle, cancels one of them, and returns this error.
3 min read9 sectionsUpdated
On this page
ERROR: deadlock detected
DETAIL: Process 4120 waits for ShareLock on transaction 99812; blocked by process 4133.
Process 4133 waits for ShareLock on transaction 99811; blocked by process 4120.
Process 4120: UPDATE accounts SET balance = balance - 10 WHERE id = 2
Process 4133: UPDATE accounts SET balance = balance + 10 WHERE id = 1
HINT: See server log for query details.Fixes
- Consistent order: always lock or update rows in the same order, for example by ascending id.
- Lock up front:
SELECT ... FOR UPDATEthe rows you will change, in order, at the start of the transaction. - Short transactions: no external calls or user waits inside a transaction.
- Index foreign keys: unindexed foreign keys make updates and deletes lock more than needed.
- Retry: deadlocks can still happen; catch SQLSTATE
40P01and retry the transaction a couple of times.
BEGIN;
SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;Catching it in production
Deadlocks show as errors with SQLSTATE 40P01 on specific endpoints, often under load. Group them in error tracking and check pg_stat_database.deadlocks for the trend.
VitalRix error tracking groups exceptions recorded on OpenTelemetry spans into issues with counts, first and last seen, affected endpoints and versions, and marks an issue as regressed if it comes back after being resolved. Alert rules on error rate per service or endpoint route the problem to the right team before customers report it.
Can I turn off deadlock detection?
No, and you would not want to: without it both transactions wait forever. deadlock_timeout only controls how soon PostgreSQL checks.
Are deadlocks a sign of a bug?
Occasional ones under heavy concurrency can be normal if you retry. Frequent ones mean lock ordering or transaction design should change.
Related reading
- PostgreSQL idle in transaction: find and fix it: Find and fix PostgreSQL idle in transaction sessions: why they block vacuum and hold locks, which application patterns cause them and which timeout to set.
- PostgreSQL replication lag: causes and how to fix it: Diagnose PostgreSQL replication lag: use pg_stat_replication to tell send, write and replay delays apart, and fix slow replicas, long queries and WAL pile-ups.
- PostgreSQL "too many clients already": how to fix it: Fix PostgreSQL FATAL: sorry, too many clients already. See who holds connections, stop leaks, add PgBouncer and size max_connections the right way.
- PostgreSQL high CPU usage: how to find the cause: Diagnose PostgreSQL high CPU: use pg_stat_statements to rank queries by total time, spot missing indexes and stale statistics, and read EXPLAIN properly.
- PostgreSQL table bloat: how to find and remove it: Find and remove PostgreSQL table bloat: how dead tuples build up, autovacuum tuning for busy tables, when pg_repack beats VACUUM FULL, and what blocks cleanup.
- PostgreSQL connection refused: how to fix it: Fix PostgreSQL connection refused on port 5432: server not running, listen_addresses, pg_hba.conf, Docker hostnames and firewalls, with commands for every case.
Watch your own site and services with VitalRix
Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.