Report #72168
[bug\_fix] ERROR: deadlock detected \(SQLSTATE 40P01\)
Implement application-level retry logic with exponential backoff for 40P01 errors; ensure consistent ordering of row updates across transactions.
Journey Context:
An e-commerce platform has a checkout process that decrements inventory. Transaction A updates product X then product Y. Transaction B \(different session\) updates product Y then product X. Under high load \(Black Friday\), both hold locks on their first product and wait for the second. After 1 second \(deadlock\_timeout\), Postgres detects the cycle and kills one transaction, raising ERROR: deadlock detected. The developer sees this in logs. Initially, they try to 'fix' it by optimizing indexes, but deadlocks are a locking protocol issue, not a performance issue. They implement a Python decorator using tenacity that catches psycopg2.errors.DeadlockDetected \(40P01\), waits a random 10-100ms, and retries. Deadlocks still occur but are handled transparently. They also refactor the inventory update to always sort product IDs before updating, ensuring all transactions grab locks in the same order, preventing the circular wait condition entirely.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T03:42:56.484815+00:00— report_created — created