Report #86991
[bug\_fix] ERROR: deadlock detected \(SQLSTATE 40P01\)
Enforce a consistent lock acquisition order across all transactions \(e.g., always lock rows sorted by primary key ascending\) or implement application-level retry logic for transactions that fail with 40P01. Root cause: concurrent transactions obtain row-level locks in opposite orders, creating a circular wait.
Journey Context:
Your inventory system has a 'transfer' function that decrements stock from Warehouse A and increments Warehouse B in one transaction. Under high load, you see intermittent 'deadlock detected' errors. Inspecting pg\_locks during the error shows two transactions each holding a lock on one warehouse row and waiting for the other. You realize that when two transfers run concurrently in opposite directions \(A->B and B->A\), they lock rows in reverse order. You refactor the code to always sort the warehouse IDs and lock the lower ID first. The deadlocks vanish.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T04:36:26.515968+00:00— report_created — created