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

📚 Interview question

During a sale, your ASP.NET Core API's response times jump from 100 ms to 30 seconds, health probes start failing and Kubernetes restarts pods, which makes it worse, yet CPU sits at 20%. How do you confirm it's ThreadPool starvation, stop the bleeding during the incident, find the blocking code, and make sure it doesn't happen again?

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.

Senior Debugging Advanced aspnet-core dotnet-counters kubernetes production sync-over-async threadpool-starvation

🎯 Key points

  • Signature: latency climbs, CPU low, threadpool-queue-length growing; thread count rises only at the injection rate (about 1–2 per second above the minimum)
  • Probes on the same starved pool fail, Kubernetes restarts pods, survivors get more load: a death spiral
  • Mitigate: relax liveness probes, scale out, shed load; raising MinThreads is a temporary bandage with a removal date, never the fix
  • Confirm: dotnet-counters threadpool-queue-length and thread-count; dotnet-dump clrthreads and pstacks show many threads blocked in Task.Wait or .Result
  • Root cause is usually sync-over-async: .Result, .Wait(), GetAwaiter().GetResult() or a sync API on an I/O path, in DI factories, constructors, options setup or startup code
  • Rule out a slow dependency: traces show the dependency call is fast but starts late
  • Fix: async all the way, async-only clients, no blocking in constructors or DI factories
  • Prevent: threading analysers and banned APIs, load tests at peak, alert on queue length, separate liveness from readiness

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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-counters showed threadpool-queue-length in the thousands and thread count creeping up by about one a second. A dump with dotnet-dump analyze and pstacks showed [several hundred] threads with the same stack: Task.Wait under a token service that called an async method with .Result inside 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 SetMinThreads in 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."


The playbook, in order

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

Telling starvation from look-alikes

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

Mitigations and their cost

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

Production example

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.

🔍 What the interviewer is checking

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

  • Reads "high latency, low CPU" as waiting, and names starvation
  • Explains the hill-climbing injection rate and the probe death spiral
  • Mitigates with probes, scaling, shedding and a temporary MinThreads change
  • Confirms with threadpool-queue-length and pstacks
  • Fixes with async end to end and prevents with analysers and load tests

Red flags

  • "Add more CPU" or "add more pods" as the fix
  • Leaves SetMinThreads in place as the solution
  • Thinks ConfigureAwait(false) solves it in ASP.NET Core

📚 Learn in depth

1. How the ThreadPool decides how many threads to run

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.

2. Why CPU stays low

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.

3. The probe death spiral

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.

4. Reading the dump

> 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().

5. Where sync-over-async hides

  • DI factory delegates (sp => new Client(GetTokenAsync().Result)) because factories are synchronous.
  • Constructors that load configuration or tokens.
  • IOptions validation or IConfigureOptions that call async APIs.
  • Synchronous library APIs that block internally (older SDKs, HttpWebRequest).
  • Logging providers or sinks that write synchronously to the network.
  • lock around code that waits on a task.

6. Setting the minimum, safely, as a bandage

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.

Try it yourself

  1. Create an endpoint that does Task.Delay(500).Wait() and another that does await Task.Delay(500). Load both with k6 at 200 virtual users and compare throughput.
  2. Watch dotnet-counters monitor --counters System.Runtime[threadpool-queue-length,threadpool-thread-count] during the blocking test and note the injection rate.
  3. Take a dump with dotnet-dump collect during the test and run pstacks.
  4. Set System.Threading.ThreadPool.MinThreads to 200 in runtimeconfig.template.json, repeat, and note that it helps but costs memory.
  5. Run the blocking test in a pod with a liveness probe pointing at a normal endpoint and watch the restarts start.

💻 Code

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

⚠ Common mistakes

  • Mistake: Treating 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.
  • Mistake: Scaling up CPU because the API is slow. Why it is wrong: CPU isn't the bottleneck; threads are waiting. Instead: Read the ThreadPool counters first.
  • Mistake: Putting dependency checks in the liveness probe. Why it is wrong: A slow dependency or starved pool turns into restarts and a death spiral. Instead: Keep liveness trivial; use readiness for dependencies.
  • Mistake: Wrapping blocking code in 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.
  • Mistake: Adding 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.
  • Mistake: Expecting the thread count to explode. Why it is wrong: Above the minimum the pool injects threads slowly, so starvation shows as a long queue with a slowly rising (or capped) thread count. Instead: Watch queue length, not just thread count.
  • Mistake: Only testing at average load. Why it is wrong: Starvation appears when the arrival rate outruns thread injection, so it only shows at peak. Instead: Load test at sale-day peak with a ramp.
  • Mistake: Restarting pods to clear it. Why it is wrong: The new pods starve the same way as soon as traffic returns. Instead: Stop the spiral, then remove the blocking.

🏛 Senior insight: trade-offs

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)

🔗 Follow-ups the interviewer may ask

  1. When: Candidate names ThreadPool starvation Why: Checks the internals of recognising and diagnosing starvation
    How to answer

    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.

  2. When: Candidate says the cause was .Result or .Wait() Why: Checks where sync-over-async hides and how to remove it
    How to answer

    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.

  3. When: Candidate mentions thread injection or hill climbing Why: Checks understanding of how the ThreadPool sizes itself
    How to answer

    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.

🛠 Real-world problems: how you handle them

Sale-day starvation from a blocking token factory
Situation
A checkout API on AKS, [ten] pods, normally [80 requests/s], expected [600 requests/s] during [an end-of-financial-year sale]. A partner shipping client was registered with a DI factory that fetched an OAuth token synchronously.
Signals
p95 went from [100 ms] to [30 s] within minutes of the sale starting. Node CPU stayed around 20%. Liveness probes failed and four pods restarted in five minutes. Application Insights showed dependency calls to the partner taking [150 ms] but starting seconds after the request began.
Investigation
Ran `dotnet-counters` on a live pod: `threadpool-queue-length` above [3,000], thread count growing by about one a second. Captured a dump with `dotnet-dump collect`; `pstacks` showed [about 400] threads in `Task.Wait` under the DI factory for `PartnerClient`. Ruled out the partner with traces (fast once started) and GC with counters (under 5%).
Resolution
Immediate: patched the liveness probe to a longer timeout and higher failure threshold, scaled to [20] pods, disabled recommendations with a feature flag, and set `DOTNET_ThreadPool_ForceMinWorkerThreads` to 200. Real fix: moved token acquisition to an async `DelegatingHandler` with a cached token service and redeployed the next morning.
Prevention
Turned on the Microsoft.VisualStudio.Threading analysers as errors, banned `.Result` and `.Wait()` with BannedApiAnalyzers, added a peak-load test stage at 1.5 times forecast, split liveness from readiness, alerted on `threadpool-queue-length`, and removed the MinThreads override with a tracked ticket.

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.

↩ Usually asked after

More in Debugging Production Issues

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me