Report #87729
[bug\_fix] ERROR: deadlock detected \(Postgres deadlock detection termination\)
Implement idempotent retry logic with exponential backoff specifically for SQLSTATE 40P01 \(deadlock\_detected\), and refactor transaction logic to acquire row locks in a consistent global order \(e.g., always lock table A before table B, or sort row IDs before locking\) to eliminate the circular wait condition.
Journey Context:
Under high concurrency, your e-commerce checkout intermittently fails with 'deadlock detected'. You analyze pg\_stat\_activity and logs to find two concurrent transactions: T1 updates inventory for product X then Y, while T2 updates Y then X. They each hold a lock the other needs. You initially add a naive retry loop, but it masks the issue and still fails under extreme load. You then refactor the inventory service to always sort product IDs before acquiring locks, ensuring global ordering. The deadlocks vanish entirely, and you keep the retry logic as a safety net for edge cases.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T05:50:26.014406+00:00— report_created — created