Deadlock Prevention

Difficulty: Intermediate

Question

What causes a database deadlock, how does the database detect it, and what do you do in practice to prevent and handle deadlocks?

Answer

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.

How a deadlock forms

The classic case is two transfers running at the same time:

  1. Transaction T1 transfers from account A to B. It updates A and holds A's row lock.
  2. Transaction T2 transfers from B to A. It updates B and holds B's row lock.
  3. T1 now tries to update B and waits for T2.
  4. T2 tries to update A and waits for T1.

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.

How databases detect and resolve it

  • Wait-for graph: each transaction is a node, and an edge T1 to T2 means T1 is waiting on a lock T2 holds. A cycle means deadlock.
  • PostgreSQL: a waiting transaction checks for deadlock after deadlock_timeout (default 1 second). If it finds a cycle, it aborts one transaction with SQLSTATE 40P01 "deadlock detected".
  • MySQL InnoDB: detection is on by default (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.
  • Separately, innodb_lock_wait_timeout (default 50 seconds) and PostgreSQL's lock_timeout stop transactions that simply wait too long.

Prevention techniques that work

  • Consistent lock order. Always lock rows in the same order, such as ascending primary key. In the transfer example, lock min(A, B) first, then max(A, B).
  • Short transactions. Do not make HTTP calls, send emails or wait for user input inside a transaction. Less time holding locks means fewer collisions.
  • Index your WHERE clauses. An 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.
  • Lock up front. SELECT ... FOR UPDATE all the rows you will need at the start, in a fixed order, rather than escalating midway.
  • Batch large updates. Updating a million rows in one statement locks for a long time; chunks of a few thousand reduce overlap.
  • Consider isolation level. Moving MySQL from REPEATABLE READ to READ COMMITTED removes most gap locking, but check your consistency needs first.

Handling the deadlocks you cannot prevent

Deadlocks are a normal, expected event in a busy OLTP system. The correct response is:

  • Catch the specific error code (40P01 or 1213, or serialization failure 40001).
  • Retry the whole transaction from the beginning, with a small randomized backoff, a limited number of times.
  • Log and alert if the rate rises, then use the deadlock report to find which statements collided.
Two transfers deadlocking. Each transaction holds one row lock and waits for the other's.
  1. T1 → Database: UPDATE account A (lock A)
  2. T2 → Database: UPDATE account B (lock B)
  3. T1 → Database: UPDATE account B, waits on T2
  4. T2 → Database: UPDATE account A, waits on T1
  5. Database → T2: Cycle found, T2 aborted
  6. Database → T1: Lock on B granted, T1 continues

Code examples

Locking rows in a consistent order

-- 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.

Retrying on deadlock in application code

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.

Key points

  • A deadlock is a cycle of transactions each waiting on a lock another holds
  • Databases detect cycles in a wait-for graph and abort one victim transaction
  • PostgreSQL checks after deadlock_timeout (1s default) and raises 40P01; InnoDB raises 1213
  • Main prevention: consistent lock order, short transactions, indexed predicates
  • Always retry the entire transaction on deadlock errors with jittered backoff

Common follow-up questions

  • What is the difference between a deadlock and a lock wait timeout?
  • How do gap locks in InnoDB cause deadlocks?
  • How would you read a deadlock report from SHOW ENGINE INNODB STATUS?
  • Can a single UPDATE statement deadlock with another single UPDATE?

Interview tips

  • Walk through the two-transfer example step by step; interviewers like a concrete timeline
  • Say clearly that deadlocks cannot be eliminated entirely, so retry logic is required
  • Mention lock ordering by primary key as your first prevention technique

Concepts covered

Deadlock, Wait-for Graph, Lock Ordering, Deadlock Detection, Transaction Retry

More Database Design questions