Skip to content
Preptima
hardDesignConceptMidSeniorStaff

An operation in this code takes two locks and it deadlocks every few weeks. How would you design the locking so that cannot happen?

6 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

A deadlock is a cycle in the wait-for graph, so the design goal is a graph that cannot contain one: stop holding two locks where you can, impose one total order on acquisition everywhere you cannot, and never call unknown code while holding a lock.

Mention lock ordering where it changes the risk, the owner, or the next check. A useful lock ordering point should make the answer more testable, not merely longer. Tie lock ordering back to the scenario so the interviewer can see why it matters here.

Was this answer helpful?

Likely follow-ups

  • Two threads need the same two objects and there is no identifier to order on. What do you order by?
  • Why does timeout-and-retry risk livelock, and what has to be true of the operation for it to be safe?
  • Where do you find the cycle in a running process, and what does that evidence look like?
  • The same deadlock happens between two database transactions instead of two threads. Does your rule still apply?

Related questions