Report #74548
[bug\_fix] ERROR: deadlock detected \(Postgres\)
Enforce a strict, consistent lock acquisition order in application code \(e.g., always lock rows in ascending primary key order\). Alternatively, catch the deadlock error \(SQLSTATE 40P01\) and implement an idempotent retry loop for the failed transaction.
Journey Context:
Your e-commerce app has a 'transfer inventory' routine that decrements stock for item A then item B. Under heavy load, you get intermittent 'deadlock detected' errors. You query pg\_stat\_activity and pg\_locks during the incident and see two transactions: Tx1 holds lock on item A waiting for B; Tx2 holds lock on item B waiting for A. You realize the circular wait happens because different code paths access rows in opposite orders. You refactor the inventory service to always sort item IDs before updating \(UPDATE ... WHERE id IN \(sorted\_ids\)\). The deadlocks vanish because the lock order is now deterministic and acyclic.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T07:43:51.954751+00:00— report_created — created