An incident playbook for ThreadPool starvation under load: the low-CPU signature, the probe-restart death spiral, confirming with dotnet-counters and a dump, emergency mitigations such as SetMinThreads, finding sync-over-async and preventing it.
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.
"CPU at 20% while latency goes to 30 seconds tells me the machines aren't busy, they're waiting. When that happens under load in ASP.NET Core, my first suspect is ThreadPool starvation. Requests run on pool threads; if code blocks a thread on I/O, for example
httpClient.GetAsync(...).Result, that thread is stuck until the I/O finishes. Under load, all threads are blocked, new work queues up, and the pool's hill-climbing only adds threads slowly. The probes run on the same pool, so they time out, Kubernetes restarts the pod, and the remaining pods get even more traffic. That's the death spiral.For example, at [company] during [a sale], I saw exactly this. In the first minutes I stopped the restarts by relaxing the liveness probe, scaled out, and turned on load shedding for non-critical endpoints. As a bandage, I raised the minimum worker threads through configuration so the pool could absorb the blocking. Then I confirmed it:
dotnet-countersshowedthreadpool-queue-lengthin the thousands and thread count creeping up by about one a second. A dump withdotnet-dump analyzeandpstacksshowed [several hundred] threads with the same stack:Task.Waitunder a token service that called an async method with.Resultinside a synchronous DI factory. We made the path async, the queue length went to zero, and p95 went back to [110 ms].The mistake I see is leaving
SetMinThreadsin as the fix. It's a tourniquet: blocked threads still cost memory and context switches, and the next traffic spike blows past whatever number you picked."
| Step | What I do | Tool or command |
|---|---|---|
| 1. Symptom | Latency up, CPU low, probes failing, restarts | App Insights, kubectl get pods -w, node CPU |
| 2. First five minutes | Relax liveness, scale out, shed load, raise MinThreads | Deployment patch, HPA, rate limiter or feature flag, DOTNET_ThreadPool_ForceMinWorkerThreads or runtimeconfig.json |
| 3. Data to collect | Pool counters, then a dump from a starved pod | dotnet-counters, dotnet-dump collect |
| 4. Rule out | Slow dependency (traces show a fast dependency but a long gap before the call starts), GC (low GC time), CPU throttling | App Insights end-to-end transaction, counters |
| 5. Root cause | The common blocking stack | clrthreads, pstacks, clrstack -all |
| 6. Fix | Async all the way; remove .Result/.Wait() |
Code change |
| 7. Prevention | Analysers, load test, queue length alert, probe design | Pipeline, Azure Monitor |
| Signal | ThreadPool starvation | Slow dependency | CPU saturation | Deadlock |
|---|---|---|---|---|
| CPU | Low | Low | High | Near zero |
threadpool-queue-length |
Growing | Low | Moderate | Growing if requests keep arriving |
| Thread count | Creeping up | Stable | Stable | Stable or creeping |
| Dependency duration in traces | Normal, but starts late | Long | Normal | Calls never start |
| Recovers when load drops | Yes, slowly | When the dependency recovers | Yes | No |
| Mitigation | Effect | Cost |
|---|---|---|
| Relax liveness probe (longer timeout, more failures) | Stops the restart spiral | Slower detection of a truly dead pod |
| Scale out | Fewer requests per pod | Spend; doesn't fix blocking |
| Shed load (rate limiter, disable non-critical endpoints) | Protects the core path | Some users get 429 or a degraded page |
| Raise min worker threads | Pool absorbs blocking immediately | More memory and context switching; masks the bug |
In a typical case, a token-caching service is registered with a factory that calls GetTokenAsync().Result. At 50 requests/s nobody notices. At 600 requests/s during a sale, threadpool-queue-length climbs past 3,000, p95 hits 30 seconds and liveness failures restart four of ten pods in five minutes. Raising min worker threads to 200 brings p95 down to 2 seconds within minutes; making the factory async and moving token refresh to a background service brings it to 110 ms at the same load.
Checks that the candidate recognises starvation from its signature, can stop the platform from amplifying it during an incident, can prove it with counters and a dump, and knows the real fix is removing blocking rather than adding threads.
Green flags
Red flags
The .NET ThreadPool keeps a minimum number of worker threads (by default, the processor count the runtime sees). Up to the minimum, it creates threads on demand immediately. Above the minimum, a hill-climbing algorithm adds threads gradually, and a starvation detector injects roughly one or two threads per second when it sees queued work and no progress. This is deliberate: creating threads freely would waste memory (each has a stack) and cause context-switch storms. It also means a burst of blocking work outruns the injection rate.
incoming requests ──► global queue ──► worker threads (min = cores)
│
blocked in .Result ┘ (waiting for I/O that needs...)
│
I/O completion ────┘ ...a pool thread to run its continuation
That last line is the trap: the continuation of the async call you're blocking on also needs a pool thread. With every thread blocked, completions queue behind requests, and throughput collapses.
Blocked threads don't use CPU; they sit in a kernel wait. So the box looks idle while requests wait seconds in the queue. Any time latency rises and CPU doesn't, think waiting: starvation, locks, a slow dependency, or throttling.
Kestrel accepts the probe request, but the endpoint runs on the same starved pool, so /healthz times out after the probe's timeoutSeconds. After failureThreshold failures, the kubelet kills the container. Traffic moves to fewer pods, which starve faster. Two design rules help: keep liveness trivial (is the process alive?) with generous thresholds, and put dependency checks in readiness, which removes a pod from rotation instead of killing it.
> clrthreads # how many managed threads, which are pool workers
> pstacks # groups identical stacks: one stack x 400 threads is your culprit
> clrstack -all # full detail if needed
> threadpool # in recent SOS: queue length, worker counts
A starvation dump shows hundreds of threads in System.Threading.Tasks.Task.SpinThenBlockingWait or ManualResetEventSlim.Wait, called from your code via .Result, .Wait() or GetAwaiter().GetResult().
sp => new Client(GetTokenAsync().Result)) because factories are synchronous.IOptions validation or IConfigureOptions that call async APIs.HttpWebRequest).lock around code that waits on a task.ThreadPool.SetMinThreads(workers, iocp) at startup, or System.Threading.ThreadPool.MinThreads in runtimeconfig.json, or the DOTNET_ThreadPool_ForceMinWorkerThreads environment variable (hex value). It takes effect without a rebuild if you use configuration. Record it as a temporary change with an owner and a date to remove it.
Task.Delay(500).Wait() and another that does await Task.Delay(500). Load both with k6 at 200 virtual users and compare throughput.dotnet-counters monitor --counters System.Runtime[threadpool-queue-length,threadpool-thread-count] during the blocking test and note the injection rate.dotnet-dump collect during the test and run pstacks.System.Threading.ThreadPool.MinThreads to 200 in runtimeconfig.template.json, repeat, and note that it helps but costs memory.The sync-over-async that starves the pool, and the fix.
// Before: a synchronous DI factory blocks a pool thread on every resolve.
// builder.Services.AddScoped<IPartnerClient>(sp =>
// {
// var tokens = sp.GetRequiredService<ITokenService>();
// var token = tokens.GetTokenAsync(CancellationToken.None).Result; // blocks under load
// return new PartnerClient(sp.GetRequiredService<HttpClient>(), token);
// });
// After: the token is fetched asynchronously by a DelegatingHandler at call time,
// so nothing blocks during DI resolution.
namespace Checkout.Partners;
using System.Net.Http.Headers;
public interface ITokenService
{
ValueTask<string> GetTokenAsync(CancellationToken ct);
}
public sealed class BearerTokenHandler(ITokenService tokens) : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
var token = await tokens.GetTokenAsync(ct); // async, cached in the service
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
return await base.SendAsync(request, ct);
}
}
public sealed class PartnerClient(HttpClient http)
{
public async Task<Quote?> GetQuoteAsync(string sku, CancellationToken ct) =>
await http.GetFromJsonAsync<Quote>($"quotes/{Uri.EscapeDataString(sku)}", ct);
}
public sealed record Quote(string Sku, decimal Price);
// Program.cs
// builder.Services.AddSingleton<ITokenService, CachedTokenService>();
// builder.Services.AddTransient<BearerTokenHandler>();
// builder.Services.AddHttpClient<PartnerClient>(c => c.BaseAddress = new("https://partner.example/"))
// .AddHttpMessageHandler<BearerTokenHandler>()
// .AddStandardResilienceHandler();
# Confirm during the incident
dotnet-counters monitor -p 1 --counters System.Runtime[threadpool-queue-length,threadpool-thread-count,cpu-usage]
dotnet-dump collect -p 1 -o /tmp/starved.dmp
dotnet-dump analyze /tmp/starved.dmp # then: clrthreads, pstacks, threadpool
# Temporary bandage via config (hex value: 0xC8 = 200 threads), remove after the fix
kubectl set env deployment/checkout-api DOTNET_ThreadPool_ForceMinWorkerThreads=C8 -n prod
SetMinThreads as the fix. Why it is wrong: It hides blocking that will return at a higher load, and each blocked thread costs memory and context switches. Instead: Use it as a dated bandage while you remove the blocking.Task.Run and awaiting it. Why it is wrong: It still blocks a pool thread, just a different one. Instead: Use true async APIs end to end.ConfigureAwait(false) everywhere to cure it. Why it is wrong: ConfigureAwait(false) avoids resuming on a captured SynchronizationContext, which prevents the classic UI or legacy ASP.NET deadlock; ASP.NET Core has no such context, so it does nothing for a thread that is blocked in .Result. Instead: Remove the blocking call itself.Starvation is a design bug that only shows at scale, which is why it surfaces during sales and launches. The senior response has two layers: stop the spiral quickly with operational levers, then remove the class of bug with tooling (analysers, banned APIs, load tests) so it doesn't depend on reviewers spotting .Result.
The point most candidates miss is that the platform can amplify the failure: liveness probes, retries from clients and autoscalers that add pods slowly all interact. Designing probes and load shedding is part of fixing starvation.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Raise MinThreads | Emergency, blocking code you can't change today | Memory, context switches, hides the bug | As a permanent setting without a removal date |
| Async all the way | Always the real fix | Refactoring, sometimes library upgrades | Never skip it |
| Bulkhead for a blocking legacy call | A sync-only SDK you can't replace yet | A dedicated thread or limiter to manage | When an async API exists |
| Load shedding | Protecting the core path during a spike | Some users see 429 or degraded pages | When every endpoint is critical (then scale and fix) |
ThreadPool starvation happens when pool threads are blocked faster than the pool can add new ones, so queued work (requests, continuations, timers) waits. Symptoms: latency rises sharply while CPU stays low, the pool queue length grows, thread count climbs slowly, health checks time out and Kestrel logs heartbeat warnings mentioning possible starvation. I confirm it with dotnet-counters (queue length and thread count), then take dotnet-stack snapshots or a dump to see what the threads are blocked on, usually .Result, .Wait(), synchronous I/O or locks. The fix is to make that code asynchronous; raising SetMinThreads only buys time.
Sync-over-async is synchronously blocking on asynchronous work: .Result, .Wait(), GetAwaiter().GetResult() or Task.WaitAll. It holds a thread for the whole operation, causes ThreadPool starvation on servers and deadlocks under a SynchronizationContext. It sneaks in through constructors, DI factory lambdas, property getters, Dispose, lock blocks, synchronous interfaces (IComparer, old filters), static initialisers and "quick fixes" in legacy code. Remove it by making the call chain async, using async factory methods or lazy async initialisation, IAsyncDisposable, hosted-service warm-up, and async-capable interfaces. Where a sync boundary is unavoidable (for example a legacy interface), keep it at the edge and document it.
The ThreadPool is a process-wide set of reusable background threads that run queued work items: Task.Run, async continuations, timer callbacks and ASP.NET Core requests. Work goes into a global queue or, when queued from a pool thread, into that thread's local queue, and idle threads steal from others. The pool starts up to minimum threads (default: processor count) immediately on demand; above that it adds threads gradually, using a hill-climbing algorithm that measures throughput plus a starvation detector that injects threads when queued work is not progressing. That gradual injection is why blocking pool threads causes latency spikes.
How to tell it (STAR)
**S:** At [company], during [our biggest sale of the year], checkout latency went from 100 ms to 30 seconds while CPU sat at 20%, and Kubernetes started restarting pods. **T:** I was the senior on call and had to stop the bleeding, then find the cause. **A:** I relaxed the liveness probe to stop the restart spiral, scaled out, turned off a non-critical feature and raised the ThreadPool minimum as a bandage. dotnet-counters showed thousands of queued work items, and a dump showed 400 threads blocked in `.Result` inside a DI factory that fetched a token. We moved the token fetch into an async handler and banned blocking calls with an analyser. **R:** p95 came back to [110 ms] at [600 requests/s], we lost about [20 minutes] of degraded checkout instead of the whole sale, and the analyser has blocked [several] similar changes since.
Last updated 23 Nov 2026.