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

📚 Interview question

Tell me about a time requests hung under load while CPU stayed low. What did you see, how did you work out it was ThreadPool starvation (or something else), how did you stop the bleeding, and what did you change in the code and the platform afterwards?

A STAR story for ThreadPool starvation: the low-CPU hang signature, confirming it with dotnet-counters and a dump, mitigation, removing sync-over-async, and prevention.

Senior RealWorldScenario Advanced aspnet-core dotnet-counters real-world star-story sync-over-async threadpool-starvation

🎯 Key points

  • Signature: p95 (the response time 95% of requests beat) jumps, throughput flat, CPU low, thread count climbing slowly
  • Confirmed with dotnet-counters: ThreadPool queue length sustained above ~100 (healthy is near 0) and threads added ~1-2 per second
  • Dump with dotnet-dump + pstacks: hundreds of threads on the same .Result / .Wait() / GetResult() frame
  • Ruled out database, deadlock and connection-pool exhaustion with traces and APM (Application Insights or New Relic / Dynatrace)
  • Mitigated: scale out, temporary ThreadPool minimum threads, stop probe-induced restart storms
  • Real fix: await all the way, async APIs (GetStringAsync with CancellationToken), cache the dependency
  • Prevention: VSTHRD analysers as errors, load test with injected latency, queue-length alert; before/after numbers

⏱ 30-second answer

The signature I describe is p95 latency (the time 95% of requests finish within) through the roof with CPU low: requests weren't doing work, they were waiting for a thread. dotnet-counters showed ThreadPool queue length in the thousands (healthy is close to zero) and the thread count creeping up about one or two a second, which is the pool's injection rate. A dotnet-dump showed hundreds of threads parked in .Result on an HTTP call: sync-over-async, where synchronous code blocks a pool thread waiting for an async call's result. It sat in [a helper that fetched a signing key]. I mitigated by scaling out and temporarily raising the minimum threads, then made the path await end to end, added analysers and a load test. Result: [p95 from 30 s to 120 ms]. The trade-off: raising min threads buys time but hides the bug and costs memory, so it's a tourniquet, not the fix.

🗣 Full answer (senior)

How I would answer this in an interview

"At [company] our [checkout API] ran on [AKS], [six] pods. During [a sale] response times went from about [100 ms] to [30 seconds], health probes started failing, and Kubernetes restarted pods, which made it worse. The odd thing was CPU sat around [20%]. Low CPU and huge latency means requests are waiting, not working.

I ran dotnet-counters on one pod: ThreadPool queue length was in the [thousands] and thread count was climbing slowly, about one or two threads a second. That pattern is starvation: work is queued, and the pool is adding threads at its injection rate because existing ones are blocked. A dotnet-dump and clrstack -all showed [300] threads blocked in GetAwaiter().GetResult() inside [a helper that fetched a signing key over HTTP]. It had been fine at normal load because the call usually took [5 ms]; during the sale the downstream got slower, each blocked thread was held longer, and the pool couldn't keep up.

To stop the bleeding I scaled to [12] pods, raised the minimum worker threads to [200] through configuration, and relaxed the liveness probe so it stopped killing pods that were recovering. Within [ten] minutes p95 was back under [300 ms]. Then I made the helper async end to end, cached the key, and turned on the Microsoft.VisualStudio.Threading analysers as errors. We added a load test that injects downstream latency and an alert on ThreadPool queue length. The next sale ran at [2x] the traffic with p95 at [120 ms]. The lesson: a blocking call is harmless until the thing it waits on gets slow."


Diagnosis: what low CPU plus high latency can mean

Cause Distinguishing signal Confirm with
ThreadPool starvation Queue length high, thread count climbing slowly, CPU low dotnet-counters, dump with many threads in .Result/.Wait()
Deadlock Instance stops completely, never recovers, no thread growth needed dotnet-dump syncblk, clrstack
Slow dependency Dependency duration up in traces; threads not blocked if code is async Application Insights dependencies
Connection pool exhaustion InvalidOperationException pool timeout, SQL pool counters at max Microsoft.Data.SqlClient counters
Lock contention monitor-lock-contention-count high dotnet-counters, dotnet-trace

Mitigation options during the incident

Option Effect Risk
Scale out More pools, less load per pool Cost; database may become the bottleneck
ThreadPool.SetMinThreads / System.Threading.ThreadPool.MinThreads Threads injected immediately instead of slowly More memory, context switching; hides the bug
Relax liveness probe Stops restart storms Truly dead pods stay longer
Shed load / rate limit Protects healthy requests Some users rejected

Production example

Template: [checkout API], [6] pods, p95 [100 ms] → [30 s] at [3x] normal traffic with CPU [20%]; queue length [4,000+]; [300] threads blocked in .Result; mitigated in [10] min; after the async fix the next sale at [2x] traffic held p95 at [120 ms].

🔍 What the interviewer is checking

Checks whether you can recognise ThreadPool starvation from its signature, prove it with runtime evidence, mitigate safely, and remove the blocking cause for good.

Green flags

  • "Low CPU with high latency means waiting" deduction
  • Names queue length, injection rate and grouped stacks in a dump
  • Treats min threads as a tourniquet; fixes the blocking call
  • Mentions probes and autoscaling behaviour, and gives numbers

Red flags

  • "We added more servers" as the whole story
  • Task.Run or SetMinThreads as the fix
  • Can't explain why it only happened under load
  • No measured result

📚 Learn in depth

1. What the interviewer is really assessing

ThreadPool starvation is the classic senior .NET incident. The interviewer checks whether you know why low CPU and high latency point to starvation, whether you can prove it rather than guess, and whether you fix the cause (blocking) rather than the symptom (thread count). They also look for platform awareness: probes and autoscaling can turn a slowdown into an outage.

2. The mechanism

Request arrives -> work item queued -> ThreadPool worker picks it up
                                         |
                          code calls httpClient.GetAsync(...).Result
                                         |
                          worker BLOCKS waiting for the I/O completion
                                         |
             completion continuation is queued... but needs a free worker
                                         |
          all workers blocked -> queue grows -> pool injects ~1-2 threads/sec

The ThreadPool starts with a minimum number of threads (by default the processor count) and above that uses hill climbing plus a starvation detector that adds threads gradually. Sync-over-async is doubly bad: the blocked thread waits for a continuation that itself needs a pool thread. Since .NET 6 the pool has some mitigation for blocking on tasks, but under a burst it still can't inject threads fast enough.

3. The evidence

  • dotnet-counters monitor -p <pid> --counters System.Runtime: threadpool-queue-length, threadpool-thread-count, threadpool-completed-items-count.
  • dotnet-dump collect then clrstack -all or parallelstacks (pstacks) to group identical stacks: hundreds of threads on the same .Result frame is the smoking gun.
  • Application Insights: server response time rises while dependency time doesn't account for it.

4. Frameworks for telling it

Use STAR. The most memorable part is the deduction ("low CPU means waiting, not working"), so put it early in the Action. For a 60-second CAR version: context (sale, latency), action (counters, dump, async fix), result (numbers).

5. How it is scored

Weak: "we scaled up and it went away." Good: names counters and blocking. Strong: explains the injection rate and why it only broke under load. Excellent: adds analysers, load tests with injected latency, alerting, and reflects on probes and autoscaling.

6. Adapting the story

The same story answers "a time you diagnosed something others couldn't", "a time under pressure", and "a time you improved engineering standards" (lead with the analysers rule). For a non-technical audience: "The servers weren't busy, they were all waiting on one slow call. I found the call, changed it so servers don't wait, and the next sale handled twice the traffic."

Try it yourself

  1. Build a minimal API endpoint that calls HttpClient.GetAsync(...).Result against an endpoint that delays 500 ms.
  2. Load it with bombardier or k6 at 200 concurrent users and watch dotnet-counters.
  3. Take a dump and run pstacks to see the grouped blocked stacks.
  4. Make it async and repeat; compare throughput and thread count.
  5. Add Microsoft.VisualStudio.Threading.Analyzers and see which warnings fire.
  6. Write and time your STAR version.

💻 Code

The key fix in this example: a blocking helper made async and cached.

namespace Checkout.Security;

// Before (starvation under load): every request blocked a pool thread on HTTP.
// public string GetSigningKey() =>
//     _http.GetStringAsync("/keys/current").GetAwaiter().GetResult();

public sealed class SigningKeyProvider(HttpClient http, HybridCache cache)
{
    // After: async end to end, and cached so the downstream isn't on the hot path.
    public ValueTask<string> GetSigningKeyAsync(CancellationToken ct) =>
        cache.GetOrCreateAsync(
            "signing-key:current",
            async token => await http.GetStringAsync("/keys/current", token),
            new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(10) },
            cancellationToken: ct);
}
// Temporary mitigation only (runtimeconfig / env DOTNET_ThreadPool_MinThreads is NOT a fix)
{
  "configProperties": {
    "System.Threading.ThreadPool.MinThreads": 200
  }
}
STAR template
S: [Service] on [platform], [traffic], during [event].
T: Latency hit [X s] with CPU at [Y%]; I was [on call / incident lead].
A: Counters showed [queue length]; dump showed [N] threads blocked in [call];
   mitigated with [scale-out, min threads, probe change]; fixed with [async + cache]; added [analysers, load test, alert].
R: p95 back to [X ms] in [N min]; next peak at [2x] traffic held p95 at [Y ms].

Illustrative only: checkout API, sale traffic, 300 threads blocked on a key-fetch helper;
async + cache fix; next sale 2x traffic at 120 ms p95.

⚠ Common mistakes

  • Mistake: Saying "the server was overloaded". Why it is wrong: Low CPU proves it wasn't doing work. Instead: Explain that threads were blocked waiting.
  • Mistake: Presenting SetMinThreads as the fix. Why it is wrong: It hides blocking and costs memory and context switches. Instead: Call it a temporary mitigation and remove the blocking call.
  • Mistake: Wrapping the sync call in Task.Run. Why it is wrong: It still blocks a pool thread, just a different one. Instead: Use a truly async API.
  • Mistake: Fixing only the one call site. Why it is wrong: Async has to flow all the way up; one sync method in the chain (a sync interface, a constructor, a sync filter) puts the blocking back. Instead: await from controller to I/O, pass the CancellationToken, use async overloads (GetStringAsync(url, ct), ToListAsync(ct)), make interfaces return Task/ValueTask, and move async initialisation out of constructors into a factory or hosted service.
  • Mistake: Ignoring the liveness probe restarts. Why it is wrong: Restart storms turn a slowdown into an outage. Instead: Mention fixing probe settings and separating liveness from readiness.
  • Mistake: No evidence: "we guessed it was async". Why it is wrong: Seniors prove it. Instead: Queue length, thread injection, grouped stacks.
  • Mistake: Talking only about the team. Why it is wrong: Your contribution disappears. Instead: "I ran the counters, I found the stack."
  • Mistake: Too much jargon for a non-technical interviewer. Why it is wrong: They score clarity. Instead: Use the "waiting, not working" analogy and explain p95 in one phrase.
  • Mistake: No result. Why it is wrong: The impact can't be judged. Instead: Before/after p95 and the next peak's numbers.

🏛 Senior insight: trade-offs

The senior signal is the deduction from first principles (low CPU plus high latency means waiting) followed by proof and a systemic fix. Seniors also connect code to platform: probes, autoscaling on CPU (which won't trigger when CPU is low) and downstream latency all shaped this incident. Mention that CPU-based autoscaling did nothing here, and that you added a queue-length or latency-based signal.

Fix When it fits Cost When not to
Async end to end Always, for I/O Refactoring effort up the call chain Truly CPU-bound work
Cache the dependency Value changes rarely Staleness, invalidation Per-request data
Raise min threads Incident tourniquet Memory, context switching As a permanent setting without measurement
Bulkhead / concurrency limit Protect the pool from one slow dependency Rejected work When the real bug is blocking
Prevention Catches
VSTHRD analysers as errors .Result, .Wait(), async void
Load test with injected latency Blocking that only hurts under slow dependencies
Alert on ThreadPool queue length Starvation within a minute

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions health probes failing or Kubernetes restarting pods. Why: Checks the full incident playbook for starvation including probe behaviour.
    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.

  2. When: Candidate says 'ThreadPool starvation' without explaining how they confirmed it. Why: Checks the mechanism and the diagnostic evidence.
    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.

  3. When: Candidate says the cause was .Result or .Wait(). Why: Checks they know 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.

🛠 Real-world problems: how you handle them

Sale-day hang: sync-over-async key fetch starves the ThreadPool
Situation
[Checkout API] on [AKS], [6] pods, normally [~150] req/s at p95 [100 ms]. During [a sale] traffic hit [3x]. Revenue for the [day] depended on checkout working. I was [the on-call engineer / incident lead].
Signals
p95 from [100 ms] to [30 s]; throughput flat despite more incoming requests; CPU [~20%]; liveness and readiness probes timing out; pods restarting in waves; 502/504 from the ingress; no exceptions in the app logs apart from `TaskCanceledException` from cancelled requests.
Investigation
Ruled out a database problem (Azure SQL CPU and DTU normal, SQL dependency durations unchanged) and a deadlock (pods recovered slowly when traffic dipped). dotnet-counters on one pod: `threadpool-queue-length` [4,000+], `threadpool-thread-count` rising about 1–2 per second. `dotnet-dump collect`, then `pstacks`: [300] threads with the same stack in `GetAwaiter().GetResult()` inside [`SigningKeyProvider.GetSigningKey`], which called a key service over HTTP. Application Insights showed that downstream had slowed from [5 ms] to [400 ms] under the sale load, so each blocked thread was held far longer.
Resolution
Mitigation: scaled to [12] pods; set `System.Threading.ThreadPool.MinThreads` to [200] through configuration and restarted gradually; raised the liveness probe timeout and failure threshold so recovering pods weren't killed. p95 was back under [300 ms] in [~10] minutes. Real fix: made the provider async end to end and cached the key with HybridCache for [10] minutes, removing the downstream call from the hot path; removed the min-threads override after the fix proved itself under load.
Prevention
Microsoft.VisualStudio.Threading.Analyzers with VSTHRD002/VSTHRD103 as errors; a k6 load test in the pipeline that injects [300 ms] latency into dependencies; an alert on ThreadPool queue length > [100] for 2 minutes; autoscaling on request latency or RPS (KEDA / HPA custom metric) instead of CPU alone; separate liveness (process alive) from readiness (can serve).

How to tell it (STAR)

**S:** At [company], our [checkout API] on [AKS] slowed from [100 milliseconds] to [30 seconds] during [a sale], while CPU sat at [20%], and pods kept restarting. **T:** As [on-call engineer] I had to get checkout working and find out why. **A:** Low CPU with high latency told me requests were waiting, not working. dotnet-counters showed thousands of queued work items with threads being added slowly, and a dump showed [300] threads blocked on `.Result` in one key-fetch helper whose downstream had slowed under load. I scaled out, raised the minimum threads temporarily and relaxed the liveness probe, which brought p95 under [300 ms] in [ten] minutes. Then I made the helper async and cached it, turned on the threading analysers as errors, and added a load test with injected latency. **R:** The next sale ran at [twice] the traffic with p95 at [120 ms], and the analysers have since blocked [N] new blocking calls in review.

More in Production Incidents

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me