Report #38832
[bug\_fix] ERROR: deadlock detected \(SQLSTATE 40P01\)
Modify application code to always acquire locks in a consistent, global order \(e.g., alphabetically by table name, or by ID\). If transaction A updates row 1 then row 2, and transaction B updates row 2 then row 1, they deadlock; reversing B to match A's order prevents the cycle. Alternatively, reduce transaction granularity so locks are held for shorter periods, or use SELECT FOR UPDATE with NOWAIT to fail fast on contention rather than waiting. The root cause is a circular wait condition where each process holds a resource the other needs.
Journey Context:
A developer has a billing system where one background job transfers credits between accounts: it debits Account A then credits Account B. Another job handles refunds by locking Account B then Account A. Under concurrent load, Postgres logs 'ERROR: deadlock detected' and kills one transaction. The developer analyzes pg\_stat\_activity and pg\_locks, seeing two processes each holding a ExclusiveLock on a row the other is waiting for. They realize the lock order is inconsistent. They refactor both code paths to always lock the account with the lower UUID first. After deployment, deadlocks cease.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T19:39:21.038858+00:00— report_created — created