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

📚 Interview question

One endpoint is slow only in production: p95 is 3 seconds there but 150 ms in staging and locally, and you can't reproduce it. What is your plan to find out why, which tools do you use at each step, and how do you prove the fix?

A production-only slow endpoint with no repro: listing what differs in production (data, concurrency, configuration, dependencies, tenants), slicing telemetry to isolate the slow subset, then targeted evidence from distributed traces, Query Store, the Application Insights Profiler and dotnet-monitor triggers, and proving the fix with production percentiles.

Senior RealWorldScenario Advanced application-insights incident-response performance production profiling query-store

🎯 Key points

  • Treat 'can't reproduce' as information: list what differs (data volume/skew, concurrency, config, dependencies, network, tenant)
  • Slice telemetry first: which requests are slow (tenant, parameters, instance, time, payload size) using Application Insights/KQL
  • End-to-end transaction view: is the time in a dependency (SQL, HTTP) or in-process?
  • Dependency time → Query Store/execution plans: parameter sniffing on skewed data; SQL Server 2022/Azure SQL Parameter Sensitive Plan optimisation (compat level 160) may already help
  • In-process time → Application Insights Profiler or a dotnet-monitor trace triggered on slow requests
  • Low CPU with waits → counters for ThreadPool queue and contention, connection pool exhaustion
  • Reproduce with the identified input (production-like synthetic data for that slice) before fixing
  • Prove it: same slice's p95 before/after in production, plus a regression test or alert

⏱ 30-second answer

'Only in production' is a clue, not a dead end: something differs. I list the candidates (data volume and skew, concurrency, configuration, dependencies, network, specific tenants) and let telemetry eliminate them.

  1. Slice the slow requests in Application Insights: by tenant, parameters, instance, time and payload size. Usually a subset is slow, not everything.
  2. Open end-to-end transactions for slow requests: is the time in SQL or HTTP dependencies, or in-process?
  3. Dependency time → Query Store and execution plans (parameter sniffing, skewed data). In-process time → Application Insights Profiler or a dotnet-monitor trace triggered on slow requests.
  4. Reproduce with the identified input, fix, and prove it with the same slice's p95 in production.

The trade-off: production evidence is the only real evidence, but every capture there costs overhead and data exposure, so I collect narrowly.

🗣 Full answer (senior)

How I would answer this in an interview

"When something is slow only in production, I assume the environment is the variable, not the code, and I write down what's different: data volume and skew, real concurrency, configuration, dependency latency, network path, and which customers use it. Then I use telemetry to narrow it down before touching any profiler.

The first move is slicing. In Application Insights I query the endpoint's requests and split duration by tenant, by parameter values, by instance and by hour. Almost always the p95 is driven by a subset. For example, at [company] [an orders endpoint was 150 ms for most customers and 6 seconds for three large ones]. Then I open end-to-end transactions for a few slow requests. That view tells me whether the time is in a SQL or HTTP dependency or inside our process. In that case one SQL call took 5.8 seconds. Query Store showed the query had two plans: a seek plan compiled for a small customer and reused for everyone, which became a disaster for customers with [2 million] orders. Classic parameter sniffing on skewed data, which staging could never show because staging didn't have a customer that size. We fixed it with a better index and OPTION (OPTIMIZE FOR UNKNOWN) on that one query, and p95 for those customers dropped to [400 ms].

If the time is in-process instead, I use the Application Insights Profiler, which links sampled traces to slow requests, or a dotnet-monitor collection rule that captures a trace when request duration crosses a threshold. If CPU is low and requests are waiting, I look at ThreadPool queue length, lock contention and connection pool counters. The mistake I see is trying to reproduce first, with random local data, and giving up. Find the slow slice in production, then reproduce with that input."


What differs in production

Difference Typical cause Evidence
Data volume and skew Plan chosen for small values, missing index at scale Query Store, actual plans, slow only for some tenants
Concurrency Lock contention, pool exhaustion, ThreadPool starvation Counters, waits, slow under load only
Configuration Logging level, feature flag, timeouts, retry policy, GC mode Config diff, App Configuration history
Dependencies Real third-party latency, throttling (429), DNS Dependency telemetry, status codes
Network Cross-region calls, private endpoints, TLS handshakes Dependency target and duration by region
Instance One noisy node, one zone, one bad deployment slot Duration split by cloud_RoleInstance

Step by step

Step Tool Output
1. Slice Application Insights / KQL Which subset is slow
2. Locate End-to-end transaction view Dependency or in-process
3a. Dependency Query Store, execution plans, dependency status codes Plan regression, skew, throttling
3b. In-process AI Profiler, dotnet-monitor triggered trace Hot stack for slow requests
3c. Waiting dotnet-counters, contention events, dump if hung Starvation, locks, pools
4. Reproduce Production-like data for that slice Local or staging repro
5. Prove Same KQL slice before/after p95 change for the affected subset

Production example

The orders endpoint above: p95 3 s overall, but 150 ms for 97% of tenants and 6 s for three large ones. Query Store showed a regressed plan after a statistics update; a covering index and a targeted query hint brought the large tenants to 400 ms, and the overall p95 to 170 ms. A Query Store regression alert and a staging dataset with one synthetic 'large tenant' now catch this class of problem.

🔍 What the interviewer is checking

Checks whether the candidate has a systematic way to investigate production-only performance problems without guessing or giving up.

Green flags

  • Treats 'production only' as a list of differences to eliminate
  • Slices telemetry before profiling
  • Separates dependency time from in-process time
  • Knows data skew and parameter sniffing as a classic production-only cause; proves the fix on the same slice

Red flags

  • Keeps trying to reproduce locally with random data
  • Jumps straight to a full dump
  • Proves the fix with the overall average

📚 Learn in depth

1. The isolation mindset

 all requests to GET /orders
    │ slice by tenant / params / instance / time / size
    ▼
 slow subset (e.g. 3 tenants, page=1, > 1M rows)
    │ end-to-end transaction
    ▼
 where the time is
    ├─ SQL dependency ──▶ Query Store, plan, waits, stats
    ├─ HTTP dependency ─▶ status codes, retries, target region, DNS
    └─ in-process     ──▶ Profiler trace / dotnet-monitor / counters

Each step halves the search space. You only bring out heavy tools once you know where to point them.

2. Slicing with KQL

In Application Insights (or Log Analytics with workspace-based resources), requests has duration, cloud_RoleInstance, customDimensions and resultCode. Adding the tenant ID and key parameters as custom dimensions (without personal information) is what makes slicing possible. Percentiles per slice show whether the problem is universal or concentrated.

3. Data skew and parameter sniffing

SQL Server compiles a plan using the first parameter values it sees (sniffing) and caches it. With skewed data (one tenant with 2 million rows, most with 200), a plan that is ideal for a small tenant (nested loops and key lookups) can be terrible for a large one, and vice versa. Staging rarely has the skew, so it never reproduces. Evidence: Query Store shows multiple plans for the query with very different durations, or one plan whose duration varies hugely by execution. Options: better indexes (covering, so both cases are cheap), OPTIMIZE FOR UNKNOWN, RECOMPILE for rare expensive queries, Query Store plan forcing as a mitigation, and on SQL Server 2022 / Azure SQL, Parameter Sensitive Plan optimisation, which can cache several plans per query.

4. In-process time

If the transaction shows a gap with no dependency, the time is in your process: CPU (serialisation, regex, big LINQ over large results), waiting (locks, ThreadPool starvation, SemaphoreSlim), or GC pauses. The Application Insights Profiler gives sampled traces tied to request IDs. dotnet-monitor can run a trace when AspNetRequestDuration crosses a threshold. Correlate with dotnet-counters: high CPU → hot code; low CPU and growing ThreadPool queue → blocking; high time-in-gc → allocations (often from loading large result sets for big tenants).

5. Reproducing with the right input

Once you know the slice, build a reproduction with production-like data for it: a masked or synthetic copy with the same row counts and distribution (never raw customer data on a laptop). Then BenchmarkDotNet, local profiling and plan analysis all work normally.

6. Proving the fix

Compare the same slice before and after with the same KQL: p50/p95/p99 and request counts over comparable periods (same weekday and hour). An overall p95 can improve for unrelated reasons, or hide the slice. Keep the slice query as a dashboard tile or alert.

Try it yourself

  1. Add tenant ID as a custom dimension in an ASP.NET Core API with OpenTelemetry and write a KQL query for p95 by tenant.
  2. Create a table with skewed data (one key with 1M rows, others with 100) and show parameter sniffing in SQL Server with Query Store.
  3. Fix it with a covering index and compare plans; then try OPTION (RECOMPILE) and note the CPU cost.
  4. Configure a dotnet-monitor rule on AspNetRequestDuration and trigger it with a slow endpoint.

💻 Code

Slicing the slow endpoint in Application Insights, finding the regressed query in Query Store, and the fix.

// Which subset is slow? p95 by tenant for one endpoint, last 24 hours
requests
| where timestamp > ago(24h) and name == "GET /api/orders"
| extend tenant = tostring(customDimensions["tenant.id"])
| extend tenant = iff(isempty(tenant), "(unknown)", tenant)   // untagged requests stay visible
| summarize requests = count(),
            p50 = percentile(duration, 50),
            p95 = percentile(duration, 95) by tenant
| where requests >= 50                                          // ignore tiny, noisy slices
| order by p95 desc
| take 10
-- Query Store: queries with more than one plan and a big spread in duration
SELECT q.query_id, p.plan_id, rs.count_executions,
       rs.avg_duration / 1000.0 AS avg_ms, rs.max_duration / 1000.0 AS max_ms
FROM sys.query_store_query AS q
JOIN sys.query_store_plan AS p ON p.query_id = q.query_id
JOIN sys.query_store_runtime_stats AS rs ON rs.plan_id = p.plan_id
WHERE q.query_id IN (SELECT query_id FROM sys.query_store_plan GROUP BY query_id HAVING COUNT(*) > 1)
ORDER BY rs.max_duration DESC;

-- Is Parameter Sensitive Plan optimisation available? (needs compatibility level 160+)
SELECT name, compatibility_level FROM sys.databases WHERE name = DB_NAME();

-- Fix: a covering index that makes the query cheap for small and large tenants
CREATE INDEX IX_Orders_TenantId_CreatedAt
    ON dbo.Orders (TenantId, CreatedAt DESC)
    INCLUDE (Status, Total, CustomerName);

Adding the tenant as a telemetry dimension (not personal data) so slicing is possible:

using System.Diagnostics;

namespace Orders.Api;

public sealed class TenantTelemetryMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext context)
    {
        // Tag the current request activity; exported by OpenTelemetry / Azure Monitor
        // as customDimensions["tenant.id"]. Never tag names, emails or other PII.
        if (context.User.FindFirst("tenant_id")?.Value is { } tenantId)
        {
            Activity.Current?.SetTag("tenant.id", tenantId);
        }
        await next(context);
    }
}

// Program.cs
// app.UseAuthentication();
// app.UseMiddleware<TenantTelemetryMiddleware>();

⚠ Common mistakes

  • Mistake: Optimising without measuring: changing code that 'might' be slow and redeploying to see. Why it is wrong: Each guess costs a release and usually misses. Instead: Slice telemetry and locate the time first.
  • Mistake: Micro-optimising cold paths in the endpoint while the time is in one SQL call. Why it is wrong: In-process code was 2% of the request. Instead: Follow the end-to-end transaction to where the time actually goes.
  • Mistake: Trying to reproduce with random local data and concluding 'works on my machine'. Why it is wrong: The difference is usually data volume, skew or concurrency. Instead: Find the slow slice, then reproduce with that input.
  • Mistake: Looking only at overall p95. Why it is wrong: It hides that a few tenants or parameters are slow. Instead: Split percentiles by tenant, parameters, instance and time.
  • Mistake: Clearing the plan cache or restarting SQL to 'fix' a plan regression. Why it is wrong: The bad plan comes back on the next unlucky compile. Instead: Fix the index or query. On SQL Server 2022 / Azure SQL at compatibility level 160, check whether Parameter Sensitive Plan optimisation already gives the query several plans; use Query Store hints or plan forcing as a stable mitigation while the real fix ships, and remember forcing can fail silently after schema changes.
  • Mistake: Copying production data to a laptop to reproduce. Why it is wrong: Privacy Act and security exposure. Instead: Masked or synthetic data with the same distribution.
  • Mistake: Not having tenant or parameter dimensions in telemetry. Why it is wrong: You can't slice what you didn't record. Instead: Add non-personal dimensions before you need them.
  • Mistake: Declaring victory on the overall average after the fix. Why it is wrong: The affected slice may be unchanged. Instead: Compare the same slice's p95 over comparable periods.

🏛 Senior insight: trade-offs

'Can't reproduce' usually means 'haven't found the variable yet'. The senior approach is to let production telemetry do the reproduction: if requests are tagged with tenant and key parameters and traces show dependency timings, most production-only problems are located in minutes, before anyone opens a profiler. The other senior habit is designing staging to fail the same way: a synthetic 'whale' tenant with production-scale data catches skew and missing-index problems that average-sized test data never will.

Evidence source When it fits Cost When not to
KQL slicing of requests Always first Needs good dimensions —
End-to-end transaction view Locating dependency vs in-process time Sampling may drop some traces Problems inside a single dependency call
Query Store and plans SQL time dominates Read access to the database In-process CPU problems
AI Profiler / dotnet-monitor trace In-process time dominates Overhead while capturing; security setup Time is in a dependency
Full dump Hangs, native memory Pause, sensitive data Plain slowness

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions capturing traces in production with dotnet-monitor or the Application Insights Profiler Why: Checks they can do production profiling safely, with overhead and privacy in mind
    How to answer

    Safe production profiling means cheap signals always on and heavy captures rare, short and controlled.

    • Always on: runtime metrics and distributed traces through OpenTelemetry to Azure Monitor.
    • On demand: dotnet-monitor as a sidecar exposes trace, gcdump and dump endpoints over an authenticated API, with collection rules that capture automatically on a trigger (CPU, heap size, slow requests) and egress to Blob Storage.
    • Sampled continuous profiling: the Application Insights Profiler captures short traces and ties them to slow requests. The classic SDK version is GA; the OpenTelemetry-based profiler is still preview as of late 2026.

    I limit blast radius to one instance, and treat dumps as production data under the Privacy Act. The trade-off is evidence versus risk: a full dump answers anything but pauses the process and copies every secret in memory.

  2. When: Candidate mentions comparing before and after a release Why: Checks their approach to a latency regression that follows a deployment
    How to 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.

  3. When: Candidate mentions reproducing locally once the slow input is known Why: Checks they can use the Visual Studio profiler and CLI tools on a local repro
    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.

🛠 Real-world problems: how you handle them

Orders endpoint slow only for the largest tenants because of parameter sniffing
Situation
A multi-tenant B2B orders API on [Azure App Service and Azure SQL, Australia East] served [~600] tenants. GET /api/orders had p95 [3 s] in production but [150 ms] in staging, and the largest customers were escalating to account managers.
Signals
Application Insights p95 alert on the endpoint; support tickets from [3] enterprise customers; no errors; app CPU normal; overall database DTU moderate.
Investigation
KQL on requests split by tenant.id showed [97%] of tenants at p95 [150 ms] and three tenants at [6 s]. End-to-end transactions for those requests showed [5.8 s] in a single SQL dependency. Query Store showed two plans for the query: a nested-loop seek plan with key lookups, compiled for a small tenant and reused, running [5–6 s] for tenants with [~2 million] orders. Staging's largest tenant had [20,000] orders, so it never showed the problem.
Resolution
Immediate: forced the better plan with Query Store for the affected query. Fix: a covering index on (TenantId, CreatedAt DESC) with included columns, keyset pagination instead of OFFSET, and OPTIMIZE FOR UNKNOWN on that query; then removed the forced plan. Large-tenant p95 fell to [400 ms], overall p95 to [170 ms].
Prevention
A synthetic 'whale' tenant with [2 million] orders in staging; a k6 scenario for it in the release pipeline; a Query Store regressed-query alert; tenant.id as a standard telemetry dimension with a dashboard of p95 by tenant.

How to tell it (STAR)

**S:** At [company] our orders endpoint had a p95 of [3 seconds] in production but [150 ms] everywhere else, and our biggest customers were complaining. **T:** I took the investigation and needed an answer without a local repro. **A:** I sliced the request telemetry by tenant in Application Insights and found only three large tenants were slow. Their transactions showed almost all the time in one SQL query, and Query Store showed a plan compiled for a small tenant being reused for customers with [2 million] orders. I forced the good plan as a mitigation, then added a covering index, keyset pagination and a targeted hint, and removed the forced plan. **R:** Large-tenant p95 went from [6 seconds] to [400 ms], escalations stopped, and a synthetic large tenant in staging has since caught [two] similar regressions before release.

More in Profiling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me