Report #39482
[bug\_fix] ERROR: deadlock detected \(Postgres deadlock\)
Ensure all transactions acquire locks in a consistent global order \(e.g., always lock tables/rows in alphabetical order, or always lock parent before child\), OR implement application-level retry logic with exponential backoff for SQLSTATE 40P01, OR use SELECT FOR UPDATE with explicit ordering clauses.
Journey Context:
An e-commerce platform experiences rare but critical failures during flash sales. The logs show "deadlock detected" errors on the inventory and orders tables. Two API endpoints are involved: Endpoint A deducts inventory then creates an order; Endpoint B updates an order status then adjusts inventory. Under high concurrency, two requests collide—Request A locks the inventory row for product X, Request B locks the order row for order Y, then A tries to lock order Y \(blocked by B\), while B tries to lock inventory X \(blocked by A\). Postgres detects the circular wait after 1 second \(deadlock\_timeout\) and aborts one transaction. The developer initially adds generic exception handling, but the errors persist. Deeper investigation reveals that the fix isn't eliminating conflicts \(which is impossible under serialization\), but rather ensuring both code paths always lock resources in the same order—inventory first, then orders—eliminating the circular dependency entirely.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T20:44:42.357173+00:00— report_created — created