Report #40570
[bug\_fix] ERROR: deadlock detected
Implement a retry loop in the application that catches the deadlock exception \(SQLSTATE 40P01\) and re-executes the entire transaction. To prevent deadlocks, ensure all code paths acquire row locks in a consistent global order \(e.g., always lock table A before table B\) and keep transactions as short as possible. The root cause is a circular wait: Transaction A holds lock on row 1 and waits for row 2, while Transaction B holds lock on row 2 and waits for row 1.
Journey Context:
Two concurrent API endpoints modify related records. Endpoint 1 updates the 'orders' table then the 'inventory' table; Endpoint 2 updates 'inventory' then 'orders'. Under concurrent load, one transaction is abruptly terminated with 'deadlock detected' and the application receives a 500 error. The Postgres log shows 'Process 12345 waits for ShareLock on transaction 678; blocked by process 54321'. The detail shows the conflicting queries. Debugging reveals the inconsistent lock ordering. The immediate fix is to add exponential backoff retry logic \(e.g., using tenacity in Python or a simple loop in Go\). The long-term fix is refactoring both endpoints to update tables in the same alphabetical order \(inventory first, then orders\) and committing immediately after the updates.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T22:34:08.615777+00:00— report_created — created