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.
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.
"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 GCis 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 rundotnet-trace collect --profile cpu-samplingfor 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 ofRegexInterpreterorRegexRunnerframes 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 inSpinWaitorMonitormeans 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."
| 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 |
| 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 |
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.
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
Red flags
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.
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)
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.
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:
matchTimeout to the constructor, or set REGEX_DEFAULT_MATCH_TIMEOUT in the AppDomain data; the engine throws RegexMatchTimeoutException.RegexOptions.NonBacktracking (since .NET 7): a finite-automaton engine with linear time in the input length. It doesn't support backreferences or lookarounds.[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.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.
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.
new Regex("^(a+)+$").IsMatch(input) and call it with 30 as followed by b; watch one core hit 100%.dotnet-trace collect -p <pid> --profile cpu-sampling --duration 00:00:30 and open the .nettrace in Speedscope (--format Speedscope) or PerfView.RegexOptions.NonBacktracking and compare with BenchmarkDotNet.matchTimeout of 100 ms and confirm you get RegexMatchTimeoutException instead of a stuck core.--cpus=1, run a CPU-heavy loop and watch throttling in docker stats and /sys/fs/cgroup/cpu.stat.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
NonBacktracking or a timeout.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 |
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.
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.
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.
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.
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.
Last updated 23 Nov 2026.