Design a metrics system
Read first: Time-series data, Observability
A metrics system stores counters, gauges, and histograms for dashboards and alerts, and it must be able to drop samples without stalling the product. Cap the number of series, keep raw data briefly, and make queries read rollups. A label per user id is the outage.
The data you are storing is a time series: append-mostly samples, compressed, downsampled, and deleted when retention says so. Tags are the indexed dimensions. A raw event per request is a different, more expensive product. The design constraint that decides the rest of the diagram is blunt. Checkout has to keep working when the graphs go dark.
Requirements
The user is an on-call engineer, plus the alert rules that read the same store. A process emits counters, gauges, and histograms. The engineer asks for a rate, an error ratio, or a latency percentile over a window, sliced by a few labels such as service, endpoint, and status.
Observability splits the toolbox into metrics, logs, and traces. This page is metrics. RED (rate, errors, duration) is the set of series a service owes you. USE (utilization, saturation, errors) is the set a machine owes you. You can mention both in the interview and then design for RED, because that is what the user of your product feels.
Functional requirements:
- Accept samples from many processes.
- Identify a series by metric name plus its label set.
- Answer range queries for dashboards and for alerts.
- Keep recent samples at the scrape resolution, keep older samples as rollups, and drop what has aged out.
Non-goals, said out loud so the interviewer does not widen the problem:
- Traces. A trace is a tree of spans for one request. You propagate a trace context on the request. You do not store those trees in this database.
- Logs. A line per request will dwarf the counters.
- Per-user product analytics and funnels. That belongs in a warehouse. It is also the cardinality trap below, so declining it is a design choice, not a lack of ambition.
- The policy around an SLO. You store the series an SLI is computed from. You do not need a multi-window burn-rate implementation in the first diagram. An alert that pages on one bad scrape is a trap you should name.
Estimation
Say the assumptions, then multiply. These are interview assumptions, not a vendor’s footprint.
- 1,000 hosts.
- 500 series on each host. That is RED for a few dozen handlers, plus a handful of runtime gauges. It is a planned budget, not an invitation to add a label per customer.
- A sample every 10 seconds.
- Once a series has an id, a stored sample is 16 bytes: 8 for the timestamp and 8 for the value.
- While the series is live, the index keeps about 1 KB for it: label strings and a pointer at the head chunk. That 1 KB is an assumption about resident memory, so you can see the cardinality math. Measure it on the store you actually run.
- In the arithmetic below, a GB is 10^9 bytes, so you can check the powers of ten.
series 1,000 * 500 = 500,000
samples / series 86,400 / 10 = 8,640 per day
samples / day 500,000 * 8,640 = 4,320,000,000
4,320,000,000 / 86,400 = 50,000 samples/s
shortcut, day ≈ 100,000 s: 4.32e9 / 1e5 = 43,200 samples/s
values / day 4.32e9 * 16 B = 6.912e10 B ≈ 69 GB
index, planned 500,000 * 1 KB = 500 MB
A day is 86,400 seconds. The 100,000-second shortcut lands about 15 percent low here (43,200 versus 50,000) because 86,400 / 100,000 = 0.864. Show both. Interviewers want to see that you know the shortcut is a shortcut.
Peak of 3× is a further assumption: 150,000 samples/s. At an assumed 120 bytes on the wire while labels are still repeated, that is 150,000 × 120 = 18 MB/s. The network is bored. Memory for series heads is the resource that breaks.
Retention, also assumptions: 7 days of raw 10-second samples, 30 days of 1-minute rollups, 365 days of 1-hour rollups. Three copies, because a metrics region should survive a lost disk.
raw 7 * 69 GB = 483 GB
1-minute 60/10 = 6× fewer points
30 * 69 / 6 = 345 GB
1-hour 3,600/10 = 360× fewer points
365 * 69 / 360 ≈ 70 GB
one copy 483 + 345 + 70 = 898 GB
three copies 898 * 3 ≈ 2.7 TB
That is the whole fleet’s values under the label budget. It is a modest store. The design does not get to spend it on user_id.
High-level design
Each process keeps counters in its own memory and exposes them to a local agent. The agent scrapes on the interval, or a short-lived job pushes once when it exits. Agents send to an ingest tier. Ingest resolves the label set to a series id, appends the sample to the current chunk for that series, and updates the index.
A rollup job reads closed chunks and writes coarser series. A query service picks the resolution that matches the graph. Alert rules read the same query path on a schedule. Nothing in that pipeline is on the path of a user request.
flowchart LR
app[App process]
buffer[Local sample buffer]
agent[Scrape agent]
ingest[Ingest tier]
index[Series index]
raw[Raw chunks]
roll[Rollup job]
query[Query service]
app --> buffer
buffer --> agent
agent --> ingest
ingest --> index
ingest --> raw
raw --> roll
query --> raw
query --> roll
Partition ingest by metric name plus a shard of the series id, so one metric has a home and a single hot metric can be split. Partitioning by hash spreads the planned 500,000 series. It does not forgive a label that creates hundreds of millions of new ones. The cap below is what does that.
The app buffer is the isolation boundary. If the agent or the ingest tier is down, the buffer fills and then drops. Dropped samples are a gap in a graph. They are not a failed checkout.
Deep dive
The write path has to be lossy
A handler that remote-writes a sample has attached product latency and product availability to the metrics store. You will not do that. The handler increments a counter in process memory. That increment is a few instructions, on the order of a memory reference, not a network round trip.
The agent pulls those counters every 10 seconds. Pull means the process does not know where the database is, and a stuck scraper cannot push back into the handler. The cost of pull is discovery: the agent has to learn which processes exist. A job that runs for two seconds and exits will be gone before the next scrape, so that job pushes a final sample to the same ingest tier.
Push is where teams recreate the outage. Give the push a short timeout, a bounded buffer, and a drop policy. Retries on that path need backoff and jitter and a hard stop. Load shedding here is literal: when the buffer is full, discard. Per host, 500 series every 10 seconds is 50 samples/s. A buffer of 10,000 samples (assumption) holds 10,000 / 50 = 200 seconds. Past that you have a gap in the graphs and a healthy product. A team that blocks the handler instead has chosen the opposite failure.
OpenTelemetry is a reasonable way to name the instrumentation: one set of counters in the process, exported to whatever backend you run. Do not spend the interview on exporter configuration. Spend it on the drop policy.
Cardinality is a memory budget
A series exists for each distinct set of label values. Labels multiply. service, endpoint, and status are healthy because you can name the set in advance. user_id is not, because the set is the user population, and it churns.
Assumption for the trap: one HTTP counter grows an 8 million distinct user_id values in a day, and someone also keeps 20 endpoints and 4 status codes on the same series.
planned index 500 MB
user_id alone 8e6 * 1 KB = 8 GB
crossed with endpoint
and status 8e6 * 20 * 4 = 640e6 series
640e6 * 1 KB = 640 GB
Eight gigabytes for one label already dwarfs the 500 MB index you sized. The cross product is how a “small extra tag” becomes hundreds of gigabytes of series heads, most of them holding a single sample from a single request. High cardinality blows up memory. The disk of old samples is not the first thing that dies. The process that has to track every live series does.
The symptom is dull until it is sudden. Ingest memory climbs. Scrapes start timing out. The rule evaluator gets slow, then restarts. The deploy that added the label is invisible on the dashboard you needed in order to see the deploy. The product kept returning 200s the whole time, which is why this outage feels confusing.
The control is a budget, enforced at ingest:
- A cap on active series per metric, and a tighter cap per tenant if you are multi-tenant.
- New series past the cap are rejected and counted on a single meta-series (
series_dropped, low cardinality). You do not silently accept them. - A standard label allowlist for the shared platform metrics. Extra labels are a conscious request, not a free string on the client.
- Histograms use fixed buckets, on the order of a dozen counters you chose up front. A label whose value is the raw latency in milliseconds is the same trap with a numeric costume.
Pre-aggregate in the process when you can. The alert wanted error rate by service and status. It did not want a series per customer. Drop the high-cardinality label at the source and the cap never has to fire.
Rollups are what queries actually read
Raw 10-second samples are for the last few hours of an incident. A 30-day graph does not want them. One series over 30 days at 10 seconds is 30 × 8,640 = 259,200 points. A dashboard of 24 series is 24 × 259,200 = 6,220,800 points, read while someone drags a time picker. The 1-hour rollup of the same window is 30 × 24 = 720 points per series, and 17,280 points for the board.
The query service picks the rollup from the window and the step. A 15-minute incident view at 10-second steps reads raw: 15 × 60 / 10 = 90 points per series. A quarter view reads the hour rollup. If the caller asks for 10-second steps over 30 days, rewrite the query onto the hour rollup and return the step you actually used. Raw data older than 7 days is gone on purpose. A query that scans what you deleted, then draws a hole and looks like an outage, is a second incident.
Rollups are another small pipeline, a stream processing job in shape even if it is a cron at first: read closed chunks, write the coarser points, advance a watermark of “rolled up through T”. Re-running an hour is fine if the rollup write is idempotent per (series, bucket start). Compaction and downsampling are the storage story. Retention is how you stop 69 GB/day from becoming infinite. Cost here is copies times days, which is the 2.7 TB above, not a price quote.
A counter resets when a process restarts. The rate is a difference between samples, and a reset looks like a huge negative delta. Treat a large drop as a reset and start the rate from the new value. If you do not, every deploy draws a spike downward and an alert fires on a restart.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Pull from a local agent | The product has no network call to the metrics store | Short-lived jobs disappear between scrapes, so they must push once |
| Push with a bounded buffer | Batch jobs and serverless tasks get a sample in | A client that blocks or retries forever moves the outage into the product |
| Reject series past a cap | One bad label cannot exhaust ingest memory | A team that needed a new label must ask, and you will drop their new series |
| Roll up and delete raw data | Queries stay small and disks stay finite | You cannot answer a 10-second question about a day last quarter |
| Pre-aggregate in process | The series set is the one you designed | You lose the ability to regroup by a label you threw away |
| Alert on a rollup window | One missed scrape does not page anyone | A very short incident can end before the window notices |
Failure modes
Dependency down. Ingest or the query tier is unreachable. Agents fill a 200-second buffer and then drop. Dashboards gap. Alerts that already evaluated go stale, which should itself be an alert on “no samples for this service”, fed by a cheap heartbeat, not by the absence of a page. The product path never called this tier, so it stays up. That is the success case. If you cannot describe it, the design is wrong.
Retry storm. Push clients treat a slow ingest as a reason to retry without jitter, on every host, at the same moment. Ingest gets slower. Cap attempts, jitter the backoff, and drop. A scraper fleet that shortens its interval because the last scrape was slow is the same storm from the pull side. Hold the interval.
Hot partition. One metric’s series all hash to one ingest shard, or one tenant’s label explosion lands in one partition. The shard’s memory climbs and every other metric that shares the process slows down. The cap has to be per metric, enforced before the append, so a hot key made of a million series is rejected at the door. Adding partitions does not shrink user_id. Each user is already a different key. The sum of the keys is the problem.
Consistency and durability. This store is allowed to lose samples. Say that in the interview. Do not promise that a counter increment survives a process crash: the in-memory counter dies with the process, and the next scrape starts from zero, which is the reset case above. Do not promise exactly-once delivery of a pushed sample. A retry can double-count a delta. Send absolute counter values and let the query take a difference, or send a sample id and dedupe inside the ingest window. Gauges and absolute counters survive a duplicate. Deltas do not.
A query that mixes a raw chunk on one replica with an hour rollup that has not caught up can draw a seam at the boundary. Serve a resolution from one retention tier for a given range, and lag the “now” of a rollup by a bucket so you do not graph a partial hour as if it were done.
In the interview
Spend the first five minutes on the user (on-call), the non-goals (not traces, not per-user funnels), and one number: 50,000 samples/s average under the assumptions above, network trivial, memory not trivial. Name the bottleneck as series cardinality. Name the tradeoff as “we drop samples and we refuse new series, and that is how checkout stays up.”
Draw the buffer, the ingest append, the rollup, and the query picking a resolution. Then stop drawing. Skip compression codecs, the query language, and any vendor’s architecture. If you have not been asked about histograms, one sentence is enough: fixed buckets, computed in process, so you do not ship every latency.
The question that usually follows is “what if a label is a user id?” Walk the 8 GB versus 500 MB comparison and the cap. The question after that is “the metrics store is down during a sale.” The answer is the buffer and the drop, not a failover novel.
Check yourself
Using 1,000 hosts, 500 series each, and a 10-second interval, what is the average ingest rate, and what shortcut did you compare it with?
86,400 / 10 = 8,640 samples per series per day. Times 500,000 series is 4.32 billion samples a day. Divided by 86,400 that is 50,000 samples/s. The 100,000-second shortcut gives 43,200, which is the same count divided by a rounder day. The shortcut is fine for a first pass and a bit low when you need the real day.
A teammate writes each sample to the metrics store inside the checkout handler. What breaks, and what do you do instead?
Checkout latency and availability now include the metrics store. A slow ingest becomes a slow payment. Increment a counter in process memory and let an agent scrape it. If the agent is down, a bounded buffer drops samples after a couple of minutes of slack. The graph gaps. The checkout does not.
Why does a pull scraper miss a batch job that runs for two seconds, and what do you change?
The scraper wakes every 10 seconds and the job has already exited, so there is no endpoint left to read. That job pushes one final sample, with a short timeout and a drop if ingest is down. You do not hold the job open until a scraper happens to notice it.
A 30-day board graphs 24 series. Why is reading raw 10-second samples the wrong plan?
One series holds 30 × 8,640 = 259,200 raw points in that window, and 24 series hold about 6.2 million points. The hour rollup holds 720 points per series and about 17,000 for the board. The query should read the rollup and report the step it used. Raw samples older than the raw retention are not there to scan.
You cap active series per metric and start rejecting. What did you protect, and what still works?
You protected ingest memory and the neighbors that share that process. Existing series keep accepting samples. New combinations past the cap are dropped and counted on one low-cardinality meta-series so the reject is visible. The product path was never waiting on this decision.
Based on: Google SRE book and SRE workbook; Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes.