Skip to content

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

Key points

  • Deadlocks come from inconsistent lock order across transactions.
  • The log shows both queries involved.
  • Lock rows in a consistent order, and keep transactions short.
  • Retry the cancelled transaction in application code.

How a deadlock happens

sql
-- Transaction A                          -- Transaction B
BEGIN;                                     BEGIN;
UPDATE accounts SET ... WHERE id = 1;      UPDATE accounts SET ... WHERE id = 2;
UPDATE accounts SET ... WHERE id = 2;      UPDATE accounts SET ... WHERE id = 1;
-- waits for B                             -- waits for A  -> deadlock, one is cancelled

Reading the log

plaintext
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 UPDATE the 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 40P01 and retry the transaction a couple of times.
sql
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.

Retrying safely

python
from psycopg import errors

for attempt in range(3):
    try:
        with conn.transaction():
            transfer(conn, from_id, to_id, amount)
        break
    except errors.DeadlockDetected:
        if attempt == 2:
            raise
        time.sleep(0.05 * (2 ** attempt))   # short backoff, then retry the whole transaction

Frequently asked questions

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.

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.