Report #17261
[bug\_fix] ERROR: deadlock detected
Enforce a strict, deterministic order of row locking across all code paths that modify the same set of rows \(e.g., always acquire locks on primary keys in ascending order using ORDER BY\). This ensures transactions wait in a linear queue rather than forming a circular wait cycle \(the necessary condition for a deadlock\).
Journey Context:
A Django e-commerce platform experiences intermittent 500 errors during flash sales. Logs reveal \`ERROR: deadlock detected\` on a function that decrements inventory. The developer analyzes the trace and finds two concurrent checkout transactions: Transaction 1 locks product ID 100 then attempts to lock ID 200; Transaction 2 locks ID 200 then attempts to lock ID 100. This circular wait causes Postgres to kill one transaction to break the deadlock. The developer realizes the ORM's \`select\_for\_update\(\)\` does not specify an order, so lock acquisition depends on the arbitrary order of items in the user's cart. The fix involves modifying the query to explicitly sort the IDs before locking: \`Inventory.objects.filter\(id\_\_in=ids\).order\_by\('id'\).select\_for\_update\(\)\`. After deployment, deadlock monitoring drops to zero.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T04:52:42.349766+00:00— report_created — created