Report #6742
[bug\_fix] ERROR: deadlock detected
Restructure application logic to always acquire locks on resources \(tables/rows\) in a consistent global order \(e.g., alphabetically by table name, or by resource ID\). Alternatively, implement an application-level retry mechanism that catches the 40P01 SQLSTATE error code and retries the transaction with exponential backoff up to a maximum limit.
Journey Context:
Your e-commerce checkout flow randomly throws ERROR: deadlock detected during high-traffic sales. You analyze pg\_stat\_statements and find two concurrent transactions: Tx1 updates inventory \(row A\) then inserts into orders \(row B\), while Tx2 inserts into orders \(row B\) then updates inventory \(row A\). When they interleave, each holds a lock the other needs. You instrument logs to capture lock acquisition order and realize the application service layer allows different API endpoints to trigger SQL in arbitrary orders. You enforce a strict rule: all inventory-affecting transactions must lock the inventory row first \(using SELECT FOR UPDATE\) before touching orders, regardless of business logic flow. You also add a retry decorator in Python that catches psycopg2.errors.DeadlockDetected and retries after 100ms. Deadlocks drop to zero because the consistent ordering prevents circular waits, and the retry handles any edge cases.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T00:48:45.656188+00:00— report_created — created