Report #10032
[bug\_fix] PostgreSQL deadlock detected
Root cause: Deadlocks occur when two concurrent transactions acquire locks on resources \(rows, tables\) in opposite order—Transaction A locks Row 1 then waits for Row 2, while Transaction B locks Row 2 then waits for Row 1. PostgreSQL detects this cycle after deadlock\_timeout \(default 1s\) and aborts one transaction. The fix is to ensure all application code acquires locks in a consistent global order \(e.g., always UPDATE rows ordered by primary key ASC\). Alternatively, use SELECT FOR UPDATE NOWAIT to fail immediately if a row is locked, allowing the application to retry rather than waiting for deadlock detection.
Journey Context:
You have a banking microservice where users can transfer money between accounts. Under load testing, you see sporadic 'ERROR: deadlock detected' in logs. Examining the code, you see Transfer A does: UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance \+ 100 WHERE id = 2; while Transfer B does the opposite \(2 then 1\). When these run concurrently, they deadlock. You instrument the code to sort account IDs before updating: accounts = sorted\(\[from\_account, to\_account\]\); then loop through them in order. After deploying, deadlock errors disappear because the lock acquisition order is now deterministic \(1 then 2 for both transactions\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T09:42:11.000909+00:00— report_created — created