Report #12319
[bug\_fix] ERROR: deadlock detected \(SQLSTATE 40P01\)
Implement an application-level retry loop with exponential backoff specifically for 40P01 errors, and refactor SQL statements to acquire locks in a consistent global order \(e.g., alphabetically by table name\) to prevent circular wait conditions.
Journey Context:
High-traffic e-commerce site using PostgreSQL. During flash sales with 1000\+ concurrent checkouts, logs showed sporadic 'deadlock detected' errors. Analyzing two competing transactions: T1 updated inventory \(locks inventory row\) then inserted an order \(needs order lock\); T2 updated order status \(locks order\) then adjusted inventory \(needs inventory lock\). When timing aligned perfectly, T1 held inventory waiting for order, while T2 held order waiting for inventory - a classic circular wait. Postgres detected this and aborted T2 with 40P01. The immediate fix was adding a try/catch block in the application code to catch the specific deadlock error code and retry the entire transaction from the beginning. The long-term fix was refactoring the code to always acquire locks in the same order: update inventory first, then orders, regardless of business logic flow, preventing the circular dependency.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T15:42:56.620322+00:00— report_created — created