Circular Waits and Lock Contention: Spotting and Preventing Deadlocks
System DesignModel answerLast updated
Explain what a deadlock is, the conditions that make one possible, realistic scenarios, and the engineering techniques used to prevent, avoid, detect and recover from them.
Imagine you are discussing concurrency problems with a senior engineer and the topic turns to deadlocks. Prepare a structured answer that covers the following points.
- Definition. What is a deadlock, and how does it differ from livelock and starvation?
- Necessary conditions. Which conditions must all hold at the same time for a deadlock to occur?
- Scenarios. Describe several concrete situations in which deadlock can arise. Include the simple case of two threads and two locks, and at least one case that involves a cycle through three or more participants or that is less obvious (for example, something that is not a plain lock-order inversion).
- Handling. Explain how deadlocks are prevented, avoided, detected and recovered from in real systems. For each approach, state what it costs or what assumptions it makes.
A strong answer ties each prevention technique back to the specific condition it eliminates, and mentions pitfalls that people hit in practice.
Hints
Hint 1
Think of a deadlock as a cycle in a graph: nodes are threads, and an edge means 'is waiting for a resource held by'. Which four properties of the system make such a cycle both possible and permanent?
Hint 2
Every prevention strategy works by making exactly one necessary condition impossible. Map global lock ordering, try-lock with backoff, all-at-once acquisition and lock-free or message-passing designs to the condition each one removes.
Hint 3
Not every deadlock is two mutexes in opposite order. Consider self-locking with a non-reentrant lock, calling callbacks while holding a lock, a bounded thread pool whose tasks wait on other tasks, database row locks, and blocking on an async result.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. What a deadlock is
A deadlock is a state where a group of threads, processes or transactions are each blocked waiting for a resource held by another member of the group. Because every member is blocked, nobody releases anything, and without outside intervention the group never makes progress.
Two neighbouring problems are worth distinguishing:
- Livelock: participants keep running and changing state (for example, repeatedly backing off and retrying in lockstep) but still achieve nothing.
- Starvation: one participant waits indefinitely while others keep progressing, typically due to unfair scheduling or lock handoff.
2. The four necessary conditions (Coffman)
A deadlock can occur only if all four hold simultaneously:
- Mutual exclusion: at least one resource can be used by only one thread at a time.
- Hold and wait: a thread holds one resource while waiting for another.
- No preemption: resources cannot be forcibly taken; only the holder releases them.
- Circular wait: there is a cycle T1 → T2 → ... → Tn → T1 in which each thread waits for a resource held by the next.
For single-instance resources such as ordinary locks, these are also sufficient. The key insight: prevention means permanently breaking at least one condition.
3. Concrete scenarios
- Opposite lock order.
transfer(a, b)locksathenb; a concurrenttransfer(b, a)locksbthena. Each thread gets its first lock and waits forever for the second. - Longer cycle (dining philosophers). Five philosophers each grab the left fork, then the right. If all grab left at once, the wait cycle is P0→P1→P2→P3→P4→P0. The service-level analogue is three services that each lock their own record and then call the next service, which needs its record.
- Database row locks. Transaction 1 updates row 1 then row 2; transaction 2 updates row 2 then row 1. Most databases detect the cycle and abort one transaction as the victim.
- Self-deadlock. A thread takes a non-reentrant lock and then calls a helper that takes the same lock.
- Lock held across a callback. A component invokes listener code while holding its internal lock. The listener calls back in, or takes another lock that a different thread holds while calling the component, producing a hidden ordering inversion.
- Thread-pool starvation. A pool of N workers runs tasks that each submit a subtask and block on the result. Once all N workers are blocked, nobody is free to run the subtasks.
- Sync-over-async. Code on a context-bound thread (a UI thread, or a legacy request context) blocks on the result of an async operation whose continuation needs that same thread. The fix is to go async all the way or avoid capturing the context in library code.
4. Handling deadlocks
Prevention (break one condition)
| Condition broken | Technique | Trade-off |
|---|---|---|
| Circular wait | Global lock ordering by a stable key (account ID, lock level) | Cheapest and most common; needs discipline and is hard to enforce across modules |
| Hold and wait | Acquire all locks atomically up front, or release everything before requesting more | Lower concurrency; the full resource set may not be known in advance |
| No preemption | try_lock with timeout; on failure release everything, back off with random jitter, retry | Risk of livelock without jitter; operations must be safe to retry |
| Mutual exclusion | Immutable data, lock-free structures, message passing, single-writer design | Architectural change and more complex code; not always possible |
Design hygiene removes most real-world deadlocks:
- Keep critical sections short.
- Never call unknown code (callbacks, I/O, RPC) while holding a lock.
- Prefer one coarse lock to many fine ones until profiling shows contention.
- Use reentrant locks only when re-entry is genuinely required.
Avoidance
The Banker's algorithm grants a request only if the system remains in a safe state, meaning at least one order exists in which every thread can finish. It needs maximum resource claims declared in advance and costs roughly O(m·n²) per check for n processes and m resource types. It is mostly of theoretical or scheduler-level interest, rarely used in application code.
Detection
Maintain a wait-for graph with an edge T1 → T2 when T1 waits for a lock T2 holds, and search for cycles (DFS, O(V + E)) periodically or when a wait exceeds a threshold. Databases do this internally; runtimes expose it through thread dumps or deadlock-finding APIs. Lock-wait timeouts and watchdogs are cheap approximations.
Recovery
- Abort and roll back a victim (often the cheapest or youngest transaction) and retry it.
- Preempt a resource, if the operation can be undone.
- Restart the process or service.
Recovery requires work that is transactional, idempotent or retryable. In-memory thread deadlocks usually cannot be repaired in place, which is why application code leans on prevention.
Tooling
Lock-order checkers and race detectors (ThreadSanitizer, Linux lockdep), stress tests with randomized scheduling, and thread or memory dumps from hung processes all help find latent ordering bugs before production.
5. Example: ordered locking
import threading
class Account:
def __init__(self, account_id, balance):
self.id = account_id
self.balance = balance
self.lock = threading.Lock()
def transfer(src, dst, amount):
if src is dst: # avoid locking the same lock twice
return
first, second = sorted((src, dst), key=lambda a: a.id)
with first.lock:
with second.lock:
if src.balance < amount:
raise ValueError("insufficient funds")
src.balance -= amount
dst.balance += amount
Because every thread acquires locks in ascending ID order, a cycle cannot form. Time cost is O(1) per transfer plus the sort of two items.
6. Pitfalls to mention
- Ordering keys must be total and stable; ties or mutable keys reintroduce cycles.
- Handle the same-resource case (transfer to self).
- Timeouts alone do not fix the problem; lockstep retries cause livelock, so add jitter.
- Priority inversion is a related hazard, mitigated by priority inheritance.
- Deadlocks can span processes and machines; distributed locks and RPC chains need leases, TTLs and timeouts.
- Fine-grained locking multiplies the number of possible orderings, so more locks means more risk.
Summary line for the interview
A deadlock needs mutual exclusion, hold-and-wait, no preemption and circular wait. In practice, enforce a global lock order, avoid holding locks across external calls, use timeouts with jittered retry where ordering is impractical, and rely on detection plus transactional retry in databases.