← Back to System Design, page 4

system-design-0062 · Medium mid

Design a metrics and monitoring system like Prometheus or Datadog that collects metrics from 100,000 hosts and alerts on problems within a minute.

Agents on each host collect metrics and push them (or are scraped) into an ingestion tier that writes to a time-series database partitioned by series. Samples are compressed with delta-of-delta timestamps and XOR-encoded values to about 1.4 bytes each, which turns 13.8 TB per day of raw samples into about 1.2 TB. Downsampling keeps old data cheap, and a separate alerting service evaluates rules on recent data every 30 seconds.

Full answer

Requirements

Functional:

  • Collect counters, gauges and histograms with labels (service, host, region).
  • Query and graph any metric over time; aggregate across labels.
  • Alert rules (for example "error rate above 2% for 5 minutes") that notify on-call staff.

Non-functional:

  • Alerts within about a minute of a problem.
  • Ingestion keeps working during incidents, when load spikes.
  • Recent data (two weeks) at full resolution; a year at lower resolution.

Capacity estimates

Assumptions: 100,000 hosts, 1,000 active series per host, one sample every 10 seconds, 16 bytes per raw sample (8-byte timestamp, 8-byte value), about 1.37 bytes per sample after compression.

  • Active series: 100,000 x 1,000 = 100M.
  • Samples: 100M / 10 = 10M per second.
  • Raw volume: 10M x 16 bytes x 86,400 = about 13.8 TB per day.
  • Compressed: 10M x 1.37 x 86,400 = about 1.2 TB per day, about 17 TB for 14 days of full resolution.

API

POST /v1/write (batched, compressed) [{"series": "http_requests_total{service=api,code=500}", "samples": [[ts, value], ...]}] GET /v1/query?expr=sum(rate(http_requests_total{code="500"}[5m])) by (service)&start=..&end=..&step=30s POST /v1/alerts/rules {"expr": "...", "for": "5m", "severity": "page", "route": "team-payments"}

Data model

  • Series ID = hash of metric name plus sorted labels.
  • Inverted index: label value to list of series IDs, so service=api finds all matching series.
  • Chunks: per series, blocks of about 2 hours of compressed samples.
  • Downsampled tables: 5-minute and 1-hour averages, min, max and count.

High-level design

mermaid
flowchart LR
  AG[Host agents] --> ING[Ingestion tier]
  ING --> K[(Write-ahead buffer)]
  K --> TS[(TSDB shards by series hash)]
  TS --> DS[Downsampler]
  DS --> COLD[(Object storage, downsampled)]
  Q[Query service] --> TS
  Q --> COLD
  AL[Alert evaluator] --> Q
  AL --> NT[Notifier: pager, chat, email]
  UI[Dashboards] --> Q

Key techniques

  • Compression (Gorilla style). Timestamps arrive at regular intervals, so the delta of deltas is usually 0 and takes 1 bit. Values change slowly, so XOR with the previous value leaves mostly zero bits. Together this averages around 1.37 bytes per sample.
  • Sharding by series hash spreads writes; queries fan out to shards and merge.
  • Write-ahead buffer (Kafka or an internal log) protects against TSDB node loss and absorbs spikes.
  • Alerting runs rules every 30 seconds on in-memory recent data, with a for duration to avoid flapping, and routes and groups notifications so one outage creates one page, not 500.

Bottlenecks and trade-offs

  • Cardinality explosions. A label such as user_id or request_id creates millions of new series and can take down the system. Enforce per-tenant series limits and reject high-cardinality labels.
  • Push versus pull. Pull (scraping) makes target health visible and simple to control; push works better for short-lived jobs and across firewalls.
  • Monitoring must outlive what it monitors. Run the alerting path separately from the main system and have a "dead man's switch" alert that fires if no data arrives.
  • Downsampling loses spikes shorter than the step; keep max values in rollups.

By level

Fresher: Explain metrics as numbers over time with labels, collected by agents and shown on graphs. A fresher should describe a simple alert rule with a threshold and a duration.

Mid: Size ingestion and storage, explain compression and downsampling, and design the alert evaluator with routing. Mention the label index.

Senior: Discuss cardinality control, push versus pull, monitoring independence, histogram storage and multi-tenancy. Expect a plan for the dead man's switch.

Key points

  • About 100M series and 10M samples per second
  • Gorilla-style compression to about 1.4 bytes per sample
  • Shard by series hash with an inverted index on labels
  • Downsample old data and keep max values
  • Alerting runs separately with for-durations and grouping

Common mistakes

  • Allowing unbounded label cardinality
  • Storing each sample as a database row
  • Running alerting on the same cluster it monitors with no fallback
  • Downsampling with averages only and losing spikes

Follow-ups

  • How would you store histograms for latency percentiles?
  • How would you support multi-tenant limits?
  • How do you alert if the monitoring system itself is down?

Tips

  • Do the samples per second math first
  • Explain cardinality risk with a bad label example
  • Mention compression to justify storage

Evaluation rubric

  • Correct capacity math
  • Time-series storage and compression
  • Alerting design with noise control
  • Cardinality and reliability trade-offs