Report #50260
[bug\_fix] ERROR: deadlock detected \(Postgres cyclic lock dependency\)
Enforce a strict global lock acquisition order \(e.g., always lock tables alphabetically, or always acquire row locks in primary-key ascending order\) so that concurrent transactions cannot form a circular wait. Alternatively, implement application-level retry logic when catching SQLSTATE 40P01. Root cause: When Transaction A holds Lock 1 and requests Lock 2, while Transaction B holds Lock 2 and requests Lock 1, PostgreSQL's deadlock detector terminates one transaction to break the cycle.
Journey Context:
Built an inventory management system where OrderService deducts stock from inventory table then inserts order record, while AuditService logs access to order table then updates inventory. Under concurrent load, logs showed 'deadlock detected, Process 12345 waits for ShareLock on transaction 67890'. Analyzing pg\_locks revealed Process A held row lock on inventory while waiting on order\_pkey, and Process B held order lock while waiting on inventory. Changed both services to always update tables in alphabetical order \(inventory first, then order\). Deadlocks disappeared entirely because lock acquisition became sequential rather than interleaved.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T14:50:38.326518+00:00— report_created — created