Quick revision
The short answer
Keeping every sample and sorting each window is O(n log n) per update and stores every sample, which does not scale to 50,000 series. Instead, each series keeps a ring buffer of small mergeable sketches, such as HdrHistogram, DDSketch or t-digest, one per 10 second bucket. The 5-minute p99 comes from merging the 30 buckets in the window, and sliding forward simply drops the oldest bucket. Because percentiles cannot be averaged, instances send these mergeable sketches rather than their own p99, and in practice Micrometer and Prometheus histograms already implement this idea.
What to remember
In this answer, we saw that keeping every sample and sorting each window costs O(n log n) per update and over a hundred gigabytes for 50,000 series. We replaced it with mergeable histogram sketches such as HdrHistogram, DDSketch or t-digest, kept in a ring buffer of 10 second buckets per series, so the 5-minute p99 is a merge of 30 sketches and sliding drops the oldest bucket. We saw why percentiles must never be averaged and why sketches are merged before reading the percentile, and that Micrometer and Prometheus histograms already implement this approach.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Keeping every sample and sorting each window is O(n log n) per update and stores every sample, which does not scale to 50,000 series. Instead, each series keeps a ring buffer of small mergeable sketches, such as HdrHistogram, DDSketch or t-digest, one per 10 second bucket. The 5-minute p99 comes from merging the 30 buckets in the window, and sliding forward simply drops the oldest bucket. Because percentiles cannot be averaged, instances send these mergeable sketches rather than their own p99, and in practice Micrometer and Prometheus histograms already implement this idea.
Why this question is asked
Latency percentiles are the numbers on every service dashboard and in most SLOs, and p99 matters because averages hide the slow requests customers actually feel. A platform that computes them for tens of thousands of series must do it with bounded memory and CPU, and must get the maths right when combining data from many instances. Interviewers ask this design question to see whether we know the data structures built for this problem and the classic mistake of averaging percentiles. In this answer, we will size the naive approach, introduce histogram sketches, build the sliding window from a ring of buckets, explain why percentiles cannot be averaged, and end with the existing tools.
1Why Sorting Every Window Does Not Scale
A percentile is the value below which a given fraction of samples fall; p99 is the latency that 99 percent of requests beat. The exact way to compute it is to sort all samples in the window and pick the element at position 0.99 x n. Suppose each series receives 1,000 samples per second. A 5-minute window then holds 300,000 samples, 2.4 MB as doubles, and across 50,000 series that is 120 GB of raw samples. Sorting 300,000 values costs about 300,000 x 18 comparisons, around 5 million operations, and doing that for every series on every refresh, say every 10 seconds, is roughly 25 billion operations per refresh. Both memory and CPU are out of reach, and we have not even replicated anything yet.
Notice that we do not actually need every sample. A p99 latency of 412.7 ms versus 413.1 ms makes no operational difference; an answer within about 1 percent relative error is what dashboards and alerts need. That opens the door to sketches.
2Histogram Sketches: Small, Accurate, Mergeable
A sketch is a compact summary of a distribution that answers quantile queries approximately. The most practical ones are histograms with cleverly chosen buckets. HdrHistogram uses buckets that grow exponentially with a fixed number of significant digits, so a range from 1 microsecond to an hour fits in tens of kilobytes with about 0.1 to 1 percent relative error. DDSketch uses logarithmic buckets with a guaranteed relative error, for example 1 percent, and only stores non-empty buckets, so a typical latency distribution needs a few hundred counters. t-digest keeps clusters of points sized so that the tails are very accurate.
The crucial property for us is mergeability: two sketches built from separate data can be combined into one sketch that is as accurate as if it had been built from all the data. For bucket-based histograms, merging means adding the counts bucket by bucket. Recording a sample is O(1), a bucket index computed from the value and an increment.
3A Ring Buffer of Buckets for the Sliding Window
A single sketch only grows; it cannot forget old samples. So for each series we divide time into short buckets, for example 10 seconds, and keep one sketch per bucket in a ring buffer of 30 slots, which covers exactly 5 minutes. New samples go into the sketch for the current bucket. Every 10 seconds the ring advances: the oldest slot, now 5 minutes old, is cleared and reused for the new bucket. To answer a p99 query, we merge the 30 sketches and read the percentile from the merged result.
Memory per series is 30 sketches. With DDSketch at about 2 KB each, that is around 60 KB per series and 3 GB for 50,000 series, spread across a cluster. The window slides with a resolution of one bucket, 10 seconds, which is fine for monitoring. Merging 30 sketches costs 30 times the number of buckets, a few thousand additions, instead of sorting 300,000 samples.
- Sample arrivesrecord into the current bucket's sketch, O(1)
- Has 10 s passed since the bucket started?YesAdvance the ring: clear the oldest slotNoKeep recording
- Query p99 for the windowmerge the 30 sketches
- Read the 99th percentileabout 1 percent relative error
4 steps in order. Play them, or step through them one at a time.
4Why Percentiles Cannot Be Averaged
A very common mistake is to have each instance compute its own p99 and then average them, or to average the p99 of each 10 second bucket to get a 5-minute p99. That number has no meaning. Consider two instances: instance A handled 9,900 requests with p99 of 50 ms, instance B handled 100 requests with p99 of 2,000 ms because it was overloaded. The average of the two p99 values is 1,025 ms, but the true combined p99 is close to A's tail, because B holds only 1 percent of the traffic. Weighting by request count does not fix it either, because a percentile depends on the whole shape of the distribution, not on a summary number.
The correct method is to combine distributions, not statistics. Each instance sends its per-bucket sketch, the aggregator merges the sketches, and only then do we read the percentile. That is why mergeability is the property that matters most.
| Method | Result | Correct? |
|---|---|---|
| Average of per-instance p99 | (50 + 2000) / 2 = 1025 ms | no: ignores traffic and shape |
| Request-weighted average of p99 | about 69.5 ms | no: still not a percentile |
| Merge sketches, then read p99 | true p99 of all 10,000 requests | yes |
5Reusing Micrometer and Prometheus
Most of this already exists. Micrometer, the metrics library in Spring Boot, can record timers as histograms; with publishPercentileHistogram enabled it publishes fixed histogram buckets that the monitoring back end can merge across instances, and its client-side percentiles, computed per instance, are explicitly not aggregatable. Prometheus histograms expose cumulative bucket counters, and histogram_quantile(0.99, sum by (le) (rate(http_server_requests_seconds_bucket[5m]))) computes a 5-minute p99 across instances by summing buckets first, exactly the merge-then-read approach. Newer Prometheus native histograms use exponential buckets similar to DDSketch; check your version for their status. Datadog uses DDSketch for its distributions.
So my recommendation would be to standardise on these mergeable histogram formats, size the buckets for our latency range, and only build custom sketch storage if the volume or retention needs exceed what the existing back end can handle.
6Follow-up questions
Why not use a fixed-size random sample instead of a sketch?
Reservoir sampling keeps a uniform sample, but the tail is exactly where samples are rare: with 1,000 samples out of 300,000, the p99 estimate rests on about 10 values and is noisy. Sketches keep accurate counts in every range, including the tail, with a guaranteed error.
How do you choose the bucket length?
It trades window resolution against memory. Ten second buckets in a 5-minute window give 30 sketches per series and a window that moves every 10 seconds. One minute buckets would use 5 sketches but make the window jump in large steps, which can delay alerts by up to a minute.
Which sketch would you pick?
DDSketch or HdrHistogram when we want a guaranteed relative error and simple, exact merges; t-digest when we care about extreme tails like p99.9 and accept that merges are approximate. In a Prometheus based stack, the native histogram format is usually the simplest choice.
7Conclusion
In this answer, we saw that keeping every sample and sorting each window costs O(n log n) per update and over a hundred gigabytes for 50,000 series. We replaced it with mergeable histogram sketches such as HdrHistogram, DDSketch or t-digest, kept in a ring buffer of 10 second buckets per series, so the 5-minute p99 is a merge of 30 sketches and sliding drops the oldest bucket. We saw why percentiles must never be averaged and why sketches are merged before reading the percentile, and that Micrometer and Prometheus histograms already implement this approach.
Open with
The naive design keeps every sample and sorts the window, which is O(n log n) per update and, at a thousand samples a second, about 300,000 samples per series per window, so over a hundred gigabytes across 50,000 series.
Then, if they want more
Monitoring does not need exact values, about one percent relative error is fine, so I would use histogram sketches like HdrHistogram, DDSketch or t-digest. Recording a sample is O(1), a sketch takes a few kilobytes, and crucially they are mergeable: adding two sketches gives the sketch of the combined data.
For the sliding window, each series keeps a ring buffer of thirty sketches, one per ten second bucket. Samples go into the current bucket, every ten seconds the oldest bucket is cleared and reused, and a p99 query merges the thirty sketches and reads the percentile. That is a few thousand additions instead of sorting 300,000 values.
The same property solves aggregation across instances. Percentiles cannot be averaged, because a percentile depends on the whole distribution, so the average of per-instance p99 values is meaningless. Instead, instances ship their sketches and the aggregator merges them before reading p99.
In practice I would not build this myself: Micrometer's percentile histograms and Prometheus histograms with histogram_quantile over summed buckets implement exactly this, and Prometheus native histograms use exponential buckets like DDSketch.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A monitoring platform computes p99 latency over sliding 5-minute windows for 50,000 time...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/bd40414c6f/