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 Published 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

Back-of-envelope sizing for fleet-wide monitoring (assumed figures)
QuantityAssumptionResult
Sources100,000 hosts, about 500 active series eachabout 50 million active series
Ingestone sample per series every 10 secondsabout 5 million samples a second
Raw size16 bytes a sample (8-byte timestamp, 8-byte value)about 80 MB/s, about 6.9 TB a day uncompressed
Compressedabout 1.5 bytes a sample (assumed, typical for regular series)about 650 GB a day
Raw retention15 days at full resolutionabout 9.7 TB, before replication
A year at full resolutioncompressed, if nothing were rolled upabout 237 TB, which is why rollups exist
Back-of-envelope sizing for fleet-wide monitoring (assumed figures). Scroll sideways on a small screen.

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" }
Write, query and alert-rule interfaces

4. Sketch the data model

Series, samples and the index that finds them
PieceShapeNotes
Series IDhash of name + sorted labelsStable identity for one stream of samples
Sample(timestamp, float value)Appended in time order per series
Chunka compressed run of samples for one series, e.g. two hoursUnit of storage and caching
Blockall chunks for a time window plus its indexImmutable once closed; deleted or downsampled as a whole
Inverted indexlabel pair -> list of series IDsAnswers "all series with service=checkout and status=500" by intersecting lists
Series, samples and the index that finds them. Scroll sideways on a small screen.

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

Pull or push collection
ModelHow it worksGoodAwkward
Pull (scrape)Collectors fetch a metrics endpoint from each target every N seconds, using service discovery to find targetsKnowing a target is down is built in (the scrape fails); targets stay simpleShort-lived jobs may finish between scrapes; targets behind firewalls are hard to reach
PushAgents or applications send samples to an ingestion endpointWorks for short jobs, edge devices and across networksNeeds a separate check for silent targets; a misbehaving client can flood ingestion
Pull or push collection. Scroll sideways on a small screen.

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]
Delta-of-delta on scrape timestamps (run with python3; round-trip checked on 2,000 random series)

6. The architecture

  1. Sources
    • Hosts and services (metrics endpoints)
    • Batch jobs and agents (push)
    • Service discovery
  2. Ingestion
    • Scrapers
    • Ingestion gateway
    • Ingesters partitioned by series (WAL + memory)
  3. Storage
    • Object storage blocks
    • Compactor and rollups
    • Inverted label index
  4. Read
    • Query service + results cache
    • Dashboards
  5. Alerting
    • Rule evaluator
    • Alert manager (dedupe, group, route)
    • External dead-man's switch
Collection, storage, query and alerting paths. Hosts and services expose metrics that scrapers collect on a schedule, found through service discovery, while batch jobs and agents push through an ingestion gateway. Both write into a stream or directly into ingesters, which are partitioned by series and replicated, holding recent data in memory with a write-ahead log. Ingesters flush compressed blocks to object storage, where a compactor merges blocks and writes rollups. A query service reads recent data from ingesters and older data from blocks, with a results cache, serving dashboards. An alert evaluator runs rules every interval against the query service and sends firing alerts to an alert manager, which deduplicates, groups and routes notifications to chat, email and paging. An external heartbeat check watches the monitoring system itself.
  1. CollectScrapers, sharded by target, fetch each endpoint every 10 seconds and attach target labels (service, region, host).
  2. 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.
  3. 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).
  4. 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.
  5. AlertRule evaluators run each rule every 30 to 60 seconds. A rule that stays true for its for duration 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 modes worth naming
FailureEffectMitigation
Cardinality explosionIngester memory runs out; ingestion stalls for everyonePer-tenant series limits, rejecting new series above the limit, alerts on series growth
Ingester crashRecent in-memory data at riskWAL replay on restart and replicas holding the same series
Monitoring outage during an incidentNobody is paged while things burnRun alerting separately from dashboards, in another failure domain, plus an external heartbeat that pages if alerts stop arriving
Alert stormHundreds of pages for one root causeGroup by service and region, inhibit symptom alerts when a cause alert is firing, rate-limit notifications
Heavy queryOne dashboard scans billions of samples and slows everyoneQuery limits on series and samples, rollup selection, per-tenant query queues
Late or out-of-order samplesRejected or misplaced pointsAccept a small out-of-order window in the head block; drop anything older and count the drops
Failure modes worth naming. Scroll sideways on a small screen.

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

Catching the cardinality trap
Interviewer
A team adds a customer_id label 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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP