Report #24440
[bug\_fix] ERROR: deadlock detected \(PostgreSQL deadlock detection timeout\)
Ensure all transactions acquire row locks in a consistent global order \(e.g., ORDER BY primary key ascending\) so that concurrent transactions cannot form circular wait dependencies; implement application-level retry logic for deadlock victims as a safety net for unavoidable edge cases.
Journey Context:
E-commerce platform experiences intermittent 500 errors during flash sales. Logs show 'ERROR: deadlock detected' with 'DETAIL: Process 1234 waits for ShareLock on transaction 456; blocked by process 5678.' Investigation reveals two concurrent inventory update transactions: Transaction A updates product\_id 1, then attempts to update product\_id 2. Transaction B updates product\_id 2, then attempts to update product\_id 1. Under high concurrency, they enter a circular wait \(A holds lock on 1, waits for 2; B holds lock on 2, waits for 1\). PostgreSQL's deadlock detector kills one transaction after 1 second, but this causes user-facing failures. Developer initially tries increasing deadlock\_timeout, but this only delays the problem. Realizes the fix requires eliminating the circular wait possibility by enforcing lock order. Refactors inventory update code to always sort product IDs before updating: UPDATE inventory SET ... WHERE product\_id IN \(1,2\) ORDER BY product\_id FOR UPDATE. Now both transactions acquire locks in the same order \(1, then 2\), preventing circular waits.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T19:25:41.219692+00:00— report_created — created