Report #82471
[bug\_fix] ERROR: deadlock detected
Implement application-level retry logic with exponential backoff for SQLSTATE 40P01. Ensure all transactions acquire locks on rows in a consistent global order \(e.g., always update accounts ordered by account\_id ASC\). Keep transactions as short as possible to minimize lock contention.
Journey Context:
Your e-commerce platform experiences intermittent 500 errors during flash sales. The logs show 'ERROR: deadlock detected' with Detail showing Process A waits for ShareLock on transaction X, blocked by Process B, and vice versa. You analyze the code: Transaction A updates inventory for product\_id=5 then product\_id=10, while Transaction B updates product\_id=10 then product\_id=5. Under high concurrency, they deadlock. PostgreSQL kills one as the victim, but your application doesn't retry. You implement a retry decorator that catches SQLSTATE 40P01 and retries with exponential backoff. You also refactor the inventory update function to always sort product\_ids before updating, eliminating the circular wait condition.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T21:01:14.581576+00:00— report_created — created