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.
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.
"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.clrstackon 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
Monitorlocks, butpstacksshows threads parked inTask.Waitor nothing at all, anddumpasyncshows state machines waiting on aSemaphoreSlimthat will never be released, often because an exception skipped theRelease. 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."
| 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-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 |
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.
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
syncblk, clrstack, pstacks and dumpasync and what each showsRed flags
ConfigureAwait(false) fixes deadlocks in ASP.NET CoreA 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 ──┘
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.
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.
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.
Deadlocks are silent: no exceptions, no CPU. Detect them with:
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.
a then b and b then a, call them in parallel in a loop, and wait for the console app to hang.dotnet-dump collect -p <pid> and in dotnet-dump analyze run syncblk, then setthread <id> and clrstack for each owner.SemaphoreSlim(1) with a code path that throws before Release; call it twice and use dumpasync to find the waiter.try/finally in the second, and a stress test that fails on the old 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
syncblk or stuck awaits with dumpasync.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..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.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.WaitAsync(timeout, ct) or Monitor.TryEnter with a timeout on paths where a stall is worse than an error.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.