Classifying a slow .NET service as CPU-, memory/GC- or I/O-bound from dotnet-counters and telemetry, and the typical fix for each class.
I look at dotnet-counters (System.Runtime) next to request and dependency telemetry:
dotnet-trace.If CPU is low and the ThreadPool queue keeps growing, it's blocking (sync-over-async), not I/O capacity. The trade-off: one counter never proves it; I confirm with a profile or trace.
"I start with
dotnet-counters monitoron the process while it's under load, alongside Application Insights or OpenTelemetry dependency timings, because each type of bottleneck leaves a different fingerprint.If CPU usage is pinned near the number of cores the container is allowed and latency rises as load rises, it's CPU-bound: the process is doing too much computation per request, such as serialisation, regex, crypto or a bad algorithm. If CPU is moderate but the allocation rate is hundreds of megabytes a second, % time in GC is double digits and Gen 2 counts keep climbing, it's GC-bound: the CPU is busy collecting garbage rather than doing work. If CPU is low but requests are slow, I look at dependencies; when most of the request time is SQL or HTTP calls, it's I/O-bound and the fix is outside the C#: queries, indexes, round trips or caching. The special case is low CPU plus a ThreadPool queue length that keeps growing: that's threads blocked on
.ResultorThread.Sleep, and adding hardware won't help.The mistake I see is reading one counter and jumping to a fix, like scaling out because CPU is high when the CPU is actually GC. I treat counters as a triage step and confirm with a CPU trace, a gcdump or the SQL execution plan before changing anything."
| Class | Counters that move | Telemetry | Confirm with |
|---|---|---|---|
| CPU-bound | cpu-usage high, RPS plateaus |
Server time dominates, few dependencies | dotnet-trace collect --profile cpu-sampling, flame graph |
| GC-bound | alloc-rate high, time-in-gc > ~10%, gen-2-gc-count rising |
Spiky latency, p99 far above p50 | dotnet-gcdump, allocation profiling |
| I/O-bound | cpu-usage low, active-requests high |
Dependency calls take most of the request | Dependency waterfall, SQL plans, Query Store |
| Blocking / starvation | threadpool-queue-length rising, threadpool-thread-count creeping up |
All endpoints slow together | dotnet-dump + clrstack -all |
| Lock contention | monitor-lock-contention-count rising |
Throughput flat despite spare CPU | dotnet-trace contention events |
| Class | Fixes |
|---|---|
| CPU | Cheaper algorithm, cache computed results, avoid repeated serialisation, SearchValues/source-generated regex, scale out |
| GC | Pool buffers (ArrayPool<T>), spans, avoid LINQ/closures in hot loops, stream instead of buffering large payloads, check Server GC / DATAS settings |
| I/O | Projection and indexes, batch round trips, caching, async all the way, connection pooling |
| Blocking | Remove sync-over-async; never block in ASP.NET Core request paths |
An API in a container limited to 2 CPUs showed only 50% host CPU but latency doubled at peak. dotnet-counters showed process CPU at 1.95 of 2 cores and 18% time in GC from a JSON response being buffered as a string. Switching to streaming serialisation cut the allocation rate from 600 MB/s to 90 MB/s, time in GC to 3% and p95 from 480 ms to 190 ms.
Checks whether the candidate can triage a performance problem from runtime metrics instead of guessing.
Green flags
Red flags
A request thread is in one of three states: running on a CPU, paused while the GC runs, or not running because it's waiting (I/O completion, a lock, a queued work item). Each counter measures one of those states.
+-- running user code ------> CPU-bound
request ----+-- paused for GC ----------> GC-bound
+-- waiting: I/O -----------> I/O-bound
+-- waiting: lock ----------> contention
+-- waiting: thread to run -> ThreadPool starvation
The System.Runtime provider exposes (names as shown by dotnet-counters; on .NET 9+ the same data is also published through the System.Runtime Meter as dotnet.process.cpu.time, dotnet.gc.heap.total_allocated, dotnet.gc.pause.time, dotnet.thread_pool.queue.length and so on):
cpu-usage: % of total CPU used by the process. Compare against the container's CPU limit, not the host.alloc-rate: bytes allocated per interval. Hundreds of MB per second on a modest API is a red flag.time-in-gc: % of time paused in GC since the last GC.gen-0/1/2-gc-count: frequent Gen 2 means long-lived garbage or LOH churn.threadpool-queue-length, threadpool-thread-count: a queue that grows while threads are injected slowly is starvation.monitor-lock-contention-count: times a thread had to wait for a lock.Microsoft.AspNetCore.Hosting adds requests-per-second and current-requests.
With a CPU limit of 2 on a 16-core node, the runtime sees 2 processors (Environment.ProcessorCount), and Kubernetes CFS throttling pauses the process when it uses its quota early in a 100 ms period. Host CPU looks idle while your process is throttled. Check container_cpu_cfs_throttled_periods_total alongside dotnet-counters.
GC work shows up as CPU usage, so high CPU alone doesn't mean your code is expensive. If time-in-gc is high, reducing allocations is the CPU fix.
The process can't see why SQL is slow. Use dependency telemetry to find which call dominates, then the database tools: execution plans, Query Store, wait statistics.
Task.Delay(200) (I/O). Load each with k6 and record which counters move.Task.Delay(200).Wait() and watch threadpool-queue-length under 200 concurrent users.--cpus=1 and compare cpu-usage with what docker stats shows.dotnet-trace collect --profile cpu-sampling during the CPU test and open it in Speedscope.A diagnostic sandbox: endpoints that each produce a different bottleneck fingerprint for practising with dotnet-counters.
// Program.cs (.NET 10). Run, load each endpoint, and watch dotnet-counters.
var app = WebApplication.CreateBuilder(args).Build();
// CPU-bound: pure computation, cpu-usage climbs with load.
app.MapGet("/cpu", () => Results.Ok(CountPrimes(200_000)));
// GC-bound: allocates large short-lived arrays, alloc-rate and time-in-gc climb.
app.MapGet("/gc", () =>
{
long total = 0;
for (var i = 0; i < 50; i++)
{
var buffer = new byte[100_000]; // 100 KB is over the 85,000-byte threshold, so it lands on the LOH
total += buffer.Length;
}
return Results.Ok(total);
});
// I/O-bound: waits without using a thread, CPU stays low, latency is the wait.
app.MapGet("/io", async (CancellationToken ct) =>
{
await Task.Delay(200, ct);
return Results.Ok("done");
});
// Blocking: the anti-pattern. Low CPU, threadpool-queue-length grows.
app.MapGet("/blocking", () =>
{
Task.Delay(200).Wait();
return Results.Ok("done");
});
app.Run();
static int CountPrimes(int limit)
{
var count = 0;
for (var n = 2; n < limit; n++)
{
var isPrime = true;
for (var d = 2; d * d <= n; d++)
if (n % d == 0) { isPrime = false; break; }
if (isPrime) count++;
}
return count;
}
dotnet-counters monitor -n Sandbox --counters System.Runtime[cpu-usage,alloc-rate,time-in-gc,gen-2-gc-count,threadpool-queue-length,threadpool-thread-count,monitor-lock-contention-count]
cpu-usage with the CPU limit and check CFS throttling.time-in-gc and alloc-rate first.The senior move is treating counters as triage, not diagnosis, and keeping them always-on: export runtime metrics through OpenTelemetry so you have yesterday's baseline when today is slow. Most production .NET APIs are I/O-bound; true CPU-bound services are rarer (image processing, crypto, heavy serialisation), so be sceptical when someone wants to rewrite C# for speed.
| Class | Cheapest first fix | Escalation | When not to |
|---|---|---|---|
| CPU | Cache results, remove repeated work | Profile and optimise algorithms; scale out | Don't scale out a GC-bound service |
| GC | Pool or stream big buffers | Allocation profiling, struct/span refactors | Don't tune GC settings before reducing allocations |
| I/O | Index, projection, batching | Caching, read replicas | Don't add async wrappers around sync I/O |
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.
A Gen 2 GC collects the whole managed heap: Gen 0, Gen 1, Gen 2, the LOH and the POH. It is triggered when Gen 2's budget is exceeded by promotions, when large object allocations exceed the LOH budget, under memory pressure (approaching the container or GCHeapHardLimit), or by code calling GC.Collect(). Most Gen 2 GCs run as background GCs that let threads keep running; blocking full GCs (with compaction) pause everything. To investigate frequent Gen 2 GCs, check the GC reason (dotnet-trace or PerfView GCStats), then the cause: LOH churn, mid-life objects, induced collections, or memory limit pressure.
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.
Last updated 23 Nov 2026.