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

📚 Interview question

How do you tell whether a .NET service is CPU-bound, memory-bound or I/O-bound? Which dotnet-counters metrics show each, and what does the fix look like in each case?

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.

Intermediate Theory Intermediate cpu-bound diagnostics dotnet-counters gc io-bound performance

🎯 Key points

  • CPU-bound: process CPU near the container's core limit, latency rises with load
  • Memory/GC-bound: high allocation rate, high % time in GC, frequent Gen 2 collections
  • I/O-bound: CPU low, slow dependency calls (SQL, HTTP, disk, network) dominate request time
  • ThreadPool queue length growing with low CPU means blocking, not CPU
  • dotnet-counters System.Runtime: cpu-usage, alloc-rate, time-in-gc, threadpool-queue-length (Meter names on .NET 9+: dotnet.process.cpu.time, dotnet.gc.pause.time, dotnet.thread_pool.queue.length)
  • Check other saturated resources too: connection pools, network bandwidth, disk I/O, downstream rate limits
  • Fixes: algorithms and caching for CPU; fewer allocations for GC; fewer or faster round trips and async for I/O
  • Container CPU limits can throttle a service that looks idle

⏱ 30-second answer

I look at dotnet-counters (System.Runtime) next to request and dependency telemetry:

  • CPU-bound: process CPU usage sits near the cores you have and latency climbs with load. Fix: better algorithms, less work per request, caching, then profile with dotnet-trace.
  • Memory/GC-bound: high allocation rate, a high % time in GC and frequent Gen 2 collections. Fix: allocate less on hot paths (pooling, spans, streaming instead of buffering).
  • I/O-bound: CPU is low but requests are slow and dependency durations (SQL, HTTP) dominate. Fix: fewer round trips, better queries and indexes, true async I/O, caching.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"I start with dotnet-counters monitor on 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 .Result or Thread.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."


Fingerprints

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

Typical fixes

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can triage a performance problem from runtime metrics instead of guessing.

Green flags

  • Names specific counters and what each means
  • Separates GC time from user-code CPU
  • Knows low CPU plus a growing ThreadPool queue means blocking
  • Mentions container CPU limits and throttling

Red flags

  • 'Add more servers' as the first answer
  • Can't name a single counter
  • Treats every slow request as a CPU problem

📚 Learn in depth

1. Where request time goes

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

2. The counters

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.

3. Containers change the picture

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.

4. GC-bound vs CPU-bound

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.

5. I/O-bound needs end-to-end telemetry

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.

Try it yourself

  1. Build a minimal API with three endpoints: one computing primes (CPU), one allocating 1 MB arrays in a loop (GC), one awaiting Task.Delay(200) (I/O). Load each with k6 and record which counters move.
  2. Add an endpoint that calls Task.Delay(200).Wait() and watch threadpool-queue-length under 200 concurrent users.
  3. Run the API in Docker with --cpus=1 and compare cpu-usage with what docker stats shows.
  4. Capture dotnet-trace collect --profile cpu-sampling during the CPU test and open it in Speedscope.

💻 Code

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]

⚠ Common mistakes

  • Mistake: Optimising without measuring. Why it is wrong: You can't fix a bottleneck you haven't classified. Instead: Triage with counters, then confirm with a trace or dump.
  • Mistake: Micro-optimising cold paths. Why it is wrong: If the service is I/O-bound, faster C# changes nothing. Instead: Fix the class of bottleneck you actually have.
  • Mistake: Reading host CPU instead of process CPU against the container limit. Why it is wrong: A throttled container looks idle at host level. Instead: Compare cpu-usage with the CPU limit and check CFS throttling.
  • Mistake: Treating high CPU as proof that code is expensive. Why it is wrong: GC work counts as CPU. Instead: Check time-in-gc and alloc-rate first.
  • Mistake: Scaling out an I/O-bound service. Why it is wrong: More instances add more load to the slow database. Instead: Fix the query or add caching.
  • Mistake: Raising ThreadPool minimums when the queue grows. Why it is wrong: It hides blocking code. Instead: Find and remove the blocking calls.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions ThreadPool queue length Why: Checks they can diagnose starvation end to end
    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 mentions frequent Gen 2 collections Why: Checks they can investigate GC-bound behaviour in depth
    How to answer

    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.

  3. When: Candidate mentions container CPU limits Why: Checks they understand CFS throttling and ProcessorCount 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.

↩ Usually asked after

More in Application Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me