📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Every few days one instance of your .NET order service stops responding completely: its requests hang forever, CPU drops to almost zero, it never recovers on its own, and restarting it "fixes" it until next time. How do you confirm it's a deadlock, capture the evidence before anyone restarts it, read the dump with syncblk, clrstack and pstacks, and fix the lock ordering or async misuse behind it?

A production playbook for an intermittent deadlock: the frozen-instance signature, capturing a dump before restart, reading it with SOS (syncblk, clrstack, pstacks, dumpasync), lock-order and async-blocking causes, the fix and prevention.

Senior Debugging Advanced concurrency deadlock dotnet-dump incident-response production sos

🎯 Key points

  • Signature: CPU near zero, requests on that instance never complete, no recovery when load drops (unlike starvation)
  • Mitigate by draining and replacing the instance, but take a full dump first: dotnet-dump collect or a dotnet-monitor trigger
  • syncblk shows which thread owns each Monitor lock and how many are waiting
  • clrstack on the owners shows each holding one lock and waiting for the other: a lock-order cycle
  • pstacks and dumpasync find async deadlocks: a SemaphoreSlim never released on an exception path, or .Result on a task that needs the blocked resource
  • Fix: a documented lock order enforced through one helper, no I/O, callbacks or awaits while holding a lock, SemaphoreSlim.WaitAsync with a timeout and Release in finally
  • Detection: a watchdog or liveness check that proves the work path progresses, plus a stuck-request alert
  • Prevent: avoid nested locks where one lock or a Channel will do, and a stress test that hammers the two code paths concurrently

⏱ 30-second answer

A deadlock looks different from starvation: CPU near zero, the instance's requests never complete, and it doesn't recover when load drops. Restarting hides it, so I drain the instance and take a full dump first (dotnet-dump collect, or a dotnet-monitor trigger). In the dump, syncblk shows which thread owns each Monitor lock and who is waiting; clrstack on the owners usually shows a lock-order cycle: thread A holds lock 1 and wants lock 2, thread B the reverse. For async code, pstacks and dumpasync show tasks waiting on a SemaphoreSlim or on a task that can never complete. The fix is a single lock order, never holding a lock across an await or a callback, and timeouts on waits. The trade-off: the dump pauses the process and holds sensitive data, but without it you're guessing.

🗣 Full answer (senior)

How I would answer this in an interview

"The words that matter are 'never recovers' and 'CPU near zero'. Starvation recovers when load drops; a slow dependency recovers when the dependency does. A deadlock doesn't recover, because two or more threads are each waiting for something another one holds. So the first decision is about evidence: the instance is already out of action, so I drain it from the load balancer, let a replacement take the traffic, and take a full dump of the frozen process before anyone restarts it. If this has happened before, I'd already have a dotnet-monitor rule or a runbook step for that.

For example, at [company] we had [an order service] that froze every [few days]. I took a dump and ran syncblk: two locks, each owned by a different thread, each with waiters. clrstack on the owners showed the inventory code took the stock lock then the order lock, while the cancellation path took the order lock then the stock lock. Under normal traffic the window was tiny, which is why it took days to hit. We introduced one lock order, moved the slow work out of the locked region, and added a stress test that runs both paths in parallel for a minute. It never froze again in [the following six months].

For async code the dump looks different: no Monitor locks, but pstacks shows threads parked in Task.Wait or nothing at all, and dumpasync shows state machines waiting on a SemaphoreSlim that will never be released, often because an exception skipped the Release. The mistake I see is adding a restart-on-hang script and calling it resilience: it turns a bug into a recurring outage with no evidence."


The playbook, in order

Step What I do Tool or command
1. Symptom One instance frozen, CPU ~0, never recovers Per-instance request duration, dotnet-counters (CPU low, queue length rising)
2. First five minutes Drain, replace capacity, keep the frozen process alive Remove from LB / label off the Service
3. Data to collect Full dump dotnet-dump collect -p 1 --type Full
4. Rule out Starvation (would recover; many threads, not a cycle), slow dependency (traces show calls in progress) Counters, App Insights
5. Root cause The cycle syncblk, clrstack -all, pstacks, dumpasync
6. Fix Lock order, smaller critical sections, async-aware primitives with timeouts Code change + stress test
7. Prevention Watchdog, stuck-request alert, review checklist Health check, KQL alert

Lock deadlock versus async deadlock

Lock-order deadlock Async deadlock
Primitive lock / Monitor, ReaderWriterLockSlim SemaphoreSlim, TaskCompletionSource, blocking on a task
What syncblk shows Owners and waiters Usually nothing
Best SOS command syncblk, then clrstack on owners dumpasync, pstacks
Typical cause Two paths take locks in different orders Missing Release on an exception path, .Result on a task that needs the blocked thread, awaiting inside a lock-like section
Fix Global ordering; never call out while locked try/finally around Release, WaitAsync with timeout, no sync-over-async

Production example

In a typical case the deadlock window is a few microseconds, so at 300 requests/s it fires roughly once every two to four days on one of eight instances. Each freeze costs about 12% of capacity and, before detection existed, 40 minutes of failed orders on that instance until someone noticed. After the lock-order fix and a stress test that drives both code paths 50,000 times in parallel, the freezes stop and the stress test fails within seconds if the old order is reintroduced.

🔍 What the interviewer is checking

Checks that the candidate can distinguish a deadlock from starvation, preserves evidence under pressure, reads a dump with the right SOS commands for both lock and async deadlocks, and fixes the design rather than adding restarts.

Green flags

  • Uses "never recovers, CPU near zero" to separate deadlock from starvation
  • Takes a full dump before restarting and handles it as sensitive data
  • Knows syncblk, clrstack, pstacks and dumpasync and what each shows
  • Fixes with lock ordering, no calls out under a lock, and timeouts
  • Adds a watchdog and a stress test that reproduces the cycle

Red flags

  • "Restart it and add a health check" as the full answer
  • Thinks ConfigureAwait(false) fixes deadlocks in ASP.NET Core
  • Can't explain why an async deadlock may show no blocked threads

📚 Learn in depth

1. The four conditions

A deadlock needs all four Coffman conditions: mutual exclusion (a resource only one holder can have), hold and wait (holding one while waiting for another), no pre-emption (nobody can take it away), and circular wait (a cycle). Break any one and the deadlock is impossible. In practice you break circular wait (lock ordering) or hold-and-wait (don't call out while holding a lock).

Thread 12                     Thread 31
  lock(stock)  ✓                lock(order)  ✓
  ...                           ...
  lock(order)  ← waits ──┐      lock(stock)  ← waits
                         └── cycle ──┘

2. How Monitor locks show up in a dump

A lock statement compiles to Monitor.Enter/Exit. The CLR stores lock state in the object header: a thin lock for the uncontended case, upgraded to a sync block entry when contended. syncblk lists those entries: the object, the owning thread and the waiter count. clrstack on each owner shows where it is stuck. Since .NET 9 the C# lock statement can also target System.Threading.Lock; SOS support for it differs from Monitor, so you may need clrstack -all and the source to see which Lock instance is held.

3. Async deadlocks don't hold threads

An async method waiting on SemaphoreSlim.WaitAsync() doesn't block a thread; it's a state machine object on the heap waiting for a continuation. So a frozen async service can show no blocked threads at all. dumpasync walks async state machines and shows what each is awaiting; you look for a pile of them awaiting the same semaphore or the same TaskCompletionSource.

The classic async deadlock in ASP.NET Core isn't the SynchronizationContext one (Core has no context); it's either a semaphore that was never released or blocking with .Result on work that needs the blocked resource.

4. Capturing safely

dotnet-dump collect --type Full suspends the process while it writes, which is fine because the process is frozen anyway. A full dump contains everything in memory, including tokens, connection strings and customer data, so store it encrypted with restricted access, record who opened it, and delete it after the investigation; treat it as personal information under the Privacy Act.

5. Detection

Deadlocks are silent: no exceptions, no CPU. Detect them with:

  • A stuck-request query: requests in progress for more than N minutes on one instance.
  • A watchdog in the health check that proves progress (for example, a background loop updates a timestamp; liveness fails if it's older than a minute). That converts a silent hang into a restart after a dotnet-monitor rule has taken a dump.

6. Making the bug reproducible

Deadlocks hide behind small timing windows. A stress test that runs both code paths in parallel thousands of times, optionally with Thread.Yield() injected inside the critical sections in a test build, turns a once-a-week freeze into a sub-second test failure.

Try it yourself

  1. Write two methods that lock a then b and b then a, call them in parallel in a loop, and wait for the console app to hang.
  2. Run dotnet-dump collect -p <pid> and in dotnet-dump analyze run syncblk, then setthread <id> and clrstack for each owner.
  3. Write an async version: a SemaphoreSlim(1) with a code path that throws before Release; call it twice and use dumpasync to find the waiter.
  4. Fix both: a fixed lock order in the first, try/finally in the second, and a stress test that fails on the old code.
  5. Add a watchdog health check and confirm liveness fails when the loop stops.

💻 Code

A lock-order deadlock and an async semaphore leak, and their fixes.

// Before: two code paths take the same locks in different orders.
namespace Orders.Fulfilment;

public sealed class StockLedger
{
    private readonly object _stockLock = new();
    private readonly object _orderLock = new();

    public void Reserve(Order o)
    {
        lock (_stockLock) { lock (_orderLock) { /* reserve */ } }   // stock -> order
    }

    public void Cancel(Order o)
    {
        lock (_orderLock) { lock (_stockLock) { /* release */ } }   // order -> stock: cycle
    }
}
// After: one documented order, and the async path always releases.
namespace Orders.Fulfilment;

public sealed record Order(Guid Id, string Sku, int Quantity);

public sealed class StockLedger
{
    // Lock order: _stockLock BEFORE _orderLock, everywhere. Enforced by this helper,
    // so no caller can take them in the other order.
    private readonly Lock _stockLock = new();
    private readonly Lock _orderLock = new();

    private void WithBoth(Action action)
    {
        lock (_stockLock)
        lock (_orderLock)
        {
            action(); // keep it short: no I/O, no callbacks, no awaits in here
        }
    }

    public void Reserve(Order o) => WithBoth(() => { /* reserve */ });
    public void Cancel(Order o) => WithBoth(() => { /* release */ });
}

public sealed class PartnerGate
{
    private readonly SemaphoreSlim _gate = new(1, 1);

    public async Task<T> RunAsync<T>(Func<CancellationToken, Task<T>> work, CancellationToken ct)
    {
        // A timeout turns a silent hang into an exception you can see and alert on.
        if (!await _gate.WaitAsync(TimeSpan.FromSeconds(10), ct))
            throw new TimeoutException("Partner gate wait exceeded 10 s");
        try { return await work(ct); }
        finally { _gate.Release(); } // released even when work throws
    }
}
# Capture and read the dump from the frozen instance
dotnet-dump collect -p 1 --type Full -o /tmp/frozen.dmp
dotnet-dump analyze /tmp/frozen.dmp
> syncblk                 # owners and waiters per lock
> setthread 12
> clrstack                # what thread 12 holds and waits for
> pstacks                 # group identical stacks
> dumpasync --waiting     # async state machines stuck on something

⚠ Common mistakes

  • Mistake: Restarting the frozen instance straight away. Why it is wrong: The dump is the only evidence, and the bug comes back in days. Instead: Drain, take a full dump, then restart.
  • Mistake: Treating it as ThreadPool starvation and raising MinThreads. Why it is wrong: Starvation recovers when load drops; a deadlock never does, and more threads can't break a cycle. Instead: Look for a cycle with syncblk or stuck awaits with dumpasync.
  • Mistake: Nesting locks casually, or taking several locks in whatever order the code happens to need them. Why it is wrong: Every extra lock multiplies the possible orderings, and one path taking them in a different order is enough for a cycle. Instead: Avoid nested locks; if you must, document one order and enforce it through a single helper.
  • Mistake: Calling external code, logging sinks, events or await inside a lock. Why it is wrong: You can't control what locks that code takes, so you create hidden cycles. Instead: Copy the data out, release the lock, then call out.
  • Mistake: Blocking on async work with .Result, .Wait() or GetAwaiter().GetResult() inside code that other async work depends on. Why it is wrong: The blocked thread or held resource may be exactly what the awaited task needs to finish, so neither side progresses. Instead: Await all the way up.
  • Mistake: SemaphoreSlim.Release() outside a finally. Why it is wrong: One exception leaves the semaphore at zero and every later caller waits forever. Instead: try/finally around the protected work.
  • Mistake: Waiting without a timeout. Why it is wrong: A hang produces no exception, log or metric. Instead: Use WaitAsync(timeout, ct) or Monitor.TryEnter with a timeout on paths where a stall is worse than an error.
  • Mistake: Adding an auto-restart-on-hang script as the fix. Why it is wrong: It hides a correctness bug and destroys evidence each time. Instead: Capture a dump on hang automatically, then restart.
  • Mistake: Leaving full dumps in a shared folder. Why it is wrong: They contain secrets and personal data. Instead: Encrypted storage, restricted access, deletion after the RCA.

🏛 Senior insight: trade-offs

Intermittent deadlocks are where good process beats heroics. The fix is usually ten lines; the hard part is getting one good dump. So the senior investment is in automation: a progress watchdog, a dotnet-monitor rule that dumps on hang, and a runbook step that says "dump before restart". After the fix, a stress test that reproduces the old cycle in seconds is the proof, and it protects the fix from being undone in a future refactor.

I also push teams away from fine-grained locking in application code. Most business services shouldn't need two locks at all: a single lock, an actor-style Channel<T> consumer, or optimistic concurrency in the database usually removes the possibility of a cycle.

Option When it fits Cost When not to
One global lock order Two or more locks genuinely needed Discipline, documentation When one lock would do
Single lock or Channel<T> consumer In-process shared state Less parallelism Very hot paths needing fine-grained locks
Optimistic concurrency in the database State that lives in SQL anyway Retries on conflict High-contention rows (then queue the work)
Wait timeouts Async gates, external resources Callers handle timeouts Inside tight in-memory critical sections

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions both lock and async deadlocks Why: Checks the internals of diagnosing deadlocks from locks and from async code
    How to answer

    A deadlock is a cycle where each participant waits for something another holds, so nothing progresses and CPU drops to zero. In .NET the common kinds are lock-ordering deadlocks (thread A holds lock 1 and wants lock 2, thread B the reverse), sync-over-async deadlocks on a SynchronizationContext, non-reentrant SemaphoreSlim re-entry, and tasks that are never completed. I diagnose with a memory dump: dotnet-dump collect, then syncblk to see Monitor owners and waiters, clrstack -all or parallelstacks for thread stacks, and dumpasync for stuck async chains. Fixes are a consistent lock order, shorter locks with no callouts, timeouts, and async all the way.

  2. When: Candidate says 'I take a dump' Why: Checks how to capture and analyse a dump safely in production
    How to answer

    When I can't attach a debugger, I take a dump: a snapshot of the process's memory, threads and stacks that I analyse offline. For a hang or a leak, dotnet-dump collect -p <pid> does it in seconds. For crashes, I enable automatic crash dumps with the DOTNET_DbgEnableMiniDump environment variables. On App Service I use Diagnose and solve problems, and in Kubernetes dotnet-monitor. Then I analyse with dotnet-dump analyze: clrstack -all and syncblk for hangs, dumpheap -stat and gcroot for leaks, pe for exceptions. Or I open the dump in Visual Studio and use the Threads and Parallel Stacks windows. Dumps contain customer data, so they're handled as sensitive.

  3. When: Candidate confuses the symptom with high latency under load Why: Checks the difference between a deadlock and ThreadPool starvation
    How to answer

    High latency with low CPU under load is the signature of ThreadPool starvation: threads are blocked waiting on I/O (usually sync-over-async like .Result or .Wait()), so queued work items wait for a thread, and the pool only injects new threads slowly (roughly one or two a second beyond the minimum). In Kubernetes it gets worse because health probes wait on the same pool, fail, and the restarts push more load onto the survivors. I mitigate first: relax the liveness probe, scale out and shed load; raising MinThreads is a bandage that buys time. I confirm with dotnet-counters (rising threadpool-queue-length) and a dump (pstacks showing hundreds of threads in Task.Wait). The fix is async all the way down; more threads only hide it.

🛠 Real-world problems: how you handle them

An order service that froze every few days
Situation
An order fulfilment service on [AKS, eight pods] handling [about 300 requests/s]. Roughly every [two to four days], one pod stopped responding until someone restarted it. Each freeze failed [hundreds] of orders before it was noticed.
Signals
A stuck-request KQL query showed requests on one `cloud_RoleInstance` in progress for over 10 minutes. That pod's CPU was near zero; the others were normal. `dotnet-counters` showed the ThreadPool queue growing and no throughput. No exceptions were logged.
Investigation
Drained the pod by removing its Service label, then ran `dotnet-dump collect --type Full` in an ephemeral debug container. `syncblk` showed two locks with waiters, owned by threads 12 and 31. `clrstack` showed thread 12 in `Reserve` holding the stock lock and waiting for the order lock, and thread 31 in `Cancel` holding the order lock and waiting for the stock lock.
Resolution
Immediate: deleted the frozen pod after the dump. Real fix: one lock order through a shared helper, slow work moved outside the locked region, and the cancellation path rewritten to call the shared helper.
Prevention
A stress test running `Reserve` and `Cancel` in parallel 50,000 times; a progress watchdog in the liveness probe paired with a dotnet-monitor rule that captures a dump before the restart; a stuck-request alert; and a review checklist item: no I/O, callbacks or awaits inside a lock.

How to tell it (STAR)

**S:** At [company], one pod of our order service froze every few days and only a restart fixed it, so we kept losing orders without knowing why. **T:** I took ownership of finding the cause instead of adding another restart script. **A:** The next time it froze, I drained the pod and took a full dump before restarting it. `syncblk` showed two locks each held by a different thread, and `clrstack` showed reservation and cancellation taking them in opposite orders. I put both behind one helper with a fixed order, moved slow work out of the lock, and added a stress test that reproduces the old cycle in seconds. **R:** The freezes stopped completely over [the next six months], we stopped losing [about 40 minutes] of orders per freeze, and the watchdog plus dump rule now give us evidence automatically if anything hangs.

More in Debugging Production Issues

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me