Report #43841
[bug\_fix] ERROR: deadlock detected \(SQLSTATE 40P01\)
Reorder all transactions to acquire row locks in a consistent global order \(e.g., sort primary keys before updating\), and eliminate long-running transactions that hold locks while waiting for external I/O. Root cause: Deadlocks occur when two concurrent transactions each hold a lock on a resource the other needs, creating a circular wait. Without a consistent lock ordering protocol, the probability of deadlock increases quadratically with concurrency.
Journey Context:
Your Python e-commerce platform starts throwing 500 errors during flash sales. The logs show 'deadlock detected' on 'UPDATE inventory SET count = count - 1 WHERE sku = 12345'. You add generic retry logic with exponential backoff, but the deadlocks happen so frequently \(20% of requests\) that retries just cascade into latency spikes. You analyze pg\_stat\_activity during the incident and see two PIDs: PID 100 holds a lock on SKU 'A' and is waiting on SKU 'B'; PID 200 holds SKU 'B' and waits on SKU 'A'. You realize your checkout code loops through the cart items in the order they were added to the cart, so different checkouts have different lock orders. You refactor the inventory decrement to first 'SELECT sku FROM inventory WHERE sku IN \(...\) ORDER BY sku FOR UPDATE', which sorts the lock acquisition, then performs the updates. The deadlocks vanish completely.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T04:03:26.372935+00:00— report_created — created