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

📚 Interview question

After a release, one of your services' p95 latency doubled from 180 ms to 360 ms, with no errors and no obvious change in traffic. Walk me through your end-to-end investigation and fix.

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.

Senior RealWorldScenario Advanced application-insights dotnet-trace incident-response latency-regression performance release

🎯 Key points

  • Mitigate first: roll back or flip the feature flag if impact justifies it; speed beats evidence when users are hurting
  • Confirm it's abnormal against historical baselines (same weekday/hour, same traffic mix) and tied to the deployment annotation
  • Narrow down: which operations, which instances, which dependencies (Application Insights / OpenTelemetry)
  • Diff the whole release: code, direct and transitive package versions, configuration and flags, base image, infrastructure, migrations
  • dotnet-counters to classify (CPU, GC, ThreadPool, contention); dotnet-trace or the Profiler to pinpoint the code
  • Reproduce with a load test comparing old and new builds
  • Communicate status to stakeholders throughout; blameless review afterwards
  • Prevent: performance budget, load test or benchmark gates in CI, alerts on p95

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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-trace from one instance, a dotnet-counters snapshot, 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-counters showed 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 using LoggerMessage source 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."


Investigation path

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

Common causes of release regressions

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can run a structured, evidence-led investigation of a latency regression and leave the system safer.

Green flags

  • Mitigates first while preserving evidence
  • Narrows by operation, instance and dependency using telemetry
  • Diffs code, packages, config and infra
  • Uses counters to choose the right profiler
  • Adds a performance gate and alert afterwards

Red flags

  • Starts reading code before looking at telemetry
  • Never considers rollback
  • Stops at the fix with no prevention

📚 Learn in depth

1. Mitigation vs evidence

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.

2. Narrowing with telemetry

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.

3. Diffing the release

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.

4. Classify then profile

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.

5. Reproduce and verify

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).

6. Prevent

  • A performance budget per critical endpoint (p95 at a stated RPS) enforced by a load test stage.
  • BenchmarkDotNet for hot library code, compared with the main branch.
  • Alerts on p95 relative to the pre-deployment baseline (Azure Monitor dynamic thresholds).
  • A blameless post-incident review with actions tracked.

Try it yourself

  1. Add an unconditional JsonSerializer.Serialize of a large object into a log call and measure p95 and alloc-rate under k6.
  2. Replace it with a [LoggerMessage] source-generated method with the level check and measure again.
  3. Set up Application Insights deployment annotations from your pipeline.
  4. Write a k6 threshold that fails if p95 exceeds 200 ms and wire it into a pipeline stage.

💻 Code

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' } });
}

⚠ Common mistakes

  • Mistake: Optimising without measuring, by guessing from the commit list. Why it is wrong: Releases contain many changes; the obvious suspect is often innocent. Instead: Let telemetry narrow to an operation, a span and a resource first.
  • Mistake: Micro-optimising cold paths found while investigating. Why it is wrong: It burns incident time on code that didn't regress. Instead: Fix the regression; log other ideas as backlog items.
  • Mistake: Not mitigating while investigating. Why it is wrong: Users suffer for hours while you profile. Instead: Roll back or flag off when impact justifies it, after a quick evidence capture.
  • Mistake: Rolling back without capturing anything. Why it is wrong: You may be unable to reproduce it later. Instead: Grab a short trace and counters first.
  • Mistake: Ignoring non-code changes. Why it is wrong: Package defaults, config, base images and infra cause many regressions. Instead: Diff everything that shipped.
  • Mistake: Comparing different traffic. Why it is wrong: A new customer with bigger payloads can look like a regression. Instead: Compare the same operation, payload size and time of day.
  • Mistake: Declaring it fixed after one quiet hour. Why it is wrong: Traffic patterns vary. Instead: Verify across a full traffic cycle.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions baselines or measuring before and after Why: Checks the general measurement method behind the investigation
    How to 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.

  2. When: Candidate mentions dotnet-counters Why: Checks they can classify the bottleneck from counters
    How to 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.

  3. When: Candidate mentions throughput flattening with low CPU Why: Checks they can diagnose lock contention as one cause
    How to answer

    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.

🛠 Real-world problems: how you handle them

p95 doubles after a release because a debug log serialises every order
Situation
An orders API on [Azure App Service, 4 instances] serving [1,500] RPS at peak; [mobile checkout] depends on it. A routine release went out on [a Tuesday morning].
Signals
Azure Monitor alert: p95 for GET /orders/{id} from [180 ms] to [360 ms]; no errors; CPU up [15 points]; dotnet-counters showed alloc-rate [4x] and time-in-gc from [2%] to [11%].
Investigation
Application Insights deployment annotation lined up with the change; split by operation and instance showed one endpoint on all instances; dependency time unchanged, in-process time up. Captured dotnet-trace cpu-sampling on one instance before rollback; flame graph in PerfView showed JsonSerializer.Serialize under OrderEnricher. Release diff showed the new enrichment step with a debug log.
Resolution
Rolled back via slot swap within [20 minutes]. Fixed by replacing the serialise-then-log call with a LoggerMessage source-generated method logging only the id and line count; k6 comparison of old and new builds confirmed parity; redeployed.
Prevention
Added a k6 load-test stage with a p95 threshold for the top [5] endpoints; enabled CA1848/CA2254 logging analysers; added an Azure Monitor dynamic-threshold alert on p95 after deployments; blameless review shared with the team.

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.

↩ Usually asked after

More in Application Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me