Deadlocks, Livelocks and Starvation
You add locks to fix a race, the tests pass, and the service goes to production. A week later, under a busy hour, two requests stop responding. No exception, no error log, CPU at zero. The threads are alive but stuck, each waiting for a lock the other one holds. Nothing will ever wake them.
That is a deadlock, and it is the price of using more than one lock. Its two cousins are quieter: in a livelock threads stay busy but never finish, and in starvation one thread never gets its turn while the others run fine. This post starts from a bank transfer that deadlocks, explains exactly why, and walks through the fixes: taking locks in a fixed order, giving up with a timeout, and detecting a deadlock after it happens.
💡 Why this matters in an interview: the moment your design takes two locks at once (a transfer between two accounts, a move between two shelves, a booking that locks a seat and a user), your interviewer will ask "can this deadlock?" You should be able to say yes or no, explain why, and prevent it with one rule.
A Deadlock in Four Lines
Each Account has its own lock, so transfers between unrelated accounts can run in parallel. To move money, a
transfer locks the source, then the destination, so both balances change together.
class Account:
def __init__(self, account_id: int, balance: int) -> None:
self.id = account_id
self.balance = balance
self.lock = threading.Lock()
def transfer(src: Account, dst: Account, amount: int) -> bool:
with src.lock: # 1. lock the source
with dst.lock: # 2. then lock the destination
if src.balance < amount:
return False
src.balance -= amount
dst.balance += amount
return True
This is correct for one transfer at a time, and it is correct for most pairs of transfers too. Now Alice sends Bob 10 dollars at the same moment Bob sends Alice 5:
| Step | Thread A: transfer(alice, bob) | Thread B: transfer(bob, alice) |
|---|---|---|
| 1 | locks alice |
|
| 2 | locks bob |
|
| 3 | waits for bob (held by B) |
|
| 4 | waits for alice (held by A) |
|
| 5 | waits forever | waits forever |
Thread A holds Alice's lock and needs Bob's. Thread B holds Bob's lock and needs Alice's. Neither will release what it has until it gets what it wants, so neither ever moves again. Every later transfer that touches Alice or Bob queues up behind them and freezes too.
Two things make this bug nasty. It only happens when the timing lines up, so tests that run transfers one at a time never see it. And it produces no error at all: the program just stops making progress.