Report #61728
[bug\_fix] ERROR: deadlock detected \(SQLSTATE 40P01\)
Implement application-level retry logic with exponential backoff that catches SQLSTATE 40P01, rolls back the failed transaction, and re-executes it.
Journey Context:
A background job processing system executed two concurrent tasks. Task A updated \`account\` row 1 then \`balance\` row 2. Task B updated \`balance\` row 2 then \`account\` row 1. Under load, they occasionally deadlocked. PostgreSQL detected the cycle after 1 second \(default \`deadlock\_timeout\`\), killed Task B \(the victim\), which threw 'ERROR: deadlock detected'. The application initially treated this as a fatal error. The investigation revealed the conflicting lock order. While reordering updates is the ideal fix, complex business logic made consistent ordering impractical. The robust solution was adding a try-catch block around the transaction: if SQLSTATE is 40P01, rollback and retry up to 3 times with exponential backoff. This transparently handles the occasional deadlock.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T10:05:58.036771+00:00— report_created — created