Report #85553
[bug\_fix] PostgreSQL: ERROR: deadlock detected
PostgreSQL automatically kills one transaction \(the victim\) to break the deadlock. The fix requires ensuring consistent lock acquisition order across the application \(e.g., always lock rows in primary key ascending order\), keeping transactions short to reduce lock windows, and implementing application-level retry logic with exponential backoff for SQLSTATE 40P01.
Journey Context:
The e-commerce checkout intermittently failed with 'ERROR: deadlock detected'. Investigation of pg\_locks and deadlock trace logs \(log\_lock\_waits = on\) revealed two concurrent transactions: TX1 locked inventory row ID=5 then tried to lock ID=10; TX2 locked ID=10 then tried to lock ID=5. The application logic processed refunds and orders in different code paths with no ordering guarantees. The immediate fix was to sort item IDs before acquiring row locks \(SELECT ... FOR UPDATE with ORDER BY id\). Additionally, a retry decorator was added to catch SQLSTATE 40P01 and retry 3 times with jitter. This eliminated the deadlocks entirely.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T02:11:17.912268+00:00— report_created — created