Report #7611
[bug\_fix] Postgres ERROR: deadlock detected
Implement consistent lock ordering \(e.g., alphabetical by table name\) across all transactions that modify multiple tables, and add application-level retry logic with exponential backoff specifically for SQLSTATE 40P01. Root cause is circular wait where Transaction A holds Lock 1 and waits for Lock 2, while Transaction B holds Lock 2 and waits for Lock 1; consistent ordering prevents the circle.
Journey Context:
During a high-volume flash sale, the e-commerce platform began logging 'deadlock detected' errors in the payment service. The error messages showed Process 12345 waits for ShareLock on transaction 67890; Process 67890 waits for ShareLock on transaction 12345. Developers analyzed the code: the checkout transaction updated the inventory table first, then the user\_balances table. Meanwhile, a background job processing refunds updated user\_balances first, then inventory. Under concurrency, these crossed like an X. They queried pg\_locks and pg\_stat\_activity to confirm the pattern. The fix required two changes: first, they refactored all transactions to acquire locks in alphabetical order \(inventory before user\_balances\), eliminating the circular dependency. Second, they wrapped transaction execution in a retry loop that caught 40P01 errors and retried with jitter, ensuring transient deadlocks didn't fail user requests.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T03:15:53.839286+00:00— report_created — created