Report #96789
[bug\_fix] ERROR: deadlock detected
The root cause is a cyclic dependency in lock acquisition order between concurrent transactions \(e.g., Transaction A locks row 1 then tries to lock row 2, while Transaction B locks row 2 then tries to lock row 1\). PostgreSQL automatically detects this and aborts one transaction to break the cycle. The fix is to implement application-level retry logic that catches the 40P01 SQLSTATE error and retries the entire transaction. Alternatively, restructure the application logic to always acquire locks in a consistent global order \(e.g., always lock lower IDs first\).
Journey Context:
An e-commerce platform experiences intermittent "deadlock detected" errors during high-traffic sales events. A developer analyzes the logs and finds two specific operations conflicting: a "transfer inventory" function and an "update order status" function. By adding detailed logging, they discover that the inventory function locks the inventory row then the order row, while the order status function locks the order row then the inventory row. This creates a perfect deadlock cycle when two requests hit simultaneously. The developer first tries to reorder the operations to always lock inventory before orders, but this requires refactoring multiple code paths. As a safer immediate fix, they implement a retry decorator in their repository layer that catches DeadlockDetected exceptions and retries the transaction up to 3 times with exponential backoff, which completely eliminates user-facing errors while maintaining data consistency.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T21:02:44.965841+00:00— report_created — created