1. Home
  2. Database Management Systems
  3. Deadlock Detection (Wait-For Graph)

Deadlock Detection (Wait-For Graph)

Transactions that wait for each other forever form a cycle. Watch a depth-first search find it and the database abort a victim.

Interactive 3DIntermediate11 min readDBMSUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

When transactions lock rows, they can end up waiting for each other forever. The database keeps a wait-for graph and looks for a cycle. Press Detect deadlock.

Pseudocode

  1. build wait-for graph: edge Ti → Tj if Ti waits for a lock held by Tj
  2. for each transaction T not yet visited:
  3. DFS(T), keeping the current path on a stack
  4. if the DFS reaches a transaction already on the stack:
  5. cycle found → DEADLOCK
  6. choose a victim in the cycle (e.g. the youngest) and abort it
  7. its locks are released, so remove its edges and repeat
Read this model as text · 11 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. When transactions lock rows, they can end up waiting for each other forever. The database keeps a wait-for graph and looks for a cycle. Press Detect deadlock.
  2. Wait-for graph: an arrow Ti → Tj means Ti waits for a lock that Tj holds. T1, T2 and T3 each hold a lock that the next one needs. A cycle means deadlock.
  3. DFS path: T1.
  4. DFS path: T1 → T2.
  5. DFS path: T1 → T2 → T3.
  6. The DFS reached T1 again while it is still on the path: cycle T1 → T2 → T3 → T1. These transactions wait for each other forever: DEADLOCK.
  7. Break the cycle: abort the youngest transaction in it, T3. Its locks are released and its edges disappear from the graph.
  8. DFS path: T1.
  9. DFS path: T1 → T2.
  10. DFS path: T4.
  11. No cycle exists any more, so there is no deadlock. Transactions can finish one after another (T3 had to be rolled back and restarted). Detection costs O(V + E) per check.

Try this in the 3D model

  • Run Circular wait. Which transactions form the cycle, and which one is aborted?
  • Run No cycle. Why is it fine that several transactions are waiting?
  • In the circular scenario, T4 waits for T1 but is not in the cycle. Is T4 deadlocked? Is it stuck?
  • After the abort, which transactions can finish first?

Deadlock in a database

Transaction T1 locks row A and then asks for row B. Meanwhile T2 holds B and asks for A. Each waits for the other forever: a deadlock. Locking is required for isolation, so deadlocks must be handled rather than ignored.

The wait-for graph

Make one node per transaction. Draw an arrow Ti → Tj when Ti is waiting for a lock that Tj holds.

There is a deadlock if and only if the graph contains a cycle.

Detection

for each transaction T not yet visited:
    DFS(T), remembering the current path
    if DFS reaches a transaction already on the path:
        cycle found → deadlock

Databases run this check periodically or whenever a lock request has to wait. The cost is O(V + E).

Recovery: pick a victim

Break the cycle by aborting one transaction in it. Common victim choices:

  • the youngest transaction (least work lost),
  • the one that has done the least work,
  • the one holding the fewest locks.

The victim is rolled back, its locks are released, the others continue, and the victim is restarted. To avoid starving the same transaction, systems count how often it was chosen.

Prevention instead of detection

Timestamp-based rules never allow a cycle:

Scheme Older transaction asks for a lock held by a younger one Younger asks for a lock held by an older one
Wait-die waits dies (aborts)
Wound-wait wounds (aborts) the younger waits

Code

def find_cycle(waits_for):
    state, path = {}, []
    def dfs(u):
        state[u] = 'on-path'
        path.append(u)
        for v in waits_for.get(u, []):
            if state.get(v) == 'on-path':
                return path[path.index(v):]
            if v not in state:
                cycle = dfs(v)
                if cycle:
                    return cycle
        path.pop()
        state[u] = 'done'
        return None
    for t in list(waits_for):
        if t not in state:
            cycle = dfs(t)
            if cycle:
                return cycle
    return None

print(find_cycle({'T1': ['T2'], 'T2': ['T3'], 'T3': ['T1'], 'T4': ['T1']}))  # ['T1', 'T2', 'T3']

Common mistakes

  • Thinking that waiting means deadlock. A chain of waits without a cycle ends when the first transaction commits.
  • Aborting a transaction outside the cycle, which does not help.
  • Forgetting to remove the victim’s edges and re-check. Several cycles can exist.
  • Confusing this with the Banker’s algorithm: detection finds a deadlock after it happens, while the Banker’s algorithm avoids it.

Complexity at a glance

Case / operationTimeWhy
Cycle detection (DFS)O(V + E)V transactions and E waits-for edges.
Deadlock prevention (wait-die)O(1) per lock requestCompare transaction timestamps; no graph needed.
Extra spaceO(V + E) for the graph

Quick check

Test yourself — pick an answer to see if you got it.

1. In a wait-for graph, what does the edge T1 → T2 mean?

2. How does the DBMS know a deadlock exists?

3. What does the DBMS do after finding a deadlock?

4. Which strategy avoids deadlocks without building a graph?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Deadlock Detection (Wait-For Graph). Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.