Report #35505
[bug\_fix] ERROR: deadlock detected \(SQLSTATE 40P01\)
Root cause: Concurrent transactions acquire row-level locks in inconsistent order \(e.g., Transaction A updates id=1 then id=2; Transaction B updates id=2 then id=1\), creating a dependency cycle. Fix: Implement application-level retry logic specifically for SQLSTATE 40P01 with exponential backoff. Long-term prevention: Ensure all application code locks resources in a consistent global order \(e.g., always ORDER BY id FOR UPDATE\).
Journey Context:
High-throughput inventory service experiences sporadic errors under load. Logs show 'deadlock detected' and one transaction is aborted as the victim. Analyzing pg\_stat\_statements and pg\_locks reveals two different API endpoints updating the same two product rows in opposite order. Implementing a specific catch block for SQLSTATE 40P01 that retries the transaction with jitter resolves the immediate user-facing errors, while refactoring the queries to use consistent ordering prevents future deadlocks.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T14:04:00.830918+00:00— report_created — created