Report #22958
[bug\_fix] ERROR: deadlock detected \(PostgreSQL\)
Implement application-level retry logic with exponential backoff specifically catching error code 40P01. Alternatively, eliminate the deadlock possibility by ensuring all transactions acquire locks on rows in a consistent global order \(e.g., always lock account records ordered by account\_id ASC\).
Journey Context:
Under high concurrency, transactions failed intermittently with 'deadlock detected'. Logs showed Process X waits for ShareLock on transaction Y; blocked by process Z. Analysis revealed two concurrent fund transfers: one locking account A then B, another locking B then A. The first instinct was to increase lock\_timeout, but this doesn't prevent deadlocks. Realized deadlocks are a normal MVCC occurrence; PostgreSQL automatically rolls back one transaction to break the cycle. The solution was not to prevent deadlocks \(impossible under concurrent updates to crossing rows\) but to handle them. Implemented a decorator catching 40P01 and retrying with exponential backoff \(immediate, 100ms, 200ms, 400ms\). This resolved the issue because the rolled-back transaction simply retries on a clean state.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T16:56:58.984123+00:00— report_created — created