What is a deadlock, how does a database engine detect them, and what strategies can you use in application code to prevent them?
Last updated
A deadlock is a circular wait where transactions each hold a lock the other needs, so none can proceed.
Engines detect cycles in a wait-for graph and roll back a cheap victim with a deadlock error (lock timeouts act as a fallback).
Prevent them by acquiring locks in a consistent order, keeping transactions short, locking needed rows up front with
SELECT ... FOR UPDATE, and retrying with backoff.
- https://cslant.com/tips/database-deadlocks-detection-diagnosis-and-prevention
- https://learn.microsoft.com/en-us/sql/relational-databases/sql-server-deadlocks-guide?view=sql-server-ver17
- https://blog.sqlauthority.com/2023/06/23/sql-server-deadlocks-interview-q-and-a/
- https://learn.microsoft.com/en-us/sql/tools/sql-server-profiler/analyze-deadlocks-with-sql-server-profiler?view=sql-server-ver17
- https://www.alibabacloud.com/blog/deep-dive-into-innodb-locks_602681
- https://postgrespro.com/blog/pgsql/5968020
- https://www.postgresql.org/docs/current/runtime-config-locks.html
- https://postgresqlco.nf/doc/en/param/deadlock_timeout/