← Back to SQL, page 12

sql-0232 · Medium mid

What is a deadlock, and how do you reduce the chance of one?

A deadlock happens when two transactions each hold a lock the other needs, so neither can continue. Server engines detect the cycle and abort one transaction with an error. Reduce deadlocks by locking rows in a consistent order, keeping transactions short, and touching as few rows as possible; and retry the aborted transaction.

Full answer

A classic case is two transfers in opposite directions:

text
T1: UPDATE accounts SET ... WHERE id = 1;   -- locks row 1
T2: UPDATE accounts SET ... WHERE id = 2;   -- locks row 2
T1: UPDATE accounts SET ... WHERE id = 2;   -- waits for T2
T2: UPDATE accounts SET ... WHERE id = 1;   -- waits for T1: deadlock

PostgreSQL checks for cycles after deadlock_timeout (1 second by default) and cancels one transaction with "deadlock detected".

Prevention:

  • Lock in a fixed order, for example always the lower account id first. Then both transfers queue on row 1 instead of crossing.
  • Lock everything up front with one SELECT ... FOR UPDATE ... ORDER BY id.
  • Keep transactions short and avoid user interaction inside them.
  • Treat the deadlock error as retryable.

SQLite has no row locks; its equivalent problem is two deferred transactions that both read and then both try to write, covered in the BEGIN IMMEDIATE question.

Key points

  • Deadlock: a cycle of transactions waiting on each other's locks
  • Engines detect it and abort one transaction
  • Lock rows in a consistent order
  • Keep transactions short and retry on deadlock errors

Common mistakes

  • Updating rows in request order instead of a fixed order
  • Treating a deadlock error as a fatal bug instead of retrying

Follow-ups

  • How does PostgreSQL choose which transaction to cancel?
  • How do you find which queries deadlocked?

Tips

  • Use the opposite-direction transfer example