Report #59397
[bug\_fix] ERROR: deadlock detected \(SQLSTATE 40P01\)
Implement an application-level retry loop with exponential backoff specifically for SQLSTATE 40P01 \(deadlock detected\) and 40001 \(serialization failure\). Alternatively, reorder SQL statements within transactions to acquire locks on rows in a consistent global order \(e.g., SELECT ... ORDER BY id FOR UPDATE\) to prevent circular wait conditions.
Journey Context:
A Python e-commerce service processing checkouts sees intermittent 'deadlock detected' errors during flash sales. Two concurrent transactions update inventory: Transaction A locks SKU-123 then tries to lock SKU-456; Transaction B locks SKU-456 then tries to lock SKU-123. PostgreSQL's deadlock detector \(bgwriter\) wakes after 1s \(deadlock\_timeout\) and kills Transaction B. The application was not catching 40P01 specifically, showing a generic 500 error. Adding a retry decorator with tenacity that catches OperationalError with SQLSTATE 40P01 allows Transaction B to retry successfully on the next attempt.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T06:11:25.376805+00:00— report_created — created