Report #69827
[bug\_fix] ERROR: deadlock detected
Enforce a strict global ordering for lock acquisition \(e.g., always update rows ordered by primary key ASC\). This prevents circular wait conditions by ensuring all transactions acquire locks on the same resources in the same sequence.
Journey Context:
A nightly batch job that updates inventory counts randomly fails with "deadlock detected." The error log shows Process 12345 waits for ShareLock on transaction 67890; blocked by process 54321. Process 54321 waits for ShareLock on transaction 12345; blocked by process 12345. Investigating the code reveals two concurrent workers: Worker A updates product SKU "A123" then "B456", while Worker B updates "B456" then "A123" depending on the order they receive messages from a queue. This creates a circular dependency: TX1 holds lock on A123 waiting for B456, while TX2 holds lock on B456 waiting for A123. PostgreSQL detects the cycle and aborts one transaction. The fix requires strict ordering: always sort the list of SKUs before updating, so both workers attempt to lock A123 first, then B456. The first worker gets both locks; the second blocks on the first lock, avoiding the cycle.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T23:41:24.338757+00:00— report_created — created