Report #5789
[bug\_fix] ERROR: deadlock detected \(PostgreSQL transaction deadlock\)
Root cause is concurrent transactions acquiring row-level locks in opposite orders, creating a circular wait \(e.g., Transaction A updates row 1 then row 2, while Transaction B updates row 2 then row 1\). PostgreSQL's deadlock detector kills one transaction to break the cycle. The fix is to implement a consistent ordering strategy for all transactions that modify multiple rows \(e.g., always update rows ordered by primary key ascending\), or implement application-level retry logic with exponential backoff specifically for SQLSTATE 40P01 deadlock errors.
Journey Context:
An e-commerce application experiences intermittent 500 errors during high-traffic flash sales when multiple users try to update inventory simultaneously. The PostgreSQL logs show 'ERROR: deadlock detected' with SQLSTATE 40P01, and the detail message indicates 'Process 12345 waits for ShareLock on transaction 67890; blocked by process 54321.' Analyzing the query logs reveals two concurrent transactions: one updating SKU-A then SKU-B, and another updating SKU-B then SKU-A. The team initially suspects missing indexes, but the query plans show index usage. Realizing the inventory update logic processes items in the order added to the cart \(which varies by user\), they implement a consistent ordering strategy: all inventory updates now sort the SKU list alphabetically before executing the UPDATE statements. This eliminates the circular wait condition. They also add a retry decorator with exponential backoff for SQLSTATE 40P01 to handle any remaining edge cases during extreme concurrency.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T22:12:12.176449+00:00— report_created — created