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

๐Ÿ“š Interview question

Your dashboard shows an average response time of 120 ms and everyone is happy, but customers say the site is slow. Why are averages misleading for latency? Explain p50, p95, p99 and p99.9, how percentiles are calculated from histograms, and why you can't average percentiles across instances or time windows.

Covers why averages hide tail latency, what p50/p95/p99/p99.9 mean, how percentiles are estimated from histogram buckets, why percentiles cannot be averaged, and how to query them in Prometheus and KQL.

Intermediate Theory Intermediate kql latency metrics observability percentiles promql

๐ŸŽฏ Key points

  • Average is pulled by outliers and hides the tail: 95×50 ms + 5×3 s averages ~198 ms
  • p99 = 99% of requests were at or faster than this value
  • Fan-out amplifies the tail: 1 − 0.99^10 ≈ 10% of 10-call pages hit a p99
  • Percentiles are estimated from histogram buckets; put boundaries near the SLO threshold
  • Never average percentiles: merge the histograms, then take the quantile
  • PromQL: histogram_quantile(0.99, sum by (le) (rate(..._bucket[5m])))
  • KQL: percentile(duration, 99) on raw requests, with count() beside it
  • Alert on SLO burn rate of p95/p99, not on a raw noisy p99

โฑ 30-second answer

An average mixes fast and slow requests into one number that describes almost nobody. If 95 requests take 50 ms and 5 take 3 s, the average is (95 ร— 50 + 5 ร— 3,000) / 100 โ‰ˆ 198 ms, which looks fine while 1 in 20 customers waits 3 seconds. Percentiles describe the distribution: p50 is the typical request, p95/p99 is the slow tail people complain about.

Percentiles come from a histogram: count requests into buckets, then find the bucket where 99% of the count is reached and interpolate (put bucket boundaries close to your SLO threshold so the estimate is tight). Because a percentile is not additive, you cannot average p99 across pods or time windows; you merge the bucket counts first and then take the quantile, which is what histogram_quantile(0.99, sum by (le) (rate(...[5m]))) does.

The trade-off: high percentiles need enough traffic and well-chosen buckets to be trustworthy, so chart the request count next to them and alert on SLO burn rate rather than a raw p99.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"Latency is never a bell curve. It has a long right tail: most requests are quick, a few hit a cold cache, a lock, a GC pause or a slow dependency and take 10 to 100 times longer. An average blends those together. If 95 requests take 50 ms and 5 take 3 seconds, the average is about 200 ms, which reads as healthy, while one customer in twenty waits three seconds. That is exactly the 'dashboard green, customers angry' situation.

So I look at percentiles. p50 is the median, the typical experience. p95 means 95% of requests were at or faster than that value; p99 is the 1-in-100 experience. And the tail matters more than it sounds: a page that makes 10 back-end calls in parallel is only as fast as the slowest one, so the chance it hits at least one p99-slow call is about 1 โˆ’ 0.99ยนโฐ, roughly 10%. In practice I chart p50, p95 and p99 together, and I set SLOs on p95 or p99 with a request count next to them.

The mechanics matter too. Percentiles are calculated from a histogram: requests are counted into buckets, and the backend finds the bucket where the cumulative count crosses 99% and interpolates inside it. That has two consequences. First, accuracy depends on bucket boundaries: if your buckets jump from 1 s to 5 s, your p99 can only say 'somewhere in there'. Second, you cannot average percentiles. The mean of four pods' p99 values is not the fleet's p99, and the mean of 60 one-minute p99s is not the hour's p99. You merge the bucket counts and then compute the quantile once.

The mistake I see is a dashboard tile called 'p99' that is actually avg() of per-pod p99s. It understates the tail exactly when one pod is sick."


What each percentile tells you

Statistic Meaning Use it for
Average Sum / count Capacity maths (throughput ร— mean = concurrency), not user experience
p50 Half of requests faster Typical experience, regressions in the common path
p95 1 in 20 slower Common SLO target for interactive APIs
p99 1 in 100 slower Tail problems: GC, locks, cold caches, retries
p99.9 1 in 1,000 slower Very high-volume or latency-critical paths; needs lots of traffic
Max Single worst request Spotting outliers; too noisy to alert on

Averaging vs merging

Approach Correct? Why
avg(p99 per pod) No A sick pod with 10% of traffic barely moves the average
max(p99 per pod) Useful signal, not the fleet p99 Good for spotting the worst instance
Sum bucket counts, then quantile Yes Quantile of the combined distribution
Raw-event percentile (KQL percentiles() on requests) Yes (approximate, uses t-digest) Works on stored events, costs query time

Production example

A checkout API showed a 120 ms average and p50 of 60 ms, but p99 was 4.1 s. Breaking p99 down by route showed it came from one payment endpoint whose retry policy waited 2 s on timeouts. Lowering the timeout and adding a hedged call cut p99 to 650 ms and checkout abandonment dropped by [x]%.

๐Ÿ” What the interviewer is checking

Checks that the candidate understands latency distributions and won't build misleading dashboards or SLOs.

Green flags

  • Explains tail amplification with fan-out
  • Knows percentiles come from histogram buckets and why boundaries matter
  • States clearly that percentiles can't be averaged and how to merge correctly
  • Mentions request count and low-volume noise

Red flags

  • Thinks p99 means 'the 99th slowest request'
  • Builds a fleet p99 with avg()
  • Uses the average for SLOs

๐Ÿ“š Learn in depth

1. Why latency has a tail

Request time = queueing + work + waiting on dependencies. Each of those has occasional big delays: a Gen2 GC pause, a thread pool injection delay, lock contention, a cache miss, a TCP retransmit, a cold connection, a retry. They are rare, so they don't move the median, but they dominate the tail.

count
  โ”‚โ–ˆ
  โ”‚โ–ˆโ–ˆ
  โ”‚โ–ˆโ–ˆโ–ˆโ–ˆ
  โ”‚โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ
  โ”‚โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–„โ–„โ–ƒโ–ƒโ–‚โ–‚โ–‚โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ– ....... โ–
  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ latency
     p50   p95        p99                 max

2. Tail amplification

If a user action needs N independent calls and each has a 1% chance of being p99-slow, the chance that the action is slow is 1 โˆ’ 0.99^N:

Calls per action Chance of at least one p99-slow call
1 1%
10 ~10%
100 ~63%

This is why a back end's p99 becomes a front end's p50 in microservice systems.

3. How a histogram percentile is estimated

Given cumulative bucket counts:

le=0.05  โ†’ 900
le=0.1   โ†’ 960
le=0.25  โ†’ 985
le=0.5   โ†’ 994
le=1     โ†’ 999
le=+Inf  โ†’ 1000

p99 is the 990th request. It falls in the (0.25, 0.5] bucket, which holds requests 986 to 994. Linear interpolation: 0.25 + (990 โˆ’ 985) / (994 โˆ’ 985) ร— 0.25 โ‰ˆ 0.39 s. The true value could be anywhere in that bucket; finer buckets around your SLO threshold give better answers. Native/exponential histograms (Prometheus native histograms, OpenTelemetry exponential histograms) pick boundaries automatically with bounded relative error.

4. Why you can't average percentiles

Pod A: 900 requests, p99 = 100 ms. Pod B: 100 requests, p99 = 3 s. The average of the p99s is 1.55 s, but the real fleet p99 is close to the 10th slowest request overall, which depends on the combined distribution, not on either number. Percentiles are order statistics, not sums, so they do not compose. Bucket counts are sums, so they do.

5. Querying correctly

Prometheus (OpenTelemetry names converted to Prometheus style):

histogram_quantile(0.99,
  sum by (le, http_route) (
    rate(http_server_request_duration_seconds_bucket[5m])))

Application Insights stores each request, so KQL computes percentiles from raw events (with an approximate t-digest algorithm):

requests
| where timestamp > ago(1h)
| summarize count(), p50 = percentile(duration, 50), p95 = percentile(duration, 95), p99 = percentile(duration, 99)
    by bin(timestamp, 5m), name

Note that the Azure Monitor exporter sends OpenTelemetry histograms as count, sum, min and max, so for percentiles in Application Insights use the requests/dependencies tables or Azure Monitor managed Prometheus, not customMetrics.

6. Low volume and noise

p99 over 50 requests is effectively the maximum. Always show the request count next to the percentile, use longer windows for low-traffic routes, and don't alert on p99.9 unless you have thousands of requests per window.

Try it yourself

  1. Generate 1,000 durations where 5% are 3 s and compute the mean, p50 and p99 in a small C# console app.
  2. Run k6 against an endpoint with a random 2% Task.Delay(2000) and compare the k6 summary's avg, p(95) and p(99).
  3. In Prometheus, compare avg(histogram_quantile(...) by pod) with histogram_quantile(0.99, sum by (le) (...)) while one pod is slowed down.
  4. Change histogram bucket boundaries with InstrumentAdvice and see how much the reported p99 moves.
  5. Run the KQL query above on an Application Insights resource and add count() to see how noisy p99 is on quiet routes.

๐Ÿ’ป Code

Show the gap between average and percentiles, and the averaging trap, in a few lines:

namespace LatencyDemo;

public static class Program
{
    public static void Main()
    {
        var rng = new Random(42);
        // 95% fast (30-70 ms), 5% slow (2-4 s): a realistic long tail
        double[] podA = [.. Enumerable.Range(0, 900).Select(_ => rng.NextDouble() < 0.95 ? 30 + rng.Next(40) : 2000 + rng.Next(2000))];
        // A healthy pod with little traffic
        double[] podB = [.. Enumerable.Range(0, 100).Select(_ => 30.0 + rng.Next(40))];

        Console.WriteLine($"Pod A  avg={podA.Average():F0} p50={P(podA, 50):F0} p99={P(podA, 99):F0}");
        Console.WriteLine($"Pod B  avg={podB.Average():F0} p50={P(podB, 50):F0} p99={P(podB, 99):F0}");

        var wrong = (P(podA, 99) + P(podB, 99)) / 2;   // averaging percentiles
        var right = P([.. podA, .. podB], 99);          // merge first, then quantile
        Console.WriteLine($"avg of p99s = {wrong:F0} ms, true fleet p99 = {right:F0} ms");
    }

    // Nearest-rank percentile on raw samples
    private static double P(double[] values, double percentile)
    {
        var sorted = values.Order().ToArray();
        var rank = (int)Math.Ceiling(percentile / 100 * sorted.Length) - 1;
        return sorted[Math.Clamp(rank, 0, sorted.Length - 1)];
    }
}
-- KQL (Application Insights): percentiles with the volume next to them
requests
| where timestamp > ago(1h)
| summarize requests = count(), avg_ms = avg(duration),
            p50 = percentile(duration, 50), p95 = percentile(duration, 95), p99 = percentile(duration, 99)
    by name
| order by p99 desc

โš  Common mistakes

  • Mistake: Reporting only the average response time. Why it is wrong: a 5% slow tail barely moves it while many customers suffer. Instead: chart p50, p95 and p99 together.
  • Mistake: Averaging per-pod or per-minute p99 values. Why it is wrong: percentiles are not additive, so the result is not the fleet or hourly p99. Instead: sum histogram buckets first, then apply histogram_quantile, or compute from raw events.
  • Mistake: Using bucket boundaries that are too coarse around the SLO. Why it is wrong: the estimate can be off by the whole bucket width. Instead: put boundaries close to your threshold (for example 0.2, 0.3, 0.5 s) or use exponential histograms.
  • Mistake: Alerting on p99.9 for a route with 30 requests a minute. Why it is wrong: it is just the maximum and flaps constantly. Instead: use longer windows or a lower percentile, and show the count.
  • Mistake: Mixing successful and failed requests in one latency percentile. Why it is wrong: fast 500s can make latency look better during an outage. Instead: filter latency SLIs to successful requests and track errors separately.
  • Mistake: Assuming Application Insights customMetrics gives percentiles of OpenTelemetry histograms. Why it is wrong: the exporter sends count, sum, min and max. Instead: use the requests table or managed Prometheus for percentiles.

๐Ÿ› Senior insight: trade-offs

Percentiles are for user experience; averages are still right for capacity maths (Little's law: concurrency = throughput ร— mean latency). A senior answer keeps both and knows which question each answers. The other senior signal is knowing where percentiles come from: buckets for pre-aggregated metrics, raw events for logs and traces, each with different accuracy and cost.

Source of percentiles When it fits Cost When not to
Prometheus histogram buckets High volume, fleet-wide p99, SLOs buckets ร— tag sets series Very high-cardinality tags
Exponential / native histograms Accurate tails without tuning boundaries Similar or lower than classic buckets Backends that don't support them
Raw events (KQL percentile()) Ad-hoc slicing by any field Ingestion and query cost per event Long windows over sampled data without adjusting
Client-side summaries (pre-computed quantiles) Single-process tools Cheap Anything you need to aggregate across instances

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions load testing or coordinated omission. Why: Checks they measure percentiles correctly under load, not just in production.
    How to answer

    A useful load test answers a specific question: can we handle peak, where do we break, or do we degrade over hours. So I choose the test type (load, stress, soak or spike) and model the real workload: the endpoint mix, data volumes, auth and cache hit rates, in a production-like environment.

    I use an open model (a target arrival rate, like k6's constant-arrival-rate) because a closed model with a fixed number of virtual users slows down when the server does, which causes coordinated omission and hides the tail.

    I report p50, p95 and p99 and error rate, never averages, and read them next to server-side metrics to see which resource saturates first. The trade-off: realistic tests cost environment and data effort, but unrealistic ones give confident wrong answers.

  2. When: Candidate talks about latency as one of the key signals. Why: Checks they have a framework for choosing metrics, not just latency.
    How to answer

    RED is for services that handle requests: Rate (requests per second), Errors (failed requests, usually 5xx and timeouts, as a ratio) and Duration (latency distribution, p50/p95/p99). It answers 'are users hurting?'. 4xx responses are normally the caller's mistake, so track them separately rather than in the error ratio.

    USE is for resources: for each CPU, memory, disk, connection pool, thread pool or database, check Utilisation (how busy), Saturation (how much work is queued) and Errors. It answers 'which resource is the bottleneck?'.

    In a microservice system you apply RED to every service and to its outbound dependencies, which lets you follow a problem downstream, then USE on the resources of the service at fault. In .NET, RED comes almost entirely from the built-in http.server.request.duration histogram; USE comes from System.Runtime (thread pool queue, GC), the container or node, and the database. The trade-off: RED is simple and user-centred but says nothing about cause, so you need USE underneath it to diagnose.

  3. When: Candidate says SLOs should be set on p95 or p99. Why: Checks they can connect metrics to reliability targets.
    How to answer

    An SLI is a measurement of user experience expressed as a ratio of good events to valid events, for example requests to /api/orders answered in under 300 ms with a non-5xx status รท all requests. An SLO is the internal target for that SLI over a rolling window, such as 99% over 28 days. An SLA is the external contract with financial penalties, deliberately looser than the SLO (say 99.5% vs 99.9%) so you breach the SLO first.

    To turn a latency percentile into an SLO, rephrase it as a threshold ratio: "99% of requests complete in under 300 ms", computed from the ASP.NET Core http.server.request.duration histogram buckets, not by averaging p99s. The error budget is 1 โˆ’ SLO: at 99.9% over 30 days that is about 43 minutes or 0.1% of requests. When the budget is spent, risky releases pause and reliability work takes priority. The trade-off: each extra nine costs far more engineering and infrastructure.

๐Ÿ›  Real-world problems: how you handle them

Healthy average hid a 4-second checkout tail
Situation
A checkout API at [company] handling about [300] requests/s across [6] pods; the main dashboard showed average latency only. Customer complaints and cart abandonment were rising.
Signals
Average latency flat at ~120 ms; support tickets about 'spinning' checkout; abandonment up [x]% week on week; no alerts fired because the alert used the average.
Investigation
Ran KQL on `requests` with `percentile(duration, 99)` by `name` and found p99 of 4.1 s on `POST /checkout/pay`. Checked `dependencies` for the payment provider: p99 at 2 s, the retry policy's timeout. Confirmed in Grafana with `histogram_quantile(0.99, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket[5m])))`; per-pod p99 was even across pods, so not one sick instance.
Resolution
Immediately lowered the payment HTTP timeout from 2 s to 800 ms with one retry and a circuit breaker. Then added p50/p95/p99 tiles per route, replaced the average-based alert with a p95 SLO burn-rate alert, and asked the provider about their tail latency.
Prevention
Dashboard standard: no latency tile without p50/p95/p99 and request count; SLO defined on p95 of successful requests; k6 load test in the pipeline reports p95/p99 and fails above the budget.

How to tell it (STAR)

**S:** Our checkout dashboard at [company] showed a steady 120 ms average, but support was getting complaints about slow payments and abandonment was up [x]%. **T:** I was asked to find out why the numbers and the customers disagreed. **A:** I queried the raw requests in Application Insights for percentiles by route and found p99 on the pay endpoint was 4.1 seconds. The dependency data showed the payment call hitting our 2-second timeout and retrying. I cut the timeout to 800 ms with a single retry and a circuit breaker, then rebuilt the dashboard around p50, p95 and p99 with request counts and moved our alert to a p95 SLO. **R:** p99 dropped from 4.1 s to 650 ms within a day and abandonment returned to [baseline]; the team stopped using averages for latency.

โ†ฉ Usually asked after

More in Metrics

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me