System design interview: design a metrics monitoring and alerting system
A metrics monitoring system collects numeric measurements from every server and service, stores them as time series, draws dashboards and fires alerts when something crosses a threshold. The design questions are how data is collected (pulled or pushed), how millions of series are stored cheaply, how queries over weeks of data stay fast, and how alerting keeps working when the systems it watches are failing.
By Evin JohnPublished 8 min read
1. Clarify the requirements
Clarify early that this is about metrics (numbers over time), not logs or traces. They share dashboards but have very different storage needs.
- Functional: collect metrics such as CPU, memory, request counts and latencies from hosts and services; store them with labels such as service, region and host; query and graph them over any time range; define alert rules and notify on-call people through chat, email or paging.
- Non-functional: new data visible on dashboards within seconds; dashboards over a day of data load in about a second; alerts fire within a minute of a problem; the system keeps alerting during partial outages of what it monitors; storage cost grows slower than the fleet.
- Out of scope unless asked: log search, distributed tracing, anomaly detection with machine learning, billing for a multi-tenant product.
2. Estimate the scale
| Quantity | Assumption | Result |
|---|---|---|
| Sources | 100,000 hosts, about 500 active series each | about 50 million active series |
| Ingest | one sample per series every 10 seconds | about 5 million samples a second |
| Raw size | 16 bytes a sample (8-byte timestamp, 8-byte value) | about 80 MB/s, about 6.9 TB a day uncompressed |
| Compressed | about 1.5 bytes a sample (assumed, typical for regular series) | about 650 GB a day |
| Raw retention | 15 days at full resolution | about 9.7 TB, before replication |
| A year at full resolution | compressed, if nothing were rolled up | about 237 TB, which is why rollups exist |
Ingest is write-heavy and steady; queries are rare by comparison but can touch millions of samples each. The numbers also show where cost hides: a single careless label such as a user ID or request ID can turn 50 million series into billions, so cardinality limits are part of the design, not an afterthought.
3. Define the API
Write (push agents or the scraper):
POST /v1/write [ { "name": "http_requests_total",
"labels": { "service": "checkout", "region": "eu-west", "status": "500" },
"samples": [ [1800000000, 18342] ] } ]
Query:
GET /v1/query_range?expr=rate(http_requests_total{service="checkout",status="500"}[5m])
&start=...&end=...&step=60s
Alert rule:
{ "expr": "error_ratio{service='checkout'} > 0.02", "for": "5m",
"severity": "page", "route": "payments-oncall" }4. Sketch the data model
| Piece | Shape | Notes |
|---|---|---|
| Series ID | hash of name + sorted labels | Stable identity for one stream of samples |
| Sample | (timestamp, float value) | Appended in time order per series |
| Chunk | a compressed run of samples for one series, e.g. two hours | Unit of storage and caching |
| Block | all chunks for a time window plus its index | Immutable once closed; deleted or downsampled as a whole |
| Inverted index | label pair -> list of series IDs | Answers "all series with service=checkout and status=500" by intersecting lists |
Counters (always increasing totals), gauges (values that go up and down) and histograms (counts per latency bucket) are the common metric types. Histograms deserve a sentence in the interview: storing bucket counts lets you compute percentiles across many hosts later, which averaging per-host percentiles cannot do correctly.
5. The core decision: collection and storage
| Model | How it works | Good | Awkward |
|---|---|---|---|
| Pull (scrape) | Collectors fetch a metrics endpoint from each target every N seconds, using service discovery to find targets | Knowing a target is down is built in (the scrape fails); targets stay simple | Short-lived jobs may finish between scrapes; targets behind firewalls are hard to reach |
| Push | Agents or applications send samples to an ingestion endpoint | Works for short jobs, edge devices and across networks | Needs a separate check for silent targets; a misbehaving client can flood ingestion |
Many real systems mix the two: scrape long-running services and accept pushes from batch jobs through a gateway. Either way, ingestion lands in a time-series store whose job is to make appends cheap and range reads fast. Recent samples go to an in-memory head block per series, backed by a write-ahead log for crash recovery. Every couple of hours the head is cut into an immutable, compressed block on disk.
Compression is what makes the arithmetic work. Scrape timestamps arrive at nearly fixed intervals, so storing the change in the gap between samples (delta of delta) turns most timestamps into zeros, which pack into a bit or two each. Values are often close to the previous one, so XOR-ing their bits with the previous value leaves mostly zeros as well; this pairing is the scheme described in Facebook's Gorilla paper.
def delta_of_delta(timestamps):
"""Return the first timestamp, the first delta, then delta-of-deltas."""
out = [timestamps[0], timestamps[1] - timestamps[0]]
for i in range(2, len(timestamps)):
out.append((timestamps[i] - timestamps[i - 1]) - (timestamps[i - 1] - timestamps[i - 2]))
return out
scrapes = [1_800_000_000, 1_800_000_010, 1_800_000_020, 1_800_000_030, 1_800_000_041, 1_800_000_050]
print(delta_of_delta(scrapes)) # [1800000000, 10, 0, 0, 1, -2]6. The architecture
- Sources
- Hosts and services (metrics endpoints)
- Batch jobs and agents (push)
- Service discovery
- Ingestion
- Scrapers
- Ingestion gateway
- Ingesters partitioned by series (WAL + memory)
- Storage
- Object storage blocks
- Compactor and rollups
- Inverted label index
- Read
- Query service + results cache
- Dashboards
- Alerting
- Rule evaluator
- Alert manager (dedupe, group, route)
- External dead-man's switch
- CollectScrapers, sharded by target, fetch each endpoint every 10 seconds and attach target labels (service, region, host).
- IngestSamples are routed by series ID to ingesters, each series to two or three replicas. Ingesters append to memory and the WAL and reject series that exceed a tenant's cardinality limit.
- PersistEvery two hours each ingester writes its closed head block to object storage. The compactor merges small blocks into larger ones and produces 1-minute and 1-hour rollups (min, max, sum, count per window).
- QueryThe query service finds matching series through the label index, fetches the chunks for the time range from ingesters (recent) and blocks (older), and picks rollups when the requested step is coarse.
- AlertRule evaluators run each rule every 30 to 60 seconds. A rule that stays true for its
forduration fires; the alert manager groups related alerts and sends one notification per group.
7. Scale it
- Shard ingestion by series. Hashing the series ID spreads load evenly; replicate each series to more than one ingester so a crash loses nothing that was acknowledged. The general method is in sharding.
- Enforce cardinality limits. Cap series per metric and per tenant, reject or drop labels such as user IDs, and show teams their top series. One bad deploy can otherwise multiply memory use.
- Downsample for long ranges. A year-long graph at a 1-day step should read hourly or daily rollups, never raw samples.
- Cache query results by expression and aligned time range; dashboards refresh the same queries every few seconds. Caching covers the invalidation side.
- Buffer with a log. Writing ingest traffic to a message queue first decouples collection from storage, so a slow ingester causes lag rather than lost samples.
8. What breaks, and what you do about it
| Failure | Effect | Mitigation |
|---|---|---|
| Cardinality explosion | Ingester memory runs out; ingestion stalls for everyone | Per-tenant series limits, rejecting new series above the limit, alerts on series growth |
| Ingester crash | Recent in-memory data at risk | WAL replay on restart and replicas holding the same series |
| Monitoring outage during an incident | Nobody is paged while things burn | Run alerting separately from dashboards, in another failure domain, plus an external heartbeat that pages if alerts stop arriving |
| Alert storm | Hundreds of pages for one root cause | Group by service and region, inhibit symptom alerts when a cause alert is firing, rate-limit notifications |
| Heavy query | One dashboard scans billions of samples and slows everyone | Query limits on series and samples, rollup selection, per-tenant query queues |
| Late or out-of-order samples | Rejected or misplaced points | Accept a small out-of-order window in the head block; drop anything older and count the drops |
9. Trade-offs to discuss
- Pull or push. Pull gives free liveness checks and simple targets; push reaches short-lived and remote sources. A mix is common.
- Resolution versus cost. Ten-second samples kept forever are expensive; rollups lose detail such as short spikes, which max values in the rollup partly preserve.
- Availability over consistency. A monitoring system should keep accepting and serving data during partitions even if a graph is briefly incomplete. A missing sample is better than a blocked write (consistency and CAP).
- Build or reuse a store. A general database can hold time series at small scale; at millions of samples a second, a purpose-built append-only format with compression wins.
- Static thresholds or smarter alerts. Thresholds are predictable and easy to reason about; rate-of-change and error-budget alerts page less for noise but are harder to explain to the person woken up at 3 a.m.
10. How to talk through it in the interview
Fictional example
- Interviewer
- A team adds a
customer_idlabel to their request counter. What happens? - Candidate
- Every customer becomes a separate series for every combination of the other labels. With a hundred thousand active customers, that one metric could add millions of series, and the ingesters holding them run out of memory. I would cap series per metric and per tenant, reject new series above the cap and alert the team. Per-customer numbers belong in logs or an analytics store.
- Interviewer
- And if the monitoring cluster itself fails?
- Candidate
- Alerting runs separately, and an external service expects a heartbeat alert every minute. If it stops arriving, that service pages us.
For 45 minutes, try: 5 minutes on scope (metrics only) and retention, 5 on the estimate (series count and samples per second), 5 on the data model and labels, 10 on collection and the storage engine, 10 on queries, rollups and alerting, and 10 on failures and trade-offs. Bring up cardinality in the estimate; it signals experience.
- Define a series as name plus labels before anything else.
- Explain why compression and rollups are what make the storage bill reasonable.
- Make sure the alerting path survives the outage it is meant to report.
Practicing this design with Natively
Ops-flavored prompts like this one invite follow-ups about incidents, so practice with someone who will ask them. On the mock call, Natively produces a running transcript of both speakers and can propose talking points when a question arrives; looking back, you can check whether you raised cardinality and the monitoring-the-monitor problem. Ask it for a diagram of the collection and alerting paths to test your own drawing against. The transcript and notes are saved for review.
Questions people ask
How do you design a metrics monitoring system?
Collect samples by scraping or pushing, store each series (a metric name plus labels) in a compressed time-series store partitioned by time, keep raw data for days and rollups for months, and query through an index of labels. Run alert rules on a schedule and route notifications through a deduplicating alert manager.
Pull or push for metrics collection?
Pull (scraping) makes it obvious when a target is down and keeps targets simple; push suits short-lived jobs and sources behind firewalls. Many systems scrape long-running services and accept pushes from batch jobs through a gateway.
What is metric cardinality and why does it matter?
Cardinality is the number of distinct series, meaning every unique combination of label values. A label such as a user ID can multiply series into the millions and exhaust ingester memory. Designs cap series per metric and per tenant and keep high-cardinality data in logs instead.
How do time-series databases store data so compactly?
Scrape timestamps arrive at nearly fixed intervals, so storing delta-of-deltas turns most of them into zeros. Values close to the previous value compress well with XOR encoding. Together these can bring a sample down to a byte or two instead of 16.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
