Module 3 · Database designLesson 30 of 886 minAdvanced

Deadlocks

A deadlock is two transactions each waiting for a lock the other holds. Neither can move until one is cancelled.

Try it

Play "Deadlock" and watch the database break the cycle by aborting one transaction. Then play "Same lock order" and see why it never gets stuck.

To keep data correct, databases lock rows that a transaction is changing. Others who want the same row wait. Usually that's a short wait. But sometimes waiting forms a circle.

How a deadlock happens

  1. Transaction 1 locks row A.
  2. Transaction 2 locks row B.
  3. Transaction 1 asks for B: it waits for T2.
  4. Transaction 2 asks for A: it waits for T1.

Both wait forever. This is a deadlock.

What the database does

Databases watch for these cycles. When they find one, they pick a victim, abort it, and release its locks so the other can finish. The victim gets an error like deadlock detected.

So deadlocks aren't a disaster; they're an expected error your code should catch and retry.

Preventing them

  • Lock in a consistent order: if every transaction touching accounts locks the lower id first, no cycle is possible. A transfer from Bob to Alice locks Alice first too.
  • Keep transactions short: less time holding locks, fewer chances to collide.
  • Touch fewer rows: use precise WHERE clauses with indexes, so the database doesn't lock more than needed.
  • Lock everything up front: grab all the rows you need at the start (SELECT ... FOR UPDATE) rather than one by one.

Related ideas

The same pattern appears outside databases: two threads, two mutexes; two services each waiting on the other. Distributed locks (module 5) need timeouts precisely because a stuck lock holder elsewhere can't be detected as easily.

Quick check

Two transfer jobs keep deadlocking when moving money between the same two accounts in opposite directions. What's a simple fix?