Report #20735
[bug\_fix] Postgres: ERROR: deadlock detected \(SQLSTATE 40P01\)
Implement application-level retry logic with exponential backoff specifically for SQLSTATE 40P01. For prevention, ensure all transactions acquire locks on rows in a consistent global order \(e.g., always UPDATE rows ordered by primary key ascending\).
Journey Context:
An e-commerce platform experiences intermittent transaction failures during flash sales. The logs show ERROR: deadlock detected. Analysis reveals two concurrent transactions: Transaction A updates inventory for product X then product Y; Transaction B updates product Y then product X. When they interleave, each holds a lock the other needs. Postgres detects the circular wait and aborts one transaction \(the 'victim'\) to break the deadlock. The team implements a retry decorator in their ORM that catches 40P01 and retries up to 3 times with jitter. They also refactor the inventory update logic to always sort product IDs before updating, ensuring lock ordering and preventing the cycle.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T13:12:33.777535+00:00— report_created — created