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

📚 Interview question

One of your eight API instances is pinned at 100% CPU, its requests are slow, and the others look normal. How do you diagnose and fix it? Walk me through what you do first, how you use dotnet-counters and dotnet-trace to find the hot code, the usual culprits (a runaway loop, catastrophic regex backtracking, a hot lock, GC), and how you mitigate while you work on the fix.

A production playbook for one instance stuck at 100% CPU: isolating the instance, dotnet-counters triage, a dotnet-trace CPU sample, reading the hot path, and the usual causes such as regex backtracking, runaway loops, spin contention and GC.

Mid-Level Debugging Intermediate debugging dotnet-counters dotnet-trace high-cpu production regex

🎯 Key points

  • One instance hot and others normal points at a specific input or state, not general load
  • First five minutes: take the instance out of rotation (or drain it), don't restart it until you've captured a trace
  • dotnet-counters: cpu-usage, gc time, exception count and ThreadPool queue length to split GC from app code
  • dotnet-trace collect --profile cpu-sampling for 30–60 s, then read the flame graph in PerfView, Speedscope or Visual Studio
  • Exclusive time on System.Text.RegularExpressions frames means backtracking; on your own method means a runaway loop
  • Fix regex with a length limit, RegexOptions.NonBacktracking (.NET 7+) or a match timeout; fix loops with bounds and input validation
  • Per-instance CPU alerts and latency split by cloud_RoleInstance, so one hot box isn't hidden by the fleet average
  • Record the triggering input in the RCA and turn it into a regression test

⏱ 30-second answer

One instance hot while the others are fine means a specific input or state, not load. First I drain that instance from the load balancer so users stop hitting it, but I don't restart it until I have a trace. dotnet-counters tells me whether it's GC (high % time in GC), exceptions, or my own code. Then dotnet-trace with the cpu-sampling profile for 30–60 seconds gives me a flame graph; the frame with the most exclusive time is the hot code. The usual culprits are catastrophic regex backtracking on one long input, a runaway loop on bad data, or spinning on a contended lock. The fix is the code (regex timeout or NonBacktracking, bounded loops, input limits); the restart is just mitigation, and it destroys the evidence if you do it first.

🗣 Full answer (senior)

How I would answer this in an interview

"If only one of eight instances is hot, I don't think 'we need more capacity', I think 'something on that box is different'. Usually one request with a nasty input is burning a core, or a background job got stuck in a loop. So in the first few minutes I take that instance out of rotation so customers stop landing on it, and I resist the urge to restart it, because a restart deletes the only evidence I have.

Then I triage with dotnet-counters monitor. If % time in GC is high and allocation rate is huge, it's a memory problem showing up as CPU. If exceptions per second are in the thousands, something is throwing in a loop. If neither, it's my code. Next I run dotnet-trace collect --profile cpu-sampling for about 30 seconds and open it in PerfView, Speedscope or Visual Studio. The sampler records stacks roughly every millisecond, so whatever has the most exclusive time is where the CPU goes. A wall of RegexInterpreter or RegexRunner frames under one endpoint means catastrophic backtracking: a pattern like nested quantifiers hitting a long string that doesn't match. My own method with high exclusive time means a loop. Lots of time in SpinWait or Monitor means contention.

The mistake I see is restarting the pod, watching CPU drop, and calling it fixed. The same input comes back tomorrow. I'd rather spend ten minutes capturing a trace and fix it once."


The playbook, in order

Step What I do Tool or command
1. Symptom One instance at 100%, others normal, slow requests on that one Azure Monitor per-instance CPU, App Insights cloud_RoleInstance split
2. First five minutes Drain the instance; keep it running App Service: restart is the wrong move; AKS: remove the pod's label from the Service selector
3. Data to collect Counters, then a CPU sample dotnet-counters monitor, dotnet-trace collect --profile cpu-sampling
4. Rule out GC (counters), load imbalance (request count per instance), noisy neighbour (node CPU) Counters, App Insights, kubectl top
5. Root cause The hot frame and the input that triggers it Flame graph, request logs around the start time
6. Fix Regex timeout or rewrite, bounded loop, input validation Code change
7. Prevention Default regex timeout, input limits, per-instance CPU alert Analyser, middleware, alert rule

Reading the hot frame

Hot frames Likely cause Fix
System.Text.RegularExpressions.* Catastrophic backtracking matchTimeout, RegexOptions.NonBacktracking, [GeneratedRegex] with a safer pattern, length limit
Your own method, high exclusive time Runaway or O(n²) loop on bad data Bound the loop, fix the algorithm, validate input
SpinWait, Monitor.Enter, SpinLock Lock contention Shorter critical sections, lock-free structure, partitioning
GC*, gc_heap::* Allocation storm Reduce allocations, pool buffers
Exception constructors, stack trace capture Exceptions used for flow control Return results instead of throwing
JSON serialiser in a loop Huge payload or cyclic graph Payload limits, ReferenceHandler, streaming

Production example

A search endpoint validated email addresses with ^([a-zA-Z0-9]+\.?)+@...$. One integration partner sent a 5,000-character string without an @. Each request burned a core for minutes; with four requests in flight one instance sat at 100% and p95 on that instance went from 80 ms to 30 seconds. Draining the instance stopped user impact; the trace showed 97% of samples in the regex interpreter. A [GeneratedRegex] with a non-nested pattern, a 100 ms match timeout and a 254-character length limit brought the same input to under 1 ms.

🔍 What the interviewer is checking

Checks whether the candidate can isolate a single hot instance, capture a CPU profile in production with standard .NET tools and read it correctly, and recognise input-driven causes such as regex backtracking.

Green flags

  • Notices that one hot instance means an input or state problem
  • Drains instead of restarting, and captures evidence first
  • Uses dotnet-counters to rule GC and exceptions in or out, then dotnet-trace cpu-sampling
  • Reads exclusive time and knows what regex backtracking looks like
  • Mentions container CPU throttling

Red flags

  • "Scale up" or "restart" as the whole answer
  • Attaches Visual Studio to production
  • Can't explain inclusive versus exclusive time

📚 Learn in depth

1. Why one instance and not all of them

Load balancers spread requests evenly, so general overload heats every instance together. A single hot instance means something sticky: a request that never finishes, a background job (only one instance holds the lease), a cache entry that only that instance built, or a noisy neighbour on the node. Check request counts per instance first: if they're equal, it's work per request, not volume.

2. How CPU sampling works

dotnet-trace uses EventPipe, the runtime's in-process event channel. The cpu-sampling profile enables the Microsoft-DotNETCore-SampleProfiler provider, which walks every managed thread's stack at a fixed interval (about 1 ms) and records it. It doesn't need a debugger or admin rights, works on Linux containers, and adds a few per cent overhead.

thread stacks every ~1 ms
   │
   ▼
EventPipe session ──► .nettrace file ──► PerfView / Speedscope / Visual Studio
                                         │
                                         ├── call tree (inclusive time)
                                         └── flame graph (width = samples)
  • Inclusive time: samples where the method is anywhere on the stack.
  • Exclusive time: samples where it is the top frame. High exclusive time is where the CPU is actually spent.

Note: the sampler sees managed stacks. Time in native code shows as the managed frame that called it. For native hot spots on Linux, use perf with DOTNET_PerfMapEnabled=1.

3. Catastrophic backtracking from first principles

The default .NET regex engine is a backtracking engine. A pattern like (a+)+$ against aaaa...ab can split the run of as between the inner and outer quantifier in exponentially many ways, and the engine tries them all before failing. Thirty characters can take seconds; a few thousand can take forever.

.NET gives you three defences:

  1. Match timeout: pass matchTimeout to the constructor, or set REGEX_DEFAULT_MATCH_TIMEOUT in the AppDomain data; the engine throws RegexMatchTimeoutException.
  2. RegexOptions.NonBacktracking (since .NET 7): a finite-automaton engine with linear time in the input length. It doesn't support backreferences or lookarounds.
  3. [GeneratedRegex]: the source generator emits C# at compile time; it's faster and lets you read what the pattern does, but it still backtracks unless you choose NonBacktracking.

4. GC showing up as CPU

With Server GC, collections run on dedicated GC threads, one per heap. An allocation storm (a big JSON response built in memory, a LINQ chain on millions of items) can keep those threads busy. dotnet-counters shows % time in GC since last GC and allocation rate; above roughly 10–20% GC time is a problem in its own right.

5. Containers and throttling

In Kubernetes, a CPU limit is enforced with CFS quotas. A pod at its limit is throttled, so it may show "100% of limit" while the node is idle, and latency spikes in 100 ms periods. Check container_cpu_cfs_throttled_periods_total before blaming the code; sometimes the right answer is to remove the CPU limit and keep only the request.

Try it yourself

  1. Write an endpoint that runs new Regex("^(a+)+$").IsMatch(input) and call it with 30 as followed by b; watch one core hit 100%.
  2. Run dotnet-trace collect -p <pid> --profile cpu-sampling --duration 00:00:30 and open the .nettrace in Speedscope (--format Speedscope) or PerfView.
  3. Switch to RegexOptions.NonBacktracking and compare with BenchmarkDotNet.
  4. Add a matchTimeout of 100 ms and confirm you get RegexMatchTimeoutException instead of a stuck core.
  5. In a container with --cpus=1, run a CPU-heavy loop and watch throttling in docker stats and /sys/fs/cgroup/cpu.stat.

💻 Code

A backtracking regex on user input, and a safe version.

// Before: nested quantifiers, no timeout, no length limit. One bad input pins a core.
namespace Contacts.Validation;

public static class EmailCheck
{
    private static readonly Regex Pattern = new(@"^([a-zA-Z0-9]+\.?)+@[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+$");
    public static bool IsValid(string input) => Pattern.IsMatch(input);
}
// After: length limit first, linear-time engine, and a timeout as a backstop.
namespace Contacts.Validation;

using System.Text.RegularExpressions;

public static partial class EmailCheck
{
    private const int MaxLength = 254; // RFC 5321 path limit; rejects abuse before the regex runs

    [GeneratedRegex(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}$",
        RegexOptions.NonBacktracking, matchTimeoutMilliseconds: 100)]
    private static partial Regex Pattern();

    public static bool IsValid(string? input)
    {
        if (string.IsNullOrEmpty(input) || input.Length > MaxLength) return false;
        try { return Pattern().IsMatch(input); }
        catch (RegexMatchTimeoutException) { return false; } // treat as invalid, never as a stuck core
    }
}
# Triage and capture on the hot instance (AKS ephemeral container)
dotnet-counters monitor -p 1 --counters System.Runtime[cpu-usage,time-in-gc,exception-count,threadpool-queue-length]
dotnet-trace collect -p 1 --profile cpu-sampling --duration 00:00:30 -o /tmp/hot.nettrace
dotnet-trace convert /tmp/hot.nettrace --format Speedscope   # open in speedscope.app
# Check for throttling before blaming code
kubectl top pod -n prod && kubectl exec <pod> -- cat /sys/fs/cgroup/cpu.stat

⚠ Common mistakes

  • Mistake: Restarting the hot instance first. Why it is wrong: The stuck request and its stack disappear, and the same input comes back. Instead: Drain it from the load balancer, capture a trace, then restart.
  • Mistake: Scaling out to "fix" one hot instance. Why it is wrong: More instances just give the bad input more places to land. Instead: Find what makes that instance different.
  • Mistake: Reading inclusive time and blaming the controller. Why it is wrong: Every request's controller is on the stack; inclusive time doesn't say where the work happens. Instead: Sort by exclusive time.
  • Mistake: Using regexes on untrusted input with no timeout. Why it is wrong: The default engine backtracks, and one crafted input is a denial-of-service. Instead: Length-limit first, use NonBacktracking or a timeout.
  • Mistake: Ignoring CPU throttling in containers. Why it is wrong: A pod can look maxed out at its CFS quota while the node idles. Instead: Check throttled periods and the limit before profiling.
  • Mistake: Profiling with a debugger attached or a Debug build. Why it is wrong: The JIT doesn't optimise and the profile lies. Instead: Profile the Release build in place with dotnet-trace.
  • Mistake: Treating high GC time as a CPU problem to optimise in code paths. Why it is wrong: The fix is fewer allocations, not faster code. Instead: Check allocation rate and GC time first.

🏛 Senior insight: trade-offs

A single hot instance is a gift: the rest of the fleet is healthy, so you can afford to keep the bad one alive long enough to learn from it. The senior instinct is to protect users by draining, then use the sick instance as the lab. The other senior point is that CPU incidents caused by input are really security issues: a backtracking regex on a public endpoint is a ReDoS vulnerability, and it should go into the threat model and the analyser rules, not just get a patch.

Observability decides how fast you get here. Alert on CPU per instance (the maximum, not the fleet average, which hides one hot box among eight), keep request telemetry with cloud_RoleInstance so you can split latency by instance, and log request size on endpoints that take free text. On App Service, the Application Insights Profiler can capture the CPU sample for you on a trigger, which saves the manual dotnet-trace step. Close the loop with an RCA that records the triggering input, so the fix becomes a test case.

Option When it fits Cost When not to
Drain and capture One hot instance, others healthy Minutes of reduced capacity When every instance is hot: then you need load shedding first
Restart immediately Capacity is critical and you already have a trace Loses evidence As the first move
Regex timeout Any regex on untrusted input Callers must handle the exception As the only defence for an exponential pattern
NonBacktracking Patterns without backreferences or lookarounds Slower construction; feature limits When you need lookarounds

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions reading a flame graph Why: Checks deeper knowledge of sampling profilers and inclusive versus exclusive time
    How to answer

    dotnet-trace with the default cpu-sampling profile uses EventPipe's sample profiler: roughly every millisecond it records each managed thread's call stack. Aggregated, those samples become a call tree or flame graph, where a frame's width is the share of samples it appears in.

    I read it top-down from my entry point to find the wide paths, then bottom-up by exclusive (self) time to find the methods that actually burn CPU.

    • Inclusive time: the method and everything it calls.
    • Exclusive time: just its own code.

    A wide frame is not always CPU work: EventPipe also samples threads that are waiting on a lock or I/O, and an awaiting async request holds no thread, so it doesn't appear at all. I cross-check with dotnet-counters and distributed traces. The trade-off: sampling is cheap enough for production but statistical, so short events can be missed; I capture under real load for 30–60 seconds and verify fixes with a second profile.

  2. When: Candidate mentions Kubernetes CPU limits Why: Checks understanding of CFS quotas, throttling and scheduler effects in containers
    How to answer

    The scheduler keeps a queue of runnable threads per core and gives each a time slice. Scheduling is preemptive: when the slice ends, or a higher-priority thread becomes ready, the running thread is interrupted and another runs. Threads that wait for I/O, locks or timers are blocked and don't use CPU. Windows uses priority-based round-robin with temporary boosts; Linux uses a fair scheduler (CFS, and EEVDF from kernel 6.6). For a .NET service the practical points are: don't play with thread priorities; blocking threads wastes them; and in containers, a CPU limit is enforced as a quota per 100 ms period, so a burst of work can use the quota early and get throttled, causing latency spikes. Environment.ProcessorCount follows the limit and sizes the thread pool and GC.

  3. When: Candidate blames a regex Why: Checks whether the candidate treats input-driven CPU burn as a security issue
    How to answer

    ReDoS is a denial of service where a crafted input makes a backtracking regex take exponential time, so a handful of requests can pin every core and take an API down. In .NET you defend in layers: limit input length before matching; avoid nested quantifiers like (a+)+ and overlapping alternations; use RegexOptions.NonBacktracking (added in .NET 7, linear time) when you don't need backreferences or lookarounds; always set a match timeout on untrusted input; and prefer [GeneratedRegex] so the pattern is compiled and reviewable. Treat it as a security finding in the threat model, not just a performance bug.

🛠 Real-world problems: how you handle them

One instance pinned by a partner's oversized input
Situation
A customer search API on [Azure App Service, eight instances] in Australia East, [about 1,200 requests/s] at peak. A partner integration sent contact records with free-text email fields.
Signals
A per-instance CPU alert fired for one instance at 100% for ten minutes. Application Insights split by `cloud_RoleInstance` showed p95 of [30 s] on that instance and [80 ms] on the others. Request counts per instance were equal.
Investigation
Ran `dotnet-counters`: GC time under 3%, exceptions low, so not memory or exceptions. Captured a 30-second `dotnet-trace` cpu-sampling trace through the Kudu console; Speedscope showed 97% of samples in the regex interpreter under the contact import endpoint. A KQL query over request telemetry found [four] long-running requests from the partner's client id with bodies over [5,000] characters.
Resolution
Immediate: restarted that instance after the trace was captured and blocked the partner's import endpoint for an hour with a feature flag. Real fix: a 254-character length limit, a `[GeneratedRegex]` with `NonBacktracking` and a 100 ms timeout.
Prevention
Set a default regex timeout for the app, added an analyser rule that flags `new Regex` without a timeout, added request body size limits per endpoint, and created a per-instance CPU alert instead of an average across instances.

How to tell it (STAR)

**S:** At [company], one of eight instances of our search API sat at 100% CPU and its requests were taking 30 seconds, while the others were fine. **T:** I was on call and had to stop the impact and find out why only one box. **A:** I drained that instance rather than restarting it, ran dotnet-counters to rule out GC, then took a 30-second dotnet-trace sample. Almost all the CPU was in the regex engine, and the logs showed a partner sending 5,000-character email fields. I added a length limit, switched the pattern to `NonBacktracking` with a timeout, and added an analyser rule for regexes without timeouts. **R:** The same input now takes under a millisecond, p95 on that endpoint went back to [80 ms], and we haven't had a CPU incident from input since.

More in Debugging Production Issues

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me