Difficulty: Intermediate
What causes a database deadlock, how does the database detect it, and what do you do in practice to prevent and handle deadlocks?
A deadlock happens when two or more transactions each hold a lock the other needs, so none of them can ever proceed. Databases detect this by finding a cycle in the wait-for graph and then abort one transaction (the victim) so the others can continue. You prevent most deadlocks by acquiring locks in a consistent order, keeping transactions short, and indexing the columns you filter on, and you handle the rest by retrying the aborted transaction.
The classic case is two transfers running at the same time:
Each is waiting for the other, forever. The four classic conditions are all present: mutual exclusion, hold and wait, no preemption, and circular wait. Breaking any one of them removes the deadlock, and in databases circular wait is the easiest to break.
deadlock_timeout (default 1 second). If it finds a cycle, it aborts one transaction with SQLSTATE 40P01 "deadlock detected".innodb_deadlock_detect) and happens immediately. InnoDB rolls back the transaction it considers smaller (fewer rows changed) and returns error 1213. SHOW ENGINE INNODB STATUS prints the latest deadlock details.innodb_lock_wait_timeout (default 50 seconds) and PostgreSQL's lock_timeout stop transactions that simply wait too long.min(A, B) first, then max(A, B).UPDATE without a usable index may scan and lock many more rows than intended, especially in InnoDB, where gap and next-key locks under REPEATABLE READ are a common deadlock source.SELECT ... FOR UPDATE all the rows you will need at the start, in a fixed order, rather than escalating midway.REPEATABLE READ to READ COMMITTED removes most gap locking, but check your consistency needs first.Deadlocks are a normal, expected event in a busy OLTP system. The correct response is:
40P01 or 1213, or serialization failure 40001).-- Transfer Rs 1,000 from account 202 to account 101
BEGIN;
-- Lock both rows in ascending id order, regardless of direction
SELECT id FROM accounts
WHERE id IN (101, 202)
ORDER BY id
FOR UPDATE;
UPDATE accounts SET balance_paise = balance_paise - 100000 WHERE id = 202;
UPDATE accounts SET balance_paise = balance_paise + 100000 WHERE id = 101;
COMMIT;
Every transfer locks the lower id first, so two opposite transfers queue up instead of forming a cycle.
const RETRYABLE = new Set(["40P01", "40001"]); // deadlock, serialization failure
async function withRetry<T>(fn: () => Promise<T>, attempts = 3): Promise<T> {
for (let i = 1; ; i++) {
try {
return await fn(); // fn runs the whole transaction
} catch (err: any) {
if (!RETRYABLE.has(err.code) || i >= attempts) throw err;
const delay = 20 * 2 ** i + Math.random() * 50; // jittered backoff
await new Promise((r) => setTimeout(r, delay));
}
}
}
await withRetry(() => transfer(202, 101, 100000));
The retry wraps the entire transaction, not a single statement, because the database already rolled back everything the victim did.
Deadlock, Wait-for Graph, Lock Ordering, Deadlock Detection, Transaction Retry