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

📚 Interview question

How do you approach a performance problem in a .NET service? Walk me through how you define the goal, measure, find the bottleneck, make a change and prove it helped.

The measurement-driven method for performance work: setting a goal in percentiles and throughput, measuring a baseline, locating the bottleneck, changing one thing and verifying the result.

Beginner Theory Beginner benchmarkdotnet bottleneck dotnet-counters measurement percentiles performance

🎯 Key points

  • Goal stated as a number: p95/p99 latency and requests per second at a given load
  • Baseline measured under the same realistic load, data and environment you'll verify with
  • Find the bottleneck first (USE: utilisation, saturation, errors per resource): CPU, memory/GC, I/O or contention
  • Change one thing at a time so the effect is attributable and side-effects are visible
  • Verify with the same measurement under the same load; keep or revert
  • Percentiles, not averages: the average hides the slow tail users feel
  • Amdahl's law: prioritise by share of request time; stop when the goal is met

⏱ 30-second answer

I treat performance as an experiment, not a hunch. First I agree a goal as a number: for example p95 under 200 ms at 300 requests a second. Then I measure a baseline with the same tools I'll use to verify: Application Insights for request and dependency timings, dotnet-counters for CPU, GC and ThreadPool, and a repeatable load test.

Next I find the bottleneck: is time going to CPU, garbage collection, waiting on I/O (database, HTTP) or waiting on locks? Only then do I change one thing, re-run the same measurement and keep the change only if the numbers moved. I stop once the goal is met.

The trade-off is time: measuring first feels slower, but guessing usually optimises code that wasn't the problem.

🗣 Full answer (senior)

How I would answer this in an interview

"I start by turning 'it's slow' into a number. I ask which operation, for whom and at what load, and agree a target like 'the search endpoint at p95 under 200 milliseconds with 300 requests a second'. I use percentiles rather than averages because an average of 80 milliseconds can hide one user in twenty waiting two seconds.

Then I measure a baseline before touching code. In .NET that's Application Insights or OpenTelemetry for end-to-end request and dependency timings, dotnet-counters for CPU, GC heap, allocation rate and ThreadPool queue length, and a load test with k6 or Azure Load Testing so I can reproduce the load. From that I classify the bottleneck: is the process burning CPU, spending time in GC, waiting on a database or downstream API, or queueing on a lock? Each needs a different tool next: dotnet-trace for CPU, dotnet-gcdump for memory, dependency telemetry and execution plans for I/O.

When I know where the time goes, I change one thing, rerun the same test under the same load and compare. If it didn't move the number, I revert it, even if it 'should' be faster. The mistake I see is people optimising what they assume is slow, like rewriting a LINQ query, when 90 per cent of the time is a database round trip. Measure, change one thing, measure again: that's the whole method."


The loop

Step Question it answers .NET tools
1. Goal What does 'fast enough' mean? SLO: p95/p99 latency, throughput, error rate
2. Baseline Where are we now? Application Insights, dotnet-counters, k6 / Azure Load Testing
3. Bottleneck Where does the time go? dotnet-trace, dotnet-gcdump, dependency telemetry, Query Store
4. Change What single change targets it? Code, query, index, config
5. Verify Did the number move? Same load test, same metrics; BenchmarkDotNet for micro-level

Averages vs percentiles

Metric What it tells you Trap
Mean Total work / requests Hides the slow tail
p50 The typical request Says nothing about the worst users
p95 / p99 What 1 in 20 / 1 in 100 requests feel Needs enough samples to be stable
Max One outlier Too noisy to target

Kinds of bottleneck

Symptom Likely bottleneck Next step
CPU near 100%, latency rises with load CPU-bound code dotnet-trace CPU sampling, flame graph
High % time in GC, high allocation rate Allocations / memory dotnet-counters GC counters, allocation profiling
CPU low, latency high, slow dependencies I/O wait Dependency timings, SQL execution plans
CPU low, ThreadPool queue growing Blocking / starvation dotnet-counters ThreadPool counters, dotnet-dump stacks
CPU low, lock contention count rising Lock contention dotnet-trace contention events

Production example

A product search endpoint ran at p95 900 ms against a 300 ms target. Dependency telemetry showed 640 ms of that was a single SQL query doing a scan; adding one covering index brought p95 to 210 ms. An earlier attempt to 'optimise' the C# mapping code had saved 4 ms and was reverted as noise.

🔍 What the interviewer is checking

Checks whether the candidate follows a disciplined, measurement-first method rather than guessing.

Green flags

  • States a numeric goal with a percentile and a load
  • Measures a baseline before changing anything
  • Classifies the bottleneck (CPU, memory, I/O, contention) before choosing a fix
  • Changes one thing and verifies with the same measurement

Red flags

  • Jumps straight to a favourite optimisation (caching, async, Span)
  • Talks only about averages
  • Never mentions verifying the result

📚 Learn in depth

1. Why measurement comes first

Performance intuition is unreliable because modern stacks are layered: JIT tiering, GC, the ThreadPool, connection pools, the network, the database optimiser. Amdahl's law sets the ceiling: the overall speed-up from improving one part is limited by that part's share of the total. If a component takes 5% of the request time, making it infinitely fast saves at most 5%; halving a component that takes 75% saves 37.5%. That's how you prioritise.

Request 400 ms
|--- auth middleware   10 ms   (2.5%: not worth touching)
|--- EF Core query    300 ms   (75%: halve it, save 150 ms)
|--- mapping + JSON    40 ms   (10%)
|--- downstream HTTP   50 ms   (12.5%)

2. Writing the goal

A good goal has four parts: the operation (GET /search), the load (300 RPS, realistic data), the metric (p95 latency) and the threshold (under 200 ms). Without the load, a single-request test passes while production fails. Without a percentile, you optimise the average and keep the tail.

3. Getting a baseline

The baseline must be taken under the same conditions you'll verify under: the same load profile, data volume, build (Release) and environment size. A baseline from a quiet dev box compared with a verification run on a busy test cluster proves nothing.

  • In production: Application Insights (or OpenTelemetry exported to Azure Monitor) gives per-operation percentiles and dependency breakdowns.
  • On the box: dotnet-counters monitor -p <pid> --counters System.Runtime,Microsoft.AspNetCore.Hosting shows CPU, GC heap, allocation rate, ThreadPool queue length and requests per second live.
  • Under controlled load: k6 or Azure Load Testing with a fixed script, run at least twice to learn the run-to-run noise.

4. Locating the bottleneck: the USE method

For each resource (CPU, memory, ThreadPool, connection pool, database, network) check:

  • Utilisation: how busy it is (CPU at 95%, connection pool 100 of 100 in use).
  • Saturation: work queued because the resource is full (ThreadPool queue length, requests waiting for a pooled connection, SQL wait statistics).
  • Errors: failures caused by the resource (timeouts, InvalidOperationException: pool exhausted, 503s).

A resource with high utilisation and a growing queue is your bottleneck. For example: CPU 30%, but 100 of 100 SQL connections busy and requests waiting for one means the database path is saturated, not the CPU.

5. One change, then verify

Change one variable so the effect is attributable. Several changes at once can cancel each other out (one helps, one regresses), hide a regression in another dimension such as memory or error rate, and make it impossible to know what to keep. Compare against the baseline under the same conditions. If the difference is inside the run-to-run noise, it's not a result. Record what you tried, kept and reverted.

6. Knowing when to stop

Once the goal is met, further work on that path has diminishing returns. Spend the time on the next-worst operation or on a regression test (a load test or benchmark in CI) so the gain isn't lost.

Try it yourself

  1. Run dotnet-counters monitor against a sample API while hitting it with k6 run at increasing rates. Note which counter moves first.
  2. Compute mean, p50, p95 and p99 from a k6 run's output and see how far apart they are.
  3. Add an artificial Thread.Sleep(50) to one endpoint and watch the ThreadPool queue length grow under load.
  4. Write down a performance goal for one endpoint you own using operation, load, metric and threshold.

💻 Code

A tiny endpoint plus the measurement scaffolding: OpenTelemetry metrics for percentiles and a k6 script with a threshold that turns the goal into a pass/fail check.

// Program.cs (.NET 10)
using OpenTelemetry.Metrics;

var builder = WebApplication.CreateBuilder(args);

// Export ASP.NET Core and runtime metrics so p95 and GC/ThreadPool data are visible.
builder.Services.AddOpenTelemetry()
    .WithMetrics(m => m
        .AddAspNetCoreInstrumentation()   // http.server.request.duration histogram
        .AddRuntimeInstrumentation()      // GC, ThreadPool, CPU
        .AddOtlpExporter());

var app = builder.Build();

app.MapGet("/search", async (string q, CancellationToken ct) =>
{
    await Task.Delay(20, ct); // stand-in for real work
    return Results.Ok(new { q, results = Array.Empty<string>() });
});

app.Run();
// search.js: the goal as code. Fails the run if p95 >= 200 ms at 300 RPS.
import http from 'k6/http';

export const options = {
  scenarios: {
    steady: { executor: 'constant-arrival-rate', rate: 300, timeUnit: '1s',
              duration: '2m', preAllocatedVUs: 100 },
  },
  thresholds: { http_req_duration: ['p(95)<200'], http_req_failed: ['rate<0.01'] },
};

export default function () {
  http.get('https://localhost:5001/search?q=boots');
}
# Live view while the load test runs
dotnet-counters monitor -n MyApi --counters System.Runtime,Microsoft.AspNetCore.Hosting

⚠ Common mistakes

  • Mistake: Optimising without measuring. Why it is wrong: You fix what you assume is slow; most of the time is often elsewhere (usually I/O). Instead: Get a baseline and a breakdown first.
  • Mistake: Micro-optimising cold paths. Why it is wrong: Saving microseconds in code that runs once per request costs readability and moves no user-visible number. Instead: Optimise only code that shows up in the profile.
  • Mistake: Targeting the average. Why it is wrong: The mean hides the tail that users complain about. Instead: Set goals on p95/p99.
  • Mistake: Testing with one request on a laptop. Why it is wrong: Contention, pool exhaustion and GC only appear under concurrent load. Instead: Load test at realistic concurrency and data volume.
  • Mistake: Changing several things at once. Why it is wrong: You can't tell which change helped, or which one hurt. Instead: One change per measurement.
  • Mistake: Benchmarking a Debug build. Why it is wrong: The JIT doesn't optimise and timings are meaningless. Instead: Always measure Release builds.
  • Mistake: Declaring victory without re-measuring in production. Why it is wrong: Test data and environments differ. Instead: Compare production percentiles before and after the release.

🏛 Senior insight: trade-offs

Seniors frame performance as a budget and a business conversation: what latency the user journey needs, what it costs to get there, and when to stop. They also know the framework already does a lot (tiered JIT, Dynamic PGO, Kestrel's pooling), so in typical line-of-business services the big wins are usually architectural or I/O-related: fewer round trips, better queries, caching. Algorithmic fixes still matter when the profile shows them: replacing an O(n²) lookup with a dictionary can beat any amount of tuning, so let the measurement decide.

Approach When it fits Cost When not to
Production telemetry first Live service with real users Needs instrumentation in place Brand-new code with no traffic
Load test Before a launch or big change Environment and scripting effort Tiny internal tools
BenchmarkDotNet Comparing two implementations of a hot method Minutes per run Proving end-to-end latency
Profiler (dotnet-trace) You know which operation is slow, not why Some overhead, data to analyse Before you know the bottleneck is CPU

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions dotnet-counters or dotnet-trace Why: Checks they can actually drive the diagnostic tools on a slow endpoint
    How to answer

    First I measure: Application Insights tells me which endpoint is slow and at what percentile, and whether time goes into dependencies like SQL or HTTP. Then I reproduce it on a Release build and run the Visual Studio Performance Profiler (Alt+F2): CPU Usage for hot paths, Database for query count and duration, .NET Object Allocation Tracking for GC pressure, and .NET Async for slow awaits. In an environment where I can't use Visual Studio, dotnet-counters shows live metrics like thread pool queue length and GC, and dotnet-trace captures CPU samples. I fix the biggest cause, often an N+1 query, re-measure against the baseline, and add a load test so it doesn't regress.

  2. When: Candidate mentions CPU is low but latency is high Why: Checks they recognise ThreadPool starvation as a non-CPU bottleneck
    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.

↩ Usually asked after

More in Application Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me