Report #68763
[bug\_fix] ERROR: deadlock detected \(40P01\)
Catch the exception and retry the transaction. For prevention, ensure all transactions acquire locks on the same objects in the same order \(e.g., always lock rows in table A before table B\).
Journey Context:
A developer maintains a high-traffic e-commerce app and starts seeing intermittent 500 errors with 'deadlock detected'. Examining logs, they see two concurrent transactions: one updates inventory then orders, the other updates orders then inventory. This creates a circular wait condition. Initially, they try increasing lock\_timeout, but that only causes faster failures. After reading the PostgreSQL explicit locking documentation, they implement a retry loop with exponential backoff in their application code, catching the 40P01 error. For a permanent fix, they refactor the code to always update tables in alphabetical order \(inventory before orders\), eliminating the circular dependency and preventing deadlocks entirely.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T21:54:18.463752+00:00— report_created — created