Ch.46: Metrics Monitoring System Design: The p99 Trap
Outline
- 0:00 Two percentiles, one false answer
- 0:37 Follow the measurement to the screen
- 1:06 Ask for the answer before choosing storage
- 1:51 The workload buys constraints
- 2:41 Equal traffic still breaks the average
- 3:26 Keep counts across delay ranges
- 4:18 A stream needs an identity and a clock
- 5:13 Labels spend memory before any query
- 6:03 Checkout wins when telemetry falls behind
- 6:49 Define what accepted means
- 7:45 Explain what the time-series database does
- 8:37 Walk one dashboard query
- 9:40 Old percentiles cannot become new answers
- 10:29 Freshness can hide missing evidence
- 11:15 Bound the question as well as the writes
- 12:11 Test the failure at the right boundary
- 13:02 Return to the complete architecture
- 13:38 Ask what the dashboard can actually know
Transcript
0:00 Your metrics monitoring dashboard says checkout is healthy, but its percentile is wrong. One worker reports a p99 of 20 milliseconds. Another reports 800. You average them: 410. Below our 500-millisecond limit. But p99 means the delay by which 99% of observed requests finish. Averaging two delays doesn't tell us that fraction across checkout. Exactly. We'll design the collection and query path so the dashboard preserves the evidence behind its answer. A faster database cannot recover the requests we already summarized away.
0:32 Then where do we preserve those requests without slowing checkout itself? Here's that worker's path through our complete architecture: a bounded application buffer, checked ingestion and routing into replicated recent storage. Older blocks supply history. The query service reads both workers' distributions, selects the time range and returns freshness and coverage with the answer. That's what reaches the dashboard. Keep that map in view. Storage can't rescue information discarded earlier. We'll return to the arrows after choosing our caller's question.
1:02 So let's define the checkout answer before choosing those stores. First, our functional requirements: record request latencies, counters and gauges. A counter accumulates events within a process run, like completed checkouts. A gauge measures a current value, like queue depth. Query by service, environment, region and time window. For example, show checkout's last 5 minutes, then inspect one worker whose detail we retained. And tell me when that drilldown isn't available. An empty chart could mean missing data.
1:31 Yes. Recent data keeps that detail; older history may be coarser. Either way, stale, incomplete and unsupported must look different. Then a number alone isn't our API result. The caller needs to know what population and period it actually represents. Now put a workload behind those questions. How much data must those answers handle? Now the non-functional requirements: telemetry must not stall checkout. Bound application memory, distinct streams and query work. Authenticated tenants must never read each other's metrics.
2:00 For our exercise, suppose 2000 producers each export 50 streams every 15 seconds. That's 100,000 streams, roughly 6,700 metric points a second. That's points, not bytes. A histogram carries many counts, so changing its resolution changes the storage cost. We have to measure that encoding before buying capacity; export count alone doesn't size the machines. Right. Aim for 20-second dashboard freshness and 2-second selected queries under normal conditions. Keep detailed data 1 day, service-level history 30 days.
2:34 Those are design targets to test, not guarantees. Could traffic-weighting the two local percentiles rescue that original answer? Let's test that weighting with equal traffic. Imagine two workers with equal 100-request populations: the first takes 20 milliseconds, the second 800. Their local p99 values match those delays. Hold on. Half finish quickly; the other half need 800 milliseconds. Our required fraction takes that longer delay. Our original average is still wrong. I wanted traffic weighting to save that chart, but equal counts leave nowhere to hide.
3:06 Prometheus's histogram guidance explains the deeper problem: precomputed quantiles don't combine into a service quantile. Links are in the description. Ah, the chart didn't find a healthier service. It averaged two thresholds. We need a representation that retains how the requests are distributed. What should each worker export so we can combine that evidence? With a histogram, preserve the distribution as counts in delay ranges, called buckets. With compatible boundaries, combine corresponding counts across workers before finding the percentile.
3:36 We merge the evidence, then calculate the answer. Use our toy population. At the boundary of 500 milliseconds, 100 observations finished at or below it, out of 200. Only half met the objective. The green chart was wrong. Oh, that's a much worse service than that green chart suggested. The fraction is exact for the observed requests at that boundary. A percentile falling inside a wider bucket is only an estimate. More resolution costs more space and processing. Yes. Choose supported bucket resolution around the decision we care about.
4:09 Don't promise an exact p99 from data that only locates its range. That helps. Which identity keeps two producers from looking like one stream? Now give each stored stream a metric name, type, unit and labels, plus its producer and process run. Add the timestamp. Labels identify what we measured, like checkout latency in one region. Let me use our first worker. Its cumulative request count was 900 before the window and 1,000 afterward. That's 100 additional requests. Its start epoch identifies the process run those totals belong to. Exactly. A restart makes a new run; 40 after restarting isn't negative 960.
4:47 For cumulative histogram buckets, do that before-and-after subtraction within each writer's run, then combine workers. Never subtract across a restart. Right, those requests didn't run backward. A queue-depth gauge measures the queue now; it doesn't accumulate completed checkouts. OpenTelemetry's metric model distinguishes these meanings. One generic averaging job cannot decide what every metric represents. Writer identity protects subtraction; label policy must protect application memory. Now the application chooses its labels too.
5:16 I think one extra label should be harmless. A customer ID would help us find slow customers, wouldn't it? It would, at a cost. Each new customer's ID creates another distinct stream inside checkout. Our supposedly small annotation buys a customer-sized memory bill before ingestion can reject anything. Oh, our health check just became a little customer directory. OpenTelemetry's SDK describes overflow aggregation when a limit is reached, but that coarser total loses the original label distinction.
5:45 That's why the producer filters labels and bounds combinations before collecting. An overflow bucket can't tell us which customer was slow. Use separately controlled logs or traces for individual investigations. That bounds the local memory cost. How does export behave when the receiver stops answering? With label policy bounding local aggregation, we can export safely. Export cumulative snapshots through a finite queue, separate from request completion. Suppose the queue holds four exports. With our 15-second cadence and no receiver progress, four arrivals occupy it.
6:18 The next export cannot fit. Then keep checkout running and record that telemetry was dropped. A later cumulative snapshot may include the observations from missed exports, until that process restarts. A crash can erase observations never exported. We cannot claim zero loss while also refusing to block application requests. Keep that boundary separate from durable ingestion. Right. We can protect accepted snapshots in storage. We can't recover measurements that died inside the application. The missing interval needs to remain visible.
6:48 Now take a snapshot from our fast worker at the window's end. Ingestion authenticates its tenant and validates the schema. Route by tenant plus full stream identity; routing only by metric name would overload one group. Send this snapshot to three machines. As soon as two recovery logs durably contain it, acknowledge it. One failed disk then leaves a durable copy of the accepted snapshot. A reviewer could ask, "Why require two? Accept on one and keep writes available." That sounds attractive during an outage.
7:19 Until that sole copy's disk is lost. We'd lose data we'd already accepted. Two durable copies are our chosen boundary; fewer than two means no acknowledgement. The application's buffer policy handles that outage. Retry that very snapshot with its original sample identity. Matching contents don't add another sample; conflicting contents are rejected. We've kept the measurement. Now how do I find its 5-minute slice without reading everything? Now store those accepted snapshots beyond their recovery logs.
7:48 Keep recent samples in ordered chunks per stream, then compact them into immutable time blocks. Prometheus documents that storage shape; replication is our separate choice. Walk me through how that index finds both checkout workers without scanning every point. Think of a library index. The checkout entry lists stream IDs, called a posting list. Intersect it with the region list to select our workers. Then the chunks' time bounds let us skip pages outside the 5-minute window. I love that distinction. The index finds the books; time bounds choose the pages.
8:22 And if compaction is still writing a block, can a query see it yet? Only after it's durably written. Publishing a half-written block would send readers to incomplete evidence. With that index and catalog in place, let's trace the query itself. Now follow checkout's 5-minute query. The index selects the two producers. Read their window samples and a snapshot just before it: cumulative totals need a starting value for subtraction. And that snapshot could appear in recent chunks, a historical block and replicas.
8:52 Those are several places holding the same measurement. Ah, copying it doesn't create extra traffic. During compaction, we rewrite smaller chunks into a block and replace the catalog's earlier reference. Does a query already reading the previous block switch halfway through? No. It finishes against the version it started with. New readers use the replacement. Keep the earlier block until its readers finish, and deduplicate sample identities before calculating contributions. Then subtract 900 from 1,000 for the first writer: 100 additional checkouts.
9:24 Our second contributes another 100. We merge their bucket counts, not the local percentile values. That recovers 200 original requests. And a compressed historical summary can't join them as extra traffic either. What representation survives when detailed chunks get too expensive? For that retention boundary, historical queries need a cheaper representation. We choose minute rollups: one histogram per minute, service and region. Derive each writer's interval contribution first, then combine the counts.
9:52 Our two workers still contribute their request populations, even after individual identities disappear. Why not just keep each minute's p99? It's smaller. Because an hour's p99 isn't the average of 60 minute percentiles either. Retain the mergeable counts. And don't combine fine data and a rollup for the same interval twice. Ah, 60 useful minute percentiles still can't answer the whole hour. And dropping worker labels from old history removes the worker drilldown entirely. The system should say unsupported; a fast guess would still be a guess.
10:25 And could a current result still omit part of the service? Now consider a dashboard losing one serving partition while the others answer. The latest returned timestamp could be current, yet a whole part of checkout is absent. Wait, our slow worker could be there. The deployment registry lists both workers expected during this window. The routing catalog tells us their groups. If only the fast one answers, coverage says one of two. And the missing traffic could contain our slowest requests. A missing group never becomes zero contribution that silently improves p99.
10:58 A strict caller gets an unavailable answer instead of invented health. Even an expired heartbeat doesn't erase that worker from the earlier expected set. Return the latest fully covered time and bucket resolution. That inventory still can't prove every user request was instrumented. Now ask what a cache can honestly claim. Suppose it holds yesterday's green checkout answer. A current page load mustn't make that old measurement current. An on-call engineer might prefer yesterday's chart to a blank screen.
11:29 Could we serve it during an outage, as long as the old time remains visible? Yes, as historical context, if the caller accepts it. Serve only this tenant's matching question, with the stored version, measurement time and coverage intact. Don't relabel an old result as fresh and complete. Right. Useful yesterday isn't healthy today. And now replace our selected checkout query with all 100,000 streams in every region. That contacts many storage groups: query fanout. When it exceeds our work budget, return "query too broad" so smaller requests can still run.
12:03 And bound tenant concurrency so one tenant can't occupy every query slot. How would you test these promises under failure? Let's test this design. Restart a producer: its new run mustn't be subtracted from its old total. Retry a snapshot: its contribution mustn't double. Disconnect a serving group: coverage must change. Then cross our retention boundary. The service percentile should use retained distributions, but an expired worker-level question should become unsupported. Different queries lose different capabilities.
12:32 Finally fill the export queue and crash the process. The lost telemetry cannot masquerade as a perfectly complete healthy interval. Check whether ingestion accepts new exports independently, using a few fixed-label health metrics. My first thought here was to draw the storage boxes. That would have hidden the four-slot queue where evidence can vanish before storage ever sees it. Okay, put our original two workers back on that complete map. What if storage returns two copies of each snapshot? Now those snapshot copies are one observation each on our complete map.
13:07 The fast worker still contributed 100 requests, the slow one another 100. Storage replication cannot turn that into 400 requests. And if the slow worker's group stops answering, we haven't made checkout faster. We lost evidence. Selection, deduplication and interval merging must carry that missing coverage all the way to the dashboard. Exactly. The map now explains three different limits: buckets limit precision, missing sources limit completeness, and rollups limit old drilldowns. The caller's question decides which loss is acceptable.
13:38 So the initial pair of worker thresholds never justified that healthy p99. In our fictional population, the bucket counts show half the requests missing the chosen delay limit. Yes. And when a source is missing or old detail has expired, the answer changes from a reassuring number to a qualified or unsupported result. Design the monitoring system to preserve the evidence its callers need. Thanks for listening to Learning Podcasts.