Sub topic 11
Deadlock: wait-for graphs, wait-die and wound-wait
This chapter assumes you know shared and exclusive locks, the compatibility matrix, and two-phase locking (2PL). You should also be comfortable with directed graphs and cycle detection. Two-phase locking guarantees serializability, but it does not guarantee that every transaction finishes. Transactions can wait on each other forever. That situation is a deadlock.
What a deadlock is
A deadlock is a set of transactions in which every transaction waits for a lock held by another transaction in the same set. None of them can proceed, because each one releases its locks only after it gets the lock it is waiting for.
Here is the smallest example. Two transactions lock two items in opposite orders.
| Step | T1 | T2 |
|---|---|---|
| 1 | lock-X(A) | |
| 2 | lock-X(B) | |
| 3 | lock-X(B), must wait for T2 | |
| 4 | lock-X(A), must wait for T1 |
After step 4, T1 waits for T2 and T2 waits for T1. Neither can continue.
Deadlock is a side effect of locking. Basic 2PL, strict 2PL and rigorous 2PL can all deadlock. Strictness only changes when locks are released, not the order in which they are requested.
A deadlock is different from starvation. In starvation, one transaction waits for a long time, or forever, while others keep making progress. In a deadlock, every transaction in the cycle is stuck.
Handling deadlocks: three strategies
A database has three broad options.
- Prevention. Arrange the rules so that a deadlock can never form.
- Detection and recovery. Allow deadlocks to form, find them, and abort a victim.
- Timeouts. Abort any transaction that has waited longer than a fixed limit. This is simple but crude. It may abort transactions that were only slow, and it may react late to real deadlocks.
Prevention costs extra aborts even when no deadlock would have happened. Detection costs graph maintenance. Detection is usually preferred when deadlocks are rare. Prevention is preferred when transactions are short and conflicts are frequent.
Detection with a wait-for graph
The database keeps a wait-for graph (WFG).
- Each node is an active transaction.
- There is a directed edge Ti → Tj when Ti is waiting for a lock that Tj currently holds.
When Ti gets the lock, or Ti ends, its outgoing edges are removed. The system has a deadlock if and only if the wait-for graph contains a cycle. Every transaction on a cycle is deadlocked. A transaction that merely waits for a deadlocked transaction, without being on the cycle, is also blocked, but it is not part of the cycle.
Building the graph
Suppose the lock table holds this state.
| Transaction | Holds | Waits for |
|---|---|---|
| T1 | S(A) | X(B) |
| T2 | X(B) | X(C) |
| T3 | X(C) | X(A) |
| T4 | none | S(B) |
T1 waits for B, which T2 holds, so the edge is T1 → T2. T2 waits for C, held by T3, giving T2 → T3. T3 waits for A, held by T1 in shared mode, which conflicts with X, so T3 → T1. T4 waits for B, held by T2, giving T4 → T2.
The cycle is T1 → T2 → T3 → T1, so a deadlock exists. T4 is blocked but is not on the cycle. Aborting one of T1, T2 or T3 breaks the cycle, and T4 then proceeds once T2 releases B.
A common mistake is to draw edges from the waiting transaction to the lock, or to add edges for locks that are compatible. If Ti requests S(A) and Tj holds S(A), there is no wait and no edge.
When to run detection
The system can run the cycle check every time a lock request blocks, or periodically. Checking on every block finds deadlocks immediately but costs more. Periodic checks are cheaper but let deadlocked transactions sit idle longer. Cycle detection by depth-first search takes O(V + E) time on the graph.
Recovery: choosing a victim
Once a cycle is found, the system must abort at least one transaction on it. This is the victim. Typical selection criteria:
- Abort the transaction that has done the least work, so the least work is lost.
- Abort the one that holds the fewest locks, or that needs the most further locks.
- Avoid choosing the same transaction repeatedly, otherwise it starves. A common fix is to include the number of past rollbacks in the cost.
Then the system chooses how far to roll back. A total rollback aborts the victim and restarts it. A partial rollback undoes only enough work to release the contested lock. Partial rollback saves work but needs the system to track more state.
Prevention with timestamps
Prevention schemes give each transaction a timestamp when it starts. A smaller timestamp means an older transaction. If a transaction is aborted, it restarts with its original timestamp. This is important: the restarted transaction gets older relative to newcomers, so it eventually becomes the oldest and cannot starve.
Both schemes below decide what to do when a requester Ti asks for a lock that conflicts with a lock held by Tj. In both schemes, the direction of waiting is always older-to-younger or always younger-to-older, so a cycle of waits cannot form.
Wait-die (non-preemptive)
- If Ti is older than Tj, Ti waits.
- If Ti is younger than Tj, Ti dies: it is aborted and restarted.
Older transactions wait for younger ones. Waits therefore only go from older to younger, which cannot form a cycle, since a cycle would need some wait going from younger back to older. Only the requester is ever aborted, and no running holder is interrupted, which is why this is called non-preemptive.
Wound-wait (preemptive)
- If Ti is older than Tj, Ti wounds Tj: Tj is aborted and rolled back, and Ti takes the lock.
- If Ti is younger than Tj, Ti waits.
Younger transactions wait for older ones. Waits only go from younger to older, so again no cycle can form. The older transaction preempts the younger holder, which is why this is called preemptive.
The two schemes compared
| Property | Wait-die | Wound-wait |
|---|---|---|
| Requester older than holder | Requester waits | Holder is aborted (wounded) |
| Requester younger than holder | Requester aborts (dies) | Requester waits |
| Who gets aborted | Always the requester | Always the holder |
| Style | Non-preemptive | Preemptive |
| Direction of waiting | Older waits for younger | Younger waits for older |
| Typical abort count | Often more unnecessary aborts, since a young requester may die and retry repeatedly | Often fewer aborts |
In wait-die, a young transaction can die several times before the older holder finishes, because each restart re-requests the lock. In wound-wait, a transaction is aborted at most once by a given older transaction, then it waits for it on the retry.
def wait_die(requester_ts, holder_ts):
# smaller timestamp = older transaction
return 'wait' if requester_ts < holder_ts else 'abort requester'
def wound_wait(requester_ts, holder_ts):
return 'abort holder' if requester_ts < holder_ts else 'wait'
print(wait_die(5, 9)) # wait
print(wait_die(9, 5)) # abort requester
print(wound_wait(5, 9)) # abort holder
print(wound_wait(9, 5)) # waitApply the first rule to the opening example. Let T1 have timestamp 1 and T2 have timestamp 2. At step 3, T1 (older) requests B held by T2. Under wait-die, T1 waits. At step 4, T2 (younger) requests A held by T1, so T2 dies. T2 releases B, T1 gets B and finishes, and T2 restarts later with timestamp 2. Under wound-wait, at step 3 T1 is older, so it wounds T2, which releases B and restarts. T1 proceeds. At step 4 in the original timeline, T2 never gets there.
Other prevention approaches
- Conservative 2PL. A transaction requests all its locks before it starts and runs only when it gets them all. No waiting happens while holding locks, so there is no deadlock. It needs the lock set known in advance and reduces concurrency.
- Ordered locking. Impose a global order on data items and require locks to be requested in that order. A cycle would need a lock request going against the order, which is forbidden. This is hard to enforce for ad hoc queries.
Locking in practice with SELECT ... FOR UPDATE
Explicit row locks make waiting visible. The example below shows a safe wait, not a deadlock: both sessions lock the same row, so the second simply queues.
-- Session 1 -- Session 2
BEGIN; BEGIN;
SELECT balance FROM account SELECT balance FROM account
WHERE id = 1 FOR UPDATE; WHERE id = 1 FOR UPDATE; -- blocks here
UPDATE account SET balance = balance - 100
WHERE id = 1;
COMMIT; -- now proceeds and reads the committed balance
UPDATE account SET balance = balance - 50
WHERE id = 1;
COMMIT;A deadlock would appear if session 1 locked row 1 then row 2, while session 2 locked row 2 then row 1. Most engines then run detection and abort one session with a deadlock error. The usual application fix is to access rows in a consistent order and to retry the aborted transaction.
Common errors in exam questions
- Saying that strict 2PL prevents deadlock. It does not.
- Drawing a wait-for edge for a request that is compatible with the held lock.
- Reversing the rules: remember that in wait-die the older waits, and in wound-wait the younger waits.
- Forgetting that an aborted transaction keeps its original timestamp when it restarts.
- Treating a transaction waiting on a cycle as part of the cycle. Only transactions on the cycle are deadlocked members, though others are blocked.
- Confusing the wait-for graph with the precedence graph. The precedence graph tests serializability of a finished schedule, and its cycle means not conflict serializable. The wait-for graph shows current blocking, and its cycle means deadlock.
Exercises
Exercise
Transactions T1, T2 and T3 have timestamps 10, 20 and 30. T2 requests a lock held by T3, then T2 requests a lock held by T1, and then T3 requests a lock held by T2. For each request, give the outcome under wait-die and under wound-wait.
Show answer
Smaller timestamp means older. (1) T2 (20) requests from T3 (30): requester is older. Wait-die: T2 waits. Wound-wait: T2 aborts T3. (2) T2 (20) requests from T1 (10): requester is younger. Wait-die: T2 dies. Wound-wait: T2 waits. (3) T3 (30) requests from T2 (20): requester is younger. Wait-die: T3 dies. Wound-wait: T3 waits.
Exercise
The lock table is: T1 holds X(A) and waits for X(B); T2 holds X(B) and waits for S(C); T3 holds S(C) and S(D); T4 holds X(D) and waits for X(A). Does a deadlock exist? Name the cycle if so.
Show answer
Build edges: T1 → T2 (B held by T2), T2 → T3 (S(C) is requested while T3 holds S(C), which is compatible, so T2 would not wait). Check again: if T2 requests S(C) and T3 holds S(C), there is no wait and no edge. So T2 is not blocked and no edge leaves T2. T4 → T1 (A held by T1). The edges are T1 → T2 and T4 → T1. There is no cycle, so no deadlock. T2 will get S(C), finish, release B, and T1 then proceeds.
Exercise
Why does a transaction aborted under wait-die or wound-wait restart with its original timestamp rather than a new one?
Show answer
With its original timestamp, the transaction keeps its age, so over repeated restarts it becomes the oldest active transaction. The oldest transaction is never aborted by either scheme, so it eventually finishes. A fresh timestamp would make it young again each time and could starve it.