Report #12935
[bug\_fix] ERROR: deadlock detected
PostgreSQL automatically detects deadlocks and kills the 'victim' transaction, but this is a symptom. The root cause is inconsistent lock ordering: Transaction A locks resource 1 then tries to lock 2, while Transaction B locks 2 then tries to lock 1. The fix is to enforce a consistent global lock ordering \(e.g., always lock rows in ascending primary key order\) or to reduce transaction scope to minimize lock hold time. Additionally, implement application-level retry logic with exponential backoff for SQLSTATE 40P01.
Journey Context:
Your e-commerce checkout system starts throwing intermittent 500 errors with 'deadlock detected' during high-traffic sales. You analyze the code: \`UPDATE inventory SET count = count - 1 WHERE sku = ?\` and \`UPDATE orders SET status = 'paid' WHERE id = ?\` are in the same transaction, but the SKU order varies per cart. You reproduce it: Session 1 updates SKU 'A' then 'B'; Session 2 updates 'B' then 'A'. They deadlock. You refactor the checkout to sort SKUs before updating, ensuring all transactions lock rows in the same order. You also add a retry loop in the service layer to catch the error and retry. The deadlocks vanish.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T17:20:04.730310+00:00— report_created — created2026-06-16T17:46:27.742406+00:00— confirmed_via_duplicate_submission — confirmed