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.
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.
"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-countersfor 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-tracefor CPU,dotnet-gcdumpfor 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."
| 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 |
| 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 |
| 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 |
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.
Checks whether the candidate follows a disciplined, measurement-first method rather than guessing.
Green flags
Red flags
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%)
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.
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.
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.For each resource (CPU, memory, ThreadPool, connection pool, database, network) check:
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.
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.
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.
dotnet-counters monitor against a sample API while hitting it with k6 run at increasing rates. Note which counter moves first.Thread.Sleep(50) to one endpoint and watch the ThreadPool queue length grow under load.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
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 |
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.
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.
Last updated 23 Nov 2026.