Design: metrics and monitoring system
Buffer samples through an ingest pipeline into a compressed time-series store sharded by series, downsample old data for long ranges, cap label cardinality, and evaluate alert rules on recent data, independently of what they watch.
Fundamentals you'll use
How it works
- A series is a metric name plus labels; scale (assumed) is 10M active series, ~670k samples/s.
- Buffer ingest in Kafka, shard writers by series hash, keep ~2 h in memory, flush compressed blocks.
- Gorilla compression cuts 16 bytes per point to ~1.37 by storing only what changed.
- Downsample to 5 m and 1 h for long ranges; shorter raw retention is what saves disk.
- Cap label cardinality at ingest, and make alerting survive the outage it should report.
Check yourself
Answer to mark it learned; your answers aren't scored.
Overnight, TSDB writer memory triples while samples/s grows only 5%. Yesterday a team added a request_id label to its latency metric. What do you do first?
Go deeper
Full explanation
Requirements
Functional: ingest counters, gauges and histograms with labels; query and graph them; alert on rules; keep a year or more of history. Non-functional: emitting metrics never slows the service; new data is queryable within seconds; alerts keep working while the system is degraded. Assume 10k hosts × 1,000 series = 10M active series, sampled every 15 s ≈ 670k samples/s.
Data model and API
A series is a metric name plus a label set, http_requests_total{service="cart", code="500"}; a sample is (timestamp, float64). Writes arrive as batches (pushed, or scraped from /metrics in the Prometheus style); reads are query(expr, start, end, step).
Architecture
- Agents send batches to an ingest tier that enforces limits, backed by a Kafka buffer so a storage hiccup drops nothing.
- Writers shard by
hash(series); each keeps the last ~2 h in memory behind a write-ahead log, then flushes immutable compressed blocks. - Blocks move to object storage; a compactor merges them and writes 5 m and 1 h downsampled copies for long-range queries.
- A query tier fans out and merges. A rule engine evaluates alerts every ~1 min and hands firing ones to a notifier that dedups, groups and routes them.
The hard parts
Compression. Facebook's Gorilla stores timestamps as delta-of-deltas and values as an XOR with the previous one: 16 bytes per point down to ~1.37 (12×). Prometheus reports 1–2 bytes per sample.
Cardinality. Every unique label combination is a new series. One user_id label can turn 10 series into 10M and exhaust writer memory. Enforce series limits per tenant at ingest; per-user detail belongs in logs and traces.
Independent alerting. Alerts can't depend on the outage they report: run the rule engine redundantly, and add a dead man's switch alert that pages when the pipeline goes quiet.
Code Why time series compress: delta-of-delta and XOR
import struct
def f64_bits(x: float) -> int:
return struct.unpack(">Q", struct.pack(">d", x))[0]
def gorilla_fields(points: list[tuple[int, float]]):
"""Gorilla's idea: store how each point differs from the previous one.
On real metrics these are mostly 0, and Gorilla encodes a 0 in a single bit."""
t0, v0 = points[0]
out = [("header", t0, v0)] # first point stored in full
prev_t, prev_delta, prev_v = t0, 0, v0
for t, v in points[1:]:
delta = t - prev_t
dod = delta - prev_delta # steady 15 s scrapes -> 0
xor = f64_bits(v) ^ f64_bits(prev_v) # unchanged value -> 0
out.append((dod, hex(xor)))
prev_t, prev_delta, prev_v = t, delta, v
return out
# 15 s scrapes, the last one 1 s late; a gauge that barely moves
for row in gorilla_fields([(1000, 42.0), (1015, 42.0), (1030, 42.0), (1046, 43.0)]):
print(row)
# ('header', 1000, 42.0)
# (15, '0x0') first delta: stored once
# (0, '0x0') 2 bits for the whole point
# (1, '0x800000000000') small dod + one short run of meaningful XOR bitsReal example
At 02:10 the cart service's error ratio climbs. Its agent sends http_requests_total{service="cart",code="500"} every 15 s; samples pass through Kafka to the writer that owns that series. A rule "error ratio > 2% for: 5m" is evaluated every minute and goes from pending to firing at 02:15. The notifier groups 40 per-pod alerts into one page for the cart team and inhibits the downstream checkout-latency alert. The on-call's 90-day graph reads ~2k hourly points per series instead of ~520k raw ones.
Trade-offs +3 · −3
+ You gain
- Recent data in memory makes dashboards and alert rules fast.
- Compression (~1.37 B per point) plus per-resolution retention keeps a year of data affordable.
- The Kafka buffer absorbs storage hiccups without dropping samples or slowing services.
− You pay
- Cardinality is unbounded by default; one bad label can take the cluster down.
- Downsampled points hide short spikes unless you keep min and max per step.
- Many moving parts (Kafka, writers, compactor, object storage) behind what users see as graphs.
Use it when
Fleet-wide numeric telemetry: service health, SLOs, capacity planning, per-minute business KPIs, anything you alert on.
Avoid it when
Per-request or per-user detail (use logs or traces), exact billing counts (use a transactional store), or a small fleet where one Prometheus server or a SaaS is enough.
Numbers to know 5
- Ingest (assumed): 10k hosts × 1,000 series ÷ 15 s ≈ 670k samples/s.
- Storage: 670k/s × 86,400 s × ~1.37 B ≈ 79 GB/day raw, ~29 TB/year before retention and downsampling.
- Gorilla (VLDB 2015): 16 B to ~1.37 B per point (12×); ~96% of timestamps compress to a single bit.
- Prometheus defaults: 2 h blocks, 15-day local retention, 1 m scrape and rule-evaluation intervals (checked Nov 2026).
- Thanos: 5 m resolution for blocks older than 40 h, 1 h for blocks older than 10 days.
Common pitfalls 4
- Labels with unbounded values (
user_id,request_id, URL paths): series explode and writers run out of memory. - Alerting through the pipeline it watches, with no dead man's switch: the outage silences its own alarm.
- Expecting downsampling to save disk: it adds blocks; savings come from shorter raw retention.
- Paging on every cause (CPU, one pod down) instead of user-facing symptoms: alert fatigue.
Interview questions 3
Answer out loud first, then reveal.
How do you stop one team from blowing up cardinality?Show answer
At ingest, not in storage. I track active series per tenant and per metric (an approximate count is fine) and reject new series past a quota, while samples for existing series keep flowing, so their dashboards still work. I publish a rejected-series metric naming the offending label so the team can fix it fast, lint label names in CI, and steer per-request ids to traces, where high cardinality is cheap.
The metrics cluster is down. How do you know your services are healthy?Show answer
That's why alerting is partly independent. The rule engine runs as redundant replicas near ingest, the notifier dedups across them, and a dead man's switch, an always-firing alert sent to an external service, pages when it stops arriving. I'd also run a few black-box probes of critical endpoints from another provider. The metrics system itself is watched by a separate, much smaller one.
Why not store metrics in a regular SQL database?Show answer
Volume and access pattern. ~670k samples/s is ~58B rows a day; a row store spends tens of bytes per row plus indexes, while a TSDB stores ~1–2 bytes per sample because it compresses each series' timestamps and values together. Queries read one series over a time range, so time-ordered per-series chunks fit far better than rows. Kafka stays the buffer, not the query engine.
Deep dive 4
Write path: buffer, shard, compress
Pull (Prometheus scrapes /metrics) gives up/down detection for free and lets the server set the pace; push suits short-lived jobs and devices behind NAT. Either way, land batches in Kafka so a slow or restarting writer never blocks producers and can replay. Writers own series by hash, append to a write-ahead log and build compressed per-series chunks in memory. Every ~2 h they flush an immutable block with an inverted index from label pairs to series ids, so {service="cart"} finds its series without a scan. For redundancy, two writers consume the same partition, or you rely on Kafka replay.
Cardinality: the real cost driver
Memory and index size scale with active series, not with samples. A code label with a handful of values is fine; user_id, request_id or raw URL paths are unbounded, and 10 series × 1M users is 10M new series from one label. Defend at ingest: per-tenant and per-metric limits on new series (existing ones keep flowing, so dashboards survive), a metric of rejected series naming the offending label, and a CI lint for label names. Prometheus's docs note that cutting series saves more than lengthening the scrape interval. Put per-user detail in logs and traces, where high cardinality is cheap.
Retention and downsampling
A Thanos-style compactor writes 5 m resolution for blocks older than 40 h and 1 h for blocks older than 10 days. Its purpose is query speed: a 90-day graph reads ~2k hourly points per series instead of ~520k raw ones. Keep min and max per step, not just the average, or short spikes vanish. Downsampling alone doesn't save disk; Thanos warns that keeping every resolution grows storage ~3×. Savings come from retention per resolution, for example raw for 15 days, 5 m for 90 days and 1 h for 2 years (assumed).
Alerting that survives outages
Rules run every ~1 min against recent in-memory data, the fast path. for: 5m keeps an alert pending until the condition has held that long, which cuts flapping. Run two rule-engine replicas; the notifier (Alertmanager-style) dedups their copies, groups related alerts into one page, inhibits downstream noise and honours silences. Alert on user-facing symptoms and SLO burn, not on every cause (SLIs, SLOs & error budgets). Then monitor the monitor: an always-firing dead man's switch alert goes to an external service, which pages when it stops arriving.