KatInterview

Circular Waits and Lock Contention: Spotting and Preventing Deadlocks

System DesignModel answer
MediumModel answerSystem Designconcurrencydeadlocklocking

Last 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.

  1. Definition. What is a deadlock, and how does it differ from livelock and starvation?
  2. Necessary conditions. Which conditions must all hold at the same time for a deadlock to occur?
  3. 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).
  4. 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.