End-to-end investigation of a latency regression after a release: mitigation, comparing before/after telemetry, narrowing to an operation and dependency, profiling, root cause, fix and prevention with performance gates.
First I protect users: if the regression hurts, I roll back or turn off the feature flag, which also confirms the release caused it. If I can capture a short trace in a minute I do; if not, speed wins and I reproduce later in a test environment. I confirm it's abnormal against the historical baseline for the same time and traffic mix.
Then I narrow it down with Application Insights or OpenTelemetry: every operation or one endpoint, every instance or some, and which dependency or in-process span grew. I diff the release: code, package upgrades, config and flags, base image and infrastructure.
Next dotnet-counters tells me the class of problem (CPU, GC, ThreadPool, contention) and dotnet-trace or the Application Insights Profiler shows the code. I reproduce with a load test of old vs new builds, fix, verify p95 in production, and add a performance gate. Throughout, I keep stakeholders updated.
"My first question is impact. 360 milliseconds might be within the SLO or might be breaking checkout. If it hurts users, I roll back or disable the feature flag straight away; if latency returns to normal, I've also proved the release caused it. Before rolling back I grab what I can: a two-minute
dotnet-tracefrom one instance, adotnet-counterssnapshot, so I still have evidence.For example, at [company] we shipped [a release of our orders API] and p95 went from [180] to [360] ms. In Application Insights I split by operation: only [GET /orders/{id}] had moved, on every instance, so it wasn't a bad node. The dependency breakdown showed SQL time flat but in-process time up [170] ms. The release diff included [a logging library upgrade and a new enrichment step].
dotnet-countersshowed allocation rate up [4x] and time in GC up from [2%] to [11%], and a dotnet-trace flame graph pointed at the new enrichment step serialising the entire order to JSON on every request for a debug log that was filtered out anyway. We moved it behind a log-level check usingLoggerMessagesource generation, verified with a k6 comparison of both builds, and p95 returned to [175] ms.The mistake I see is guessing from the commit list instead of letting telemetry narrow the search. The other mistake is fixing it and moving on. I add the endpoint to a load test gate in the pipeline with a p95 budget, and an alert on p95 deviation after deployments, so the next regression is caught before customers notice."
| Step | Question | Tool |
|---|---|---|
| Mitigate | Can we stop the pain now? | Rollback, feature flag, slot swap |
| Confirm | Is it real and release-related? | Deployment annotations, traffic and payload size comparison |
| Scope | Which operations, instances, regions? | Application Insights Performance blade, OpenTelemetry dashboards |
| Locate | Dependency or in-process? | End-to-end transaction view, span breakdown |
| Diff | What changed? | Git diff, package diff (dotnet list package), config and infra changes |
| Classify | CPU, GC, ThreadPool, contention, I/O? | dotnet-counters |
| Pinpoint | Which code? | dotnet-trace / Application Insights Profiler, Query Store for SQL plans |
| Reproduce | Can we see it old vs new? | k6 / Azure Load Testing against both builds |
| Prevent | How do we catch it next time? | Perf gates, alerts, review checklist |
| Cause | Fingerprint |
|---|---|
| New N+1 or missing index | Dependency count or SQL duration up |
| SQL plan change (new parameter, data growth) | Same query text, new plan in Query Store |
| Extra serialisation or logging | Alloc-rate and GC time up |
| Sync-over-async introduced | ThreadPool queue growing, CPU low |
| Package upgrade changing defaults | Diff shows version bump; behaviour change in release notes |
| Config change (timeouts, pool sizes, log level) | No code diff, but config diff |
| Infra (SKU, region, container limits) | All operations slower, CPU throttling |
Removing the unconditional serialisation cut allocation from [480] to [120] MB/s and time in GC from [11%] to [2%], returning p95 to [175] ms. The new load-test gate failed a later PR that added an N+1 query, before it reached production.
Checks whether the candidate can run a structured, evidence-led investigation of a latency regression and leave the system safer.
Green flags
Red flags
Rolling back is the fastest fix and the cleanest experiment, but it destroys the live evidence. A quick capture plan before rollback, run on one instance:
dotnet-counters collect -n OrdersApi --duration 00:01:00 --format csv
dotnet-trace collect -n OrdersApi --profile cpu-sampling --duration 00:01:00
In App Service, the Application Insights Profiler and the Diagnose and solve problems tools can capture traces without shell access; in AKS, dotnet-monitor as a sidecar exposes the same via HTTP.
Slice the p95 by operation, instance, region and dependency. Each split halves the search space:
all requests p95 up?
|-- only one operation --> code path of that operation
|-- all operations --> shared middleware, infra, GC, ThreadPool, a shared dependency
|-- one instance --> bad node, noisy neighbour
|-- all instances --> release-wide change
Then split request time into dependency time and in-process time. Dependency up: look at queries, call counts and downstream services. In-process up: CPU, GC, locks or blocking.
A release includes more than code: package upgrades (transitive too), base image changes, configuration and feature flags, infrastructure-as-code changes, and data migrations that changed indexes or statistics. Release notes for upgraded packages often explain new defaults.
Use dotnet-counters to choose the next tool: CPU high means a CPU trace; alloc-rate or GC time high means allocation profiling; ThreadPool queue growing means a dump of blocked stacks; contention up means a contention trace; nothing in-process means the dependency. Flame graphs in PerfView, Visual Studio or Speedscope show the hottest stacks; compare them between builds.
Run the same k6 script against old and new builds in the same environment, several times, to confirm the delta is beyond noise. After the fix, verify in production over a full traffic cycle (a day or a week for seasonal traffic).
JsonSerializer.Serialize of a large object into a log call and measure p95 and alloc-rate under k6.[LoggerMessage] source-generated method with the level check and measure again.The regression and the fix: unconditional serialisation for a debug log versus a source-generated, level-checked log call.
using System.Text.Json;
namespace Orders.Api;
public sealed record Order(Guid Id, string CustomerId, IReadOnlyList<OrderLine> Lines);
public sealed record OrderLine(string Sku, int Quantity, decimal Price);
public interface IOrderStore
{
Task<Order?> FindAsync(Guid id, CancellationToken ct);
}
// BEFORE (the release): serialises the whole order on every request,
// even though Debug logging is filtered out in production.
public sealed class OrderEnricherBefore(ILogger<OrderEnricherBefore> logger)
{
public void Enrich(Order order)
{
var json = JsonSerializer.Serialize(order); // runs regardless of log level
logger.LogDebug("Enriching order {Order}", json);
}
}
// AFTER: source-generated logging checks IsEnabled before formatting,
// and we only pass cheap values.
public sealed partial class OrderEnricher(ILogger<OrderEnricher> logger)
{
public void Enrich(Order order) => LogEnriching(order.Id, order.Lines.Count);
[LoggerMessage(Level = LogLevel.Debug, Message = "Enriching order {OrderId} with {LineCount} lines")]
private partial void LogEnriching(Guid orderId, int lineCount);
}
// perf-gate.js: run against old and new builds; also used as a pipeline gate.
import http from 'k6/http';
export const options = {
scenarios: { steady: { executor: 'constant-arrival-rate', rate: 200, timeUnit: '1s', duration: '3m', preAllocatedVUs: 80 } },
thresholds: { 'http_req_duration{endpoint:get-order}': ['p(95)<200'] },
};
export default function () {
http.get(`${__ENV.BASE_URL}/orders/3f2c6a1e-0000-0000-0000-000000000001`, { tags: { endpoint: 'get-order' } });
}
A senior runs a regression like an incident: mitigation first, a clear owner, evidence over opinion, regular status updates to the people affected (product owner, support, dependent teams) and a blameless review that ends with a guardrail. The lasting value is the prevention: performance budgets that fail builds and alerts tied to deployments. Without them the team relies on customers to notice.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Immediate rollback | Clear user impact, safe to roll back | Lose features temporarily; evidence lost if not captured | Releases with irreversible migrations |
| Feature flag off | Change is behind a flag | Needs flagging discipline | Changes not flagged |
| Fix forward | Low impact, root cause obvious | Users exposed longer | When unsure of the cause |
| Load-test gate in CI | Critical endpoints | Environment and run time | Low-traffic internal tools |
| Tool | Use it to answer | Not for |
|---|---|---|
| dotnet-counters | Which resource is under pressure (CPU, GC, ThreadPool, locks)? | Which line of code |
| dotnet-trace | Which stacks consume CPU, allocate or wait? | Long-term trend monitoring |
| Application Insights | Which operation, instance and dependency? | In-process internals |
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 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.
Throughput that plateaus with spare CPU points at threads waiting, not working. I confirm with dotnet-counters: monitor-lock-contention-count (the dotnet.monitor.lock_contentions metric) climbing with load. Then I find which lock with dotnet-trace using the contention events (--clrevents contention), which record the waiting stack and duration, or a dotnet-dump where clrstack -all shows dozens of threads in Monitor.Enter on the same object.
Fixes, in order: shrink the critical section and never hold a lock across I/O; replace it with ConcurrentDictionary, Interlocked or an immutable snapshot swapped atomically; or shard the lock per key. Then I verify with the same load test. The trade-off: lock-free designs are harder to get right, so I take the simplest one that removes the contention.
How to tell it (STAR)
**S:** At [company] a routine release doubled p95 on our orders API from [180] to [360] ms, which [mobile checkout] depended on. **T:** I was on call and owned the response. **A:** I captured a short trace, then rolled back by slot swap, which brought latency back and confirmed the release. In Application Insights the regression was one endpoint, in-process time, and counters showed allocations up [4x]. The flame graph pointed at a new debug log serialising every order. I switched it to source-generated logging, proved parity with a k6 comparison, and added a load-test gate and logging analysers. **R:** p95 returned to [175] ms, and the new gate later blocked an N+1 regression before release.
Last updated 23 Nov 2026.