Report #47271
[bug\_fix] ERROR: deadlock detected \(SQLSTATE 40P01\)
Ensure all transactions acquire row locks in a consistent global order \(e.g., ORDER BY primary\_key ASC\), or implement automatic retry logic with exponential backoff for 40P01 errors. Avoid long-running transactions holding locks while waiting for user input.
Journey Context:
Your e-commerce app randomly throws ERROR: deadlock detected during checkout spikes. The stack trace points to two different workers updating inventory. You analyze pg\_locks during the incident and see two transactions: TX1 holds RowLock on SKU=123 and waits for SKU=456; TX2 holds RowLock on SKU=456 and waits for SKU=123—a classic circular wait. You realize Worker A processes cart items in insertion order while Worker B processes by price descending. You refactor the inventory deduction to always UPDATE inventory SET count = count - 1 WHERE sku IN \(?,?\) ORDER BY sku ASC, forcing a global lock order. The deadlocks vanish immediately because the lock acquisition order is deterministic, preventing circular wait conditions required for deadlocks.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T09:49:40.046356+00:00— report_created — created