hardScenarioConceptMidSeniorStaff
You are getting a handful of deadlock errors an hour under load. How do you find the cause, and how do you stop them?
7 min readUpdated 2026-08-15
Answer
Short answer
A deadlock is a cycle in the wait-for graph, so read the engine's own report to get both statements and the locks each held. Nearly all of them come from two code paths taking the same rows in different orders; impose one order, shorten transactions, and retry, because a deadlock is always safe to retry.
Was this answer helpful?
Likely follow-ups
- Why can a single UPDATE statement with no explicit locking still deadlock against itself?
- How does SKIP LOCKED change the picture for workers pulling jobs from a table?
- What is the difference between lock_timeout, statement_timeout and deadlock_timeout in PostgreSQL?
- Under what circumstances would you rather have lock-wait timeouts than deadlock detection?
Related questions
- Two doctors can go off call only if at least one remains. Both check the rule at the same moment, both see two doctors on call, and both go off call. What isolation problem is this, and what actually fixes it?hardAlso on transactions and locking6 min
- Walk me through the transaction isolation levels and which anomalies each one permits.hardAlso on transactions and postgresql6 min
- A user submits the form twice and you get two identical orders. Why did the check-then-insert not prevent it, and how do you fix it in the database?hardAlso on transactions and postgresql6 min
- A method with REQUIRES_NEW was meant to save an audit row even when the main transaction fails. When does it work, and when does it deadlock?hardAlso on transactions5 min