Report #68997
[bug\_fix] ERROR: deadlock detected \(SQLSTATE 40P01\)
Enforce a strict global lock acquisition order in application code \(e.g., always update rows ordered by primary key ascending\). Alternatively, implement application-level retry logic with exponential backoff specifically for SQLSTATE 40P01. Root cause: Concurrent transactions acquire exclusive locks on resources in opposite orders \(A locks row 1 then 2, B locks row 2 then 1\), creating a circular wait that Postgres detects and breaks by aborting one transaction.
Journey Context:
A high-throughput inventory system processes orders. Transaction 1 deducts stock for Item-A then Item-B. Transaction 2 does the opposite order. Under load, logs fill with ERROR: deadlock detected. The developer initially blames Postgres and tries lowering isolation levels, which doesn't help. After analyzing pg\_locks during the error, they see two PIDs each holding a tuple lock the other wants. Realizing it's an application logic issue, they refactor the inventory update function to sort item IDs before executing UPDATE statements. The deadlocks vanish completely without needing retries.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T22:17:44.753864+00:00— report_created — created