"Design a metrics monitoring system" asks you to build the tool everyone else uses to see their systems: collect numbers from thousands of machines, store them cheaply, draw graphs and wake someone up when something breaks.
Two existing lessons cover what you would do with such a system. Monitoring and alerting is about what to measure and when to page, and observability explains metrics, logs and traces and why cardinality is the cost driver. This page is the other side: the infrastructure itself.
Interviewers use it because the numbers force real decisions. A million samples a second is a write-heavy, append-only, time-ordered workload, and generic databases handle it badly. The questions that matter are how you store a sample in a byte or two, how you answer a query over a year of data in a second, how you keep a runaway label from taking the system down, and how the system that watches everything avoids being the thing that fails silently.
Clarify the requirements
Functional requirements:
- Collect numeric samples (counters, gauges, histograms) with labels such as
service,regionandstatus. - Store them and answer queries: a series over a time range, aggregated by label ("p99 latency by region, last 6 hours").
- Render dashboards from those queries.
- Evaluate alert rules continuously and notify on-call when they fire.
- Keep recent data at full resolution and older data at lower resolution.
Out of scope, said aloud: logs and traces (a log aggregation system is a different design), anomaly detection with machine learning, the dashboard UI.
Non-functional requirements:
- High write throughput: about a million samples a second, with no tolerance for falling behind during an incident, which is when load peaks.
- Fast queries: dashboards in under a second for recent ranges, a few seconds for long ones.
- Highly available for alerting: this is the system that must work when everything else is broken.
- Cost-efficient storage: bytes per sample matter at tens of billions of samples a day.
- Protected from cardinality: one badly labeled metric must not take the whole system down.
Estimate the scale
Assume 100,000 hosts and containers, 10 million active time series in total, and one sample per series every 10 seconds.
Ingest rate: 10,000,000 ÷ 10 s = 1,000,000 samples per second.
Samples per day: 1M × 86,400 = 86.4 billion.
Raw size: a timestamp (8 B) plus a value (8 B) is 16 B per sample: 86.4B × 16 B ≈ 1.4 TB a day.
Compressed size: time-series compression (delta-of-delta timestamps, XOR-encoded values) reaches about 1.5 bytes per sample in practice, so 86.4B × 1.5 B ≈ 130 GB a day, a tenfold saving.
Retention: 15 days at full resolution is 15 × 130 GB ≈ 1.9 TB. For a year, roll up to 5-minute points: 105,120 points per series × 10M series × 16 B (min, max, sum, count) ≈ 17 TB.
Memory for the index: assume about 3 KB per active series for the in-memory index and recent data: 10M × 3 KB = 30 GB, around 1.5 GB on each of 20 storage nodes.
Write load per node: 1M samples per second ÷ 20 nodes = 50,000 per node, easy for an append-only engine.
Query load: 100,000 alert rules evaluated every 30 s is 3,300 queries per second, and 2,000 open dashboards with 10 panels refreshing every 30 s adds about 670 per second.
"The write rate is high but regular, and compression turns 1.4 TB a day into 130 GB, so storage is manageable. The real constraint is the number of series: 10 million series cost 30 GB of index memory, and a single label with a million values could multiply that by orders of magnitude. And most queries are not dashboards, they are the 3,300 alert evaluations per second that must keep running."
You can reproduce the sample rate in the capacity estimator: treat the system as one writer sending 86.4 billion samples a day, at 1.5 bytes each, retained for 15 days (0.0411 years).
API and data model
POST /v1/write batch of { series: {name, labels}, samples: [{ts, value}] }
GET /v1/query ?expr=rate(http_requests_total{service="api"}[5m])&start=...&end=...&step=60
PUT /v1/rules/{id} { expr, forSeconds, labels, annotations }series id = hash(metric name + sorted labels)
index label=value -> [series ids] (inverted index for filtering)
chunk series id -> [ (ts, value) ... ] compressed, ~2 hours per block
rollup series id, 5 min -> (min, max, sum, count)The inverted index is the quiet star. A query like {service="api", region="eu"} is answered by intersecting two lists of series ids, exactly as a search engine intersects posting lists (see search systems), and only then are the matching chunks read.
High-level design
The slice to simulate is the ingest pipeline: agents push samples through an ingest service into a stream, writers batch them into a write-optimized store.
- Agents on each host send batches of samples to a stateless ingest service.
- The ingest service appends them to a partitioned stream, which absorbs bursts.
- Writers drain the stream in batches into a write-optimized, replicated store.
Describe this diagram
Components
- agents (Client)
- ingest (Service)
- sample stream (Kafka)
- writers (Service)
- time-series store (Cassandra)
Connections
- agents sends to ingest
- ingest sends to sample stream
- sample stream sends to writers
- writers sends to time-series store
The simulator uses an LSM-style wide-column store to stand in for the time-series store, since both share an append-only, batched write path. Run it, then try raising the load or reducing the stream's partitions, and watch whether writers keep up.
The write path: an agent batches samples for a few seconds and sends them to the ingest service, which validates them, enforces per-tenant series limits and appends to a stream partitioned by series id. Writers read a partition, group samples by series, compress them into chunks and write them to the store with replication.
The read path: a query service parses the expression, uses the label index to find series ids, reads the chunks (from recent in-memory data or older blocks, choosing raw or rolled-up data by the time range), computes the aggregation and returns points. Results for common dashboard queries are cached for a few seconds.
The interesting problem: storing and querying time series
Approach A: a relational table
One row per sample: (series_id, ts, value) with an index.
Good: familiar, and fine for a few hundred series.
Bad: 86.4 billion rows a day at roughly 30 to 50 bytes with indexes is 3 to 4 TB a day. Maintaining a B-tree under a million inserts per second means random writes everywhere. Deleting old data is expensive row-by-row work, and range scans for one series over many hours touch pages shared with other series.
Approach B: a wide-column store keyed by series and time bucket
Use a store such as Cassandra: row key (series_id, day), one column per timestamp.
Good: writes are append-only and fast, a series' samples for a day sit together, and the store scales out and replicates. Expiring a day is a cheap whole-partition delete through TTLs.
Bad: it stores each sample as a general column, with per-cell overhead and no time-series-specific compression, so you pay many bytes per sample. Label queries need a separate index you must build and maintain.
Approach C: a purpose-built time-series database
Keep the newest data in memory (the "head"), write each sample to a write-ahead log for durability, and flush it periodically into immutable, compressed blocks. Timestamps are stored as delta-of-delta: regular intervals make the second difference zero, which costs about one bit. Values are stored as an XOR with the previous value, so unchanged or slowly changing values compress to almost nothing. A label inverted index maps label pairs to series ids.
Good: about 1.5 bytes per sample instead of 16, queries on recent data come from memory, old data is dropped by deleting whole blocks, and filtering by label is fast.
Bad: it is specialized, so you operate it (or buy it) separately, and the in-memory head and its index grow with the number of active series, which brings us to cardinality.
The recommended answer is C for storage, with a stream in front to decouple ingest from storage and absorb bursts. Say that B is a sound answer when you must reuse an existing wide-column platform, and name the compression and indexing you give up.
Diagram, as text
- Agent batches leads to Ingest service
- Ingest service leads to Partitioned stream
- Partitioned stream leads to Writer: group by series
- Writer: group by series leads to In-memory head + WAL
- In-memory head + WAL leads to Compressed immutable blocks
- Compressed immutable blocks leads to 5 minute rollups
The second decision: pull or push
Who sends the sample, the monitored host or the monitoring system?
- Pull (scrape): the monitoring system fetches a
/metricsendpoint from each target every 10 seconds, using service discovery to know the targets. It controls the rate, and a failed scrape is itself a signal: you know a host is down because it did not answer, without any rule on missing data. The downside is that the system must reach every target, which is hard across firewalls and for short-lived jobs. - Push: each host sends samples to an endpoint. It works behind NAT, from serverless functions and from batch jobs that finish in seconds, and it scales by adding ingest nodes. The downside is that a silent host looks identical to an idle one, so you need a heartbeat to know it is alive, and the senders can overload you.
A sound answer is a hybrid: pull for long-running services (cheap liveness, central control) and push, through a gateway, for short-lived jobs. In the design above, agents on each host push to the ingest tier, which is the common choice when you run an agent anyway, and the agent can also scrape local endpoints. Whichever you choose, add a per-tenant series limit at ingest.
Bottlenecks and failures
Cardinality explosion. One developer adds a user_id label with a million values to a metric that already has 200 label combinations: 200 million series, twenty times the whole system. The head and index run out of memory, and the monitoring system fails during the incident that needed it. Defend at ingest: a limit on active series per tenant and per metric, rejecting new series beyond it with a clear error, alerts on series growth and a documented rule that unbounded identifiers belong in logs and traces.
Ingest bursts. A deploy restarts thousands of containers at once, producing a wave of new series (churn) and a surge of writes. The stream absorbs the burst, and writers catch up. Alert on stream lag in seconds.
Expensive queries. A dashboard asking for a year of raw data across 100,000 series can occupy the cluster. Apply a maximum number of series and samples per query, a timeout, automatic selection of rollups for long ranges and a cache for repeated queries.
A storage node fails. Replication (three copies) keeps the data available, and the write-ahead log lets a restarted node rebuild its in-memory head. Writers retry against the replicas.
Late and out-of-order samples. Clock skew or a delayed agent produces timestamps in the past. Accept a bounded window (for example two hours) and reject older samples rather than rewriting compressed blocks.
Who monitors the monitor? The alerting path must stay up when the storage layer is struggling. Run alert evaluation as its own sharded service reading recent data from memory, give it a separate, simpler notification path, and add a dead-man's switch: an alert that always fires, sent to an external service, which pages you when it stops arriving. What to put in the rules themselves is covered in monitoring and alerting.
Trade-offs to name aloud
- Purpose-built storage over a general database: an extra system to run, in exchange for a tenfold smaller footprint and faster queries.
- Rollups: a loss of fine detail on old data, in exchange for cheap long-range queries.
- Series limits at ingest: some teams are told no, in exchange for a system that survives cardinality mistakes.
- A stream in front of storage: extra latency of a second or two, in exchange for burst absorption and replay.
- Pull versus push: control and free liveness against reach and short-lived jobs.
What interviewers listen for
- A working answer: agents or scrapers, a time-series store, a query layer, dashboards and alert rules with notifications.
- A strong answer: computes samples per second and bytes per day, explains why a general database fails and how time-series compression works, and designs rollups.
- A standout answer: also treats cardinality as the central risk with limits at ingest, compares pull and push with the liveness argument, keeps alerting independent of the query path and adds a dead-man's switch.
Check your understanding
Common mistakes
Designing the dashboard. The charts are the visible part. The design is the ingest rate, the storage format, cardinality and the alert path.
Using a relational table for samples. It works in a prototype. At a million inserts per second it is the first thing to fail, and the numbers above show why.
Ignoring cardinality. Series count, not sample volume, is the usual cause of monitoring outages. Say it, and show the limit at ingest.
Making the alert path depend on the query path. If dashboards slow the database, alerts must still fire. Give alerting its own evaluation path and a dead-man's switch.
Keeping everything at full resolution. Ten-second data for a year is 30 times the data of 5-minute rollups for the same period, with little added value.
Forgetting liveness. A host that stops reporting produces no samples, so there is nothing to alert on unless you detect missing data or use pull-based up signals.
Practice
A dashboard showing 1,000 series over 30 days times out. Samples are every 10 seconds. What do you change?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Count how many points the query reads, and compare that with how many pixels a graph has.
Show a strong answer
Count the work. 30 days × 86,400 s ÷ 10 s = 259,200 points per series, and 1,000 series means 259 million points read and aggregated for one panel.
Use rollups for long ranges. 5-minute rollups give 30 × 288 = 8,640 points per series, or 8.6 million in total, thirty times less. The query planner should choose the rollup resolution from the time range automatically.
Limit the output. A graph about 1,000 pixels wide cannot show more than about 1,000 points per line, so ask for a step that fits and aggregate on the server rather than shipping raw points.
Cache and bound. Cache the result for the dashboard's refresh interval, and enforce per-query limits on series and samples, with a clear error, so one panel cannot starve alert evaluation.
The pattern worth keeping: match the resolution of the data you read to the resolution the reader can see.
During a major outage, your monitoring cluster is overloaded and alerts stop firing. How do you design so that this cannot go unnoticed?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
The system that detects failure needs its own failure detection, outside itself.
Show a strong answer
Separate the alert path. Run alert rule evaluation on dedicated nodes reading from in-memory recent data, with resource limits that dashboard queries cannot exceed. Alerts get priority over ad hoc queries.
Add a dead-man's switch. Define a rule that always fires and send it every minute to an external service (a different provider or region). If the heartbeat stops arriving, that service pages the team, so a dead monitoring stack is itself an alert.
Keep a minimal independent check. A small second system, with simple external probes of your main endpoints, can run without your metrics pipeline at all, so you still know the user-facing service is up.
Let agents buffer. Agents hold the last 10 to 15 minutes of samples locally and retry, so a short outage of the ingest tier loses no data.
The pattern worth keeping: the thing that watches must not share a failure mode with the thing it watches.
Key takeaways
- Start from the numbers: 1 million samples a second is 86.4 billion a day, 1.4 TB raw and 130 GB compressed.
- A relational table cannot hold it. Use an append-only time-series store with delta-of-delta and XOR compression.
- Cardinality is the real risk: limit series at ingest and keep unbounded identifiers out of labels.
- Roll up old data, and let the query planner pick the resolution by range.
- Pull gives free liveness, push covers short jobs: a hybrid is the usual answer.
- Keep alerting independent, and add a dead-man's switch for the monitor itself.
Further reading
- T. Pelkonen et al., "Gorilla: A Fast, Scalable, In-Memory Time Series Database", VLDB (2015): delta-of-delta and XOR compression.
- B. Beyer et al. (eds.), "Site Reliability Engineering" (O'Reilly, 2016), the chapters "Monitoring Distributed Systems" and "Practical Alerting from Time-Series Data".
- Prometheus documentation, "Overview" and "Storage": the pull model, labels and the local storage layout.