Report #14489
[bug\_fix] ERROR: deadlock detected \(40P01\)
Ensure all application code paths acquire row locks in a consistent global order \(e.g., SELECT ... ORDER BY id FOR UPDATE\), or catch 40P01 exceptions and retry the entire transaction.
Journey Context:
E-commerce checkout sporadically failed with 'deadlock detected' under high concurrency. Analysis of pg\_stat\_activity during incidents showed two transactions: one updated inventory for product A then B, while another updated B then A. Each held the lock the other needed, creating a circular wait. The fix involved refactoring all inventory deduction code to always sort product IDs before acquiring locks \(ORDER BY id FOR UPDATE\), ensuring all transactions acquire resources in the same sequence, eliminating the circular dependency. Additionally, implemented a retry decorator for 40P01 errors 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-16T21:43:39.033165+00:00— report_created — created