Sub topic 13
Deadlocks: detection and avoidance
This chapter assumes you know BEGIN, COMMIT and ROLLBACK, and that you have seen row locks from SELECT ... FOR UPDATE. The examples use PostgreSQL syntax. The ideas apply to MySQL/InnoDB and SQL Server too, though error codes and defaults differ.
What a deadlock is
A deadlock happens when two or more transactions each hold a lock the other needs, and each waits for the other to release it. Neither can proceed, because a lock is only released at COMMIT or ROLLBACK, and neither transaction can reach either one while it is waiting.
A deadlock is not the same as a slow wait. If transaction A holds a lock and is merely busy, B will get the lock eventually. In a deadlock, no amount of waiting helps. The database has to step in.
Here is the classic case, using the accounts table from earlier chapters. Session A moves money from account 1 to account 2. Session B moves money from account 2 to account 1 at the same time.
-- Session A -- Session B
BEGIN; BEGIN;
UPDATE accounts SET balance = balance - 10
WHERE id = 1; -- locks row 1
UPDATE accounts SET balance = balance - 5
WHERE id = 2; -- locks row 2
UPDATE accounts SET balance = balance + 10
WHERE id = 2; -- waits for B
UPDATE accounts SET balance = balance + 5
WHERE id = 1; -- waits for A: deadlockEach session holds one row lock and wants the other. The diagram shows the cycle.
How the database detects a deadlock
The database tracks which transactions wait for which. This is called the wait-for graph: each transaction is a node, and an edge from A to B means "A is waiting for a lock that B holds." A deadlock is a cycle in that graph.
Detection works differently across systems:
- PostgreSQL does not check on every wait. A transaction that waits for a lock longer than
deadlock_timeout(default 1 second) runs the cycle check. This keeps the common case, short waits with no cycle, cheap. - MySQL/InnoDB checks for cycles immediately when a lock wait begins (
innodb_deadlock_detect, on by default). It also hasinnodb_lock_wait_timeoutfor waits that are not cycles. - SQL Server runs a background lock monitor that looks for cycles about every few seconds, more often when deadlocks are frequent.
When the database finds a cycle, it picks a victim, aborts that transaction, and releases its locks. The other transactions can then continue. The victim receives an error. In PostgreSQL the error looks like this:
ERROR: deadlock detected
DETAIL: Process 4121 waits for ShareLock on transaction 8812; blocked by process 4130.
Process 4130 waits for ShareLock on transaction 8811; blocked by process 4121.
HINT: See server log for query details.
SQLSTATE: 40P01The SQLSTATE 40P01 is deadlock_detected. It belongs to class 40, "transaction rollback", along with 40001, serialization_failure. Both mean "the database undid your transaction, and running it again may succeed."
How the victim is chosen depends on the engine. PostgreSQL aborts the transaction that ran the check, which is usually the one that waited longest past the timeout. InnoDB prefers the transaction that has changed the fewest rows, since it is cheapest to undo. SQL Server uses the lowest DEADLOCK_PRIORITY, then the cheapest rollback. You cannot rely on being the survivor.
Common causes
Deadlocks are rarely random. They usually come from one of these patterns:
- Inconsistent lock order. Two code paths touch the same rows in different orders, as in the transfer example.
- Lock upgrades. A transaction reads with a shared lock and later tries to take an exclusive lock on the same row, while another transaction does the same. Both hold shared locks and both wait to upgrade.
- Multi-row statements with no defined order.
UPDATE ... WHERE status = 'pending'locks rows in whatever order the plan visits them. Two such statements with different plans, or run against changing data, can lock the same rows in opposite orders. - Foreign keys and indexes. Inserting a child row takes a lock on the parent row. Concurrent inserts and parent updates can form a cycle that is not obvious from the SQL.
- Long transactions. The longer locks are held, the more chances for a cycle. Waiting on a user, an HTTP call or a sleep while holding locks is a common contributor.
- Gap and next-key locks. In InnoDB under REPEATABLE READ, range queries lock gaps between index entries, so two inserts into the same gap can deadlock even though they touch different rows.
Avoiding deadlocks
Detection is a safety net. Avoidance reduces how often you need it.
Lock in a consistent order
If every transaction acquires locks in the same global order, a cycle cannot form. For a transfer, always lock the lower id first, whatever the direction of the money.
BEGIN;
-- Lock both rows up front, always in ascending id order.
SELECT id FROM accounts
WHERE id IN (1, 2)
ORDER BY id
FOR UPDATE;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;Now both sessions in the earlier example ask for row 1 first. One gets it, the other waits, and the first finishes and releases both locks. No cycle exists.
ORDER BY combined with FOR UPDATE does not strictly guarantee lock order in every PostgreSQL plan, but it is the accepted practice and works in the common case of a simple indexed query. For strict control, lock rows one at a time in a loop sorted by key.
Keep transactions short
Do slow work, such as network calls, file writes and user prompts, before BEGIN or after COMMIT. Open the transaction late and close it early.
Lock only what you need
Take the strongest lock you need at the first read. If you will update a row after reading it, use SELECT ... FOR UPDATE at the start to avoid a later upgrade. In PostgreSQL, FOR NO KEY UPDATE is weaker than FOR UPDATE and does not block foreign-key checks from other transactions, which reduces some deadlocks.
Fail fast instead of waiting
Two settings limit how long a session waits:
SET lock_timeout = '2s'; -- give up if a lock is not granted in 2 seconds
SET statement_timeout = '10s'; -- cancel any statement that runs longer than 10 secondsOr skip locked rows entirely, which suits job queues:
SELECT id FROM jobs
WHERE status = 'queued'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;NOWAIT raises an error at once if the row is locked. SKIP LOCKED ignores locked rows and returns the rest. Neither causes a deadlock, because no session waits.
Use a lower isolation level or a single statement when correctness allows
An atomic statement such as UPDATE accounts SET balance = balance - 10 WHERE id = 1 AND balance >= 10 takes one lock and holds it briefly. It avoids a read-then-write sequence altogether.
Diagnosing a deadlock
The error message names the processes and the lock types. The server log contains the full statements involved. In PostgreSQL, set log_lock_waits = on to log any wait longer than deadlock_timeout. In MySQL, SHOW ENGINE INNODB STATUS prints the most recent deadlock, and innodb_print_all_deadlocks writes every one to the error log.
To see who is blocking whom right now in PostgreSQL:
SELECT pid,
pg_blocking_pids(pid) AS blocked_by,
state,
wait_event_type,
left(query, 60) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;Rows returned are sessions currently waiting. A pair of sessions that list each other in blocked_by is a cycle that has not yet been detected.
Handling the error in the application
You cannot fully eliminate deadlocks in a busy system, so the application must treat 40P01 and 40001 as retryable. Chapter 14 covers the retry pattern in detail. The key rules are:
- Retry the whole transaction, not only the failed statement.
- Re-read any data the transaction used, since it may have changed.
- Limit attempts and add a short random delay so the retrying sessions do not collide again.
- Make the transaction free of side effects outside the database, or the retry will repeat them.
Summary table
| Aspect | Detail |
|---|---|
| Cause | Cycle of lock waits among two or more transactions |
| Detection | Wait-for graph cycle check (after `deadlock_timeout` in PostgreSQL) |
| Result | One victim transaction is rolled back with an error |
| PostgreSQL SQLSTATE | `40P01` |
| Best prevention | Same lock order everywhere, short transactions |
| Safety net | Retry the whole transaction |
Exercise
Two code paths update rows in table orders. Path 1 updates order 7 and then order 9. Path 2 updates order 9 and then order 7. Occasionally one of them fails with SQLSTATE 40P01. Explain why, and describe two changes that reduce the problem.
Show answer
When both paths run at once, Path 1 locks order 7 and Path 2 locks order 9. Then Path 1 waits for order 9 and Path 2 waits for order 7, which is a cycle, so the database aborts one of them with 40P01. First change: make both paths lock rows in the same order, for example ascending order id, by sorting the ids before updating. Second change: keep the transactions short, and wrap the work in a retry loop that re-runs the whole transaction when it sees 40P01 or 40001.
Exercise
Why does PostgreSQL wait for deadlock_timeout before checking for a deadlock, and what does that mean for a deadlock between two sessions when you set the value to 10 seconds?
Show answer
The cycle check is relatively costly, and most lock waits end quickly without any cycle, so PostgreSQL only runs the check once a wait has lasted longer than the timeout. With a value of 10 seconds, a real deadlock stays undetected for at least 10 seconds, so both sessions hang for that time before one is aborted. A longer value saves checking work but makes real deadlocks hurt more.