Report #17467
[bug\_fix] ERROR: deadlock detected \(SQLSTATE 40P01\)
Implement client-side retry logic with exponential backoff for transactions that fail with a deadlock error, or enforce a strict global ordering of row/table access \(e.g., always acquire locks on rows ordered by primary key ascending\) to prevent the circular wait condition.
Journey Context:
You have a funds transfer endpoint that debits account A and credits account B within a transaction. Under high concurrency, you see intermittent 'deadlock detected' errors. Logs show Process X waits for ShareLock on transaction Y, blocked by process Z, which is blocked by X. Analysis reveals Transaction 1 locks account 100 then 200, while Transaction 2 locks account 200 then 100, creating a cycle. You implement a retry decorator in your repository layer that catches OperationalError with SQLSTATE 40P01 and retries up to 3 times with jitter. As a permanent fix, you refactor the transfer logic to always sort account IDs and lock the smaller ID first, eliminating the possibility of deadlocks.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T05:24:49.145468+00:00— report_created — created