Lesson 9 of 19
17. Transactions and Locking

17.8 What is a deadlock?

3 min read+10 XP

On the train: Clerk A holds seat 14 and wants seat 15 (a couple booking together). Clerk B holds seat 15 and wants seat 14. Each waits for the other. Forever.

In the system: A deadlock is a cycle of transactions each waiting for a lock another holds.

transaction A holds seat 14 and waits for 15; B holds 15 and waits for 14.

Figure: the database breaks the cycle by aborting one transaction; you prevent most cycles by locking in a fixed order.

What the database does: it keeps a wait-for graph, spots the cycle (the chapter's code does this with a simple loop), aborts one transaction (the victim) with a deadlock error, and lets the other continue.

What you do:

  • Lock in a consistent order: always lock the lower seat number first. If everyone locks 14 before 15, the cycle can't form.
  • Keep transactions short, so locks are held briefly.
  • Lock what you need up front where possible, instead of adding locks gradually.
  • Retry the victim. Deadlocks under load are normal; unhandled deadlock errors are bugs.

Memory code: "Grab seats in the same order and nobody waits in a circle."