Lesson 35 of 38Case studies
Design a Metrics and Alerting System
Design a Prometheus-style metrics platform: labels and cardinality, push vs pull, compressed time-series storage, rollups, and alerts that do not storm.
At 3 a.m. the checkout error rate jumps from 0.1% to 8%. Whether someone is paged within a minute, or customers find out first, depends on the metrics system. Every company over a certain size runs one, either built on Prometheus or bought from a vendor, and engineers lean on it daily. It is also a popular senior interview prompt, because the obvious design (put every data point in a database table) dies at the first contact with real volume, and the right design uses ideas from compression, storage engines, and stream processing at the same time.
Requirements
Functional
- Services emit numeric metrics: request counts, latencies, queue depths, CPU.
- Engineers query them on dashboards: "error rate per endpoint, last 6 hours", "p99 latency, last 30 days".
- Alert rules run continuously ("error rate above 2% for 5 minutes") and notify the right on-call person.
Non-functional
- Ingest 10 million data points a second from about 100,000 hosts.
- Dashboards over 30 days load in a couple of seconds.
- An alert fires within about one minute of the condition becoming true.
- The system must stay up when the things it watches are down. A monitoring system that fails during an outage is worse than none, because people trust it.
Out of scope: logs and traces (the Observability, SLIs, and SLOs lesson covers how the three fit together), and billing for a hosted product.
Back-of-the-envelope numbers
| Quantity | Math | Result |
|---|---|---|
| Active series | 10M points/s × 15 s scrape interval | about 150 million series |
| Raw size | 10M × 16 bytes (8-byte timestamp + 8-byte float) | 160 MB/s, about 14 TB/day |
| Compressed | 10M × about 1.4 bytes | 14 MB/s, about 1.2 TB/day |
| 15 days at full resolution | 1.2 TB × 15 | about 18 TB (before replication) |
| In-memory index | 150M series × a few KB each | hundreds of GB of RAM, spread across nodes |
Two numbers drive the whole design. Compression shrinks storage roughly 10x, so disk is not the hard part. The hard part is 150 million series, because each one costs memory for its index entry and its open in-memory chunk, no matter how few points it has.
Data model: series, labels, and cardinality
A metric sample is a name, a set of labels, a timestamp, and a float value:
http_requests_total{service="checkout", method="POST", status="500"} 1761120000 1027The name plus the exact set of label values identifies one time series. Change any label value and you have a different series. The count of distinct series is called cardinality, and it is the scaling limit of every metrics system.
Cardinality multiplies. Ten services × 5 methods × 20 status codes × 50 endpoints is already 50,000 series for one metric. Now someone adds user_id as a label "to debug one customer". With a million users, that metric becomes 50 billion possible series. The ingesters run out of memory, and the whole platform is down for every team. This is the most common way real metrics systems break, so production platforms enforce per-tenant series limits and reject new series past the limit.
The rule to remember: labels are for bounded dimensions (region, status class, endpoint template). Unbounded values (user IDs, request IDs, full URLs) belong in logs or traces.
A team adds a pod label to a metric that already has 4 endpoints and 6 status codes. The service runs 30 pods, and pods are replaced on every deploy, 10 deploys a day. How many series appear in one day?
endpoints, statuses, pods, deploys = 4, 6, 30, 10 print(endpoints * statuses * pods * deploys)
Push or pull?
There are two ways to get samples from 100,000 hosts into the system.
- Pull (Prometheus scraping). Each service exposes
/metricsas plain text. The collector discovers targets through service discovery (the Kubernetes API, Consul, cloud APIs) and fetches every target every 15 to 60 seconds. A failed scrape is itself a signal: the built-inupmetric goes to 0, so "the service is dead" and "the service is quiet" are different. You can also curl/metricsby hand when debugging. - Push (OpenTelemetry OTLP, StatsD). The service sends samples to a collector endpoint. This suits short-lived jobs, serverless functions, and clients behind NAT that a scraper cannot reach.
Pull has one classic gap: a batch job that runs for 20 seconds may finish between scrapes. Prometheus's answer is the Pushgateway, a small cache the job pushes to before exiting, which is then scraped. Use it only for batch jobs, because it never forgets a value on its own, so a dead job looks alive forever.
In practice large companies run both. An OpenTelemetry Collector or a Prometheus agent sits near each cluster, scrapes or receives local samples, and remote-writes them to a central store. Recent Prometheus versions can also accept OTLP pushes directly. In the interview, say that the choice matters less than service discovery, liveness detection, and buffering at the edge.
High-level design
An agent in each cluster discovers targets and scrapes them every 15 s. If the central system is slow, the agent buffers to local disk instead of dropping samples.
The shape is the same one used by Grafana Mimir, Cortex, Thanos, and VictoriaMetrics, with small differences. Thanos keeps plain Prometheus servers and adds a sidecar that uploads their blocks. Mimir runs the distributor and ingester split shown here, and its newer versions can put a Kafka-compatible log between them. Check each project's docs for the current architecture, because they evolve quickly.
Deep dive 1: storing time series cheaply
A time series has an unusual access pattern. Writes are append-only and almost always in time order. Nobody updates an old point. Reads scan a time range of a few series. That pattern lets you skip almost everything a general database does.
The layout looks like an LSM tree, the structure behind write-heavy databases such as Cassandra and RocksDB. New samples go to an in-memory head block, one open chunk per series, plus a write-ahead log so a crash loses nothing. Every 2 hours the head is cut into an immutable block on disk: compressed chunks, plus an inverted index that maps each label pair to the series IDs that have it (service="checkout" → [12, 98, 4410]). A query like {service="checkout", status="500"} intersects two sorted ID lists, exactly as a search engine does. Background compaction merges small blocks into bigger ones (2 hours into 6, then days), and retention is just deleting whole old blocks. No row-by-row deletes, ever.
Compression comes from Gorilla, a 2015 Facebook paper whose encoding nearly every time-series database now borrows:
- Timestamps: store the first one, then the delta, then the delta of deltas. Scrapes arrive every 15 s, so the delta is 15 every time and the delta of delta is 0, which costs 1 bit.
- Values: XOR each float with the previous one. If the value did not change, the XOR is 0, which costs 1 bit. If it changed a little, the XOR has long runs of leading and trailing zeros, and only the meaningful bits in the middle are stored.
Facebook reported about 1.37 bytes per point on its real data, down from 16. Run this simplified encoder to see where that average comes from.
Press Run (⌘ Enter) to see what happens.Regular timestamps cost about 2 bits each, even with occasional jitter. Constant gauges and slowly growing integer counters compress to around a byte. Noisy decimal floats like 0.37 compress poorly, because decimal fractions have messy binary forms. The average lands near 1.4 bytes because most real series are idle or counters. Prometheus applies the same scheme to 120-sample chunks.
Why chunks are small, and why that helps queries
A chunk covers about 120 samples (30 minutes at a 15 s interval in Prometheus's defaults). Gorilla encoding is sequential: to read the 100th value you decode the 99 before it. Small chunks bound that cost, and each chunk records its min and max time, so a query for the last 10 minutes skips every chunk outside that range without decoding it. Larger chunks would compress slightly better but make short-range queries slower. That is a classic storage trade-off you can mention unprompted.
Deep dive 2: rollups and retention tiers
A 30-day dashboard with one point every 15 s would draw 172,800 points per series. A screen is about 1,500 pixels wide, so 99% of that work is wasted. The fix is downsampling: a background job reads finished blocks and writes rollups at coarser resolution.
| Tier | Resolution | Kept for | Used by |
|---|---|---|---|
| Raw | 15 s | 15 days | incident debugging, alerts |
| 5-minute rollups | 5 min | 1 year | weekly and monthly dashboards |
| 1-hour rollups | 1 h | 3+ years | capacity planning |
The detail interviewers probe: a rollup cannot store only an average. You cannot rebuild the maximum, the sum, or an accurate rate from an average. Store min, max, sum, and count per bucket (Thanos also keeps a counter-aware aggregate), so any later query can compute what it needs. The query engine then picks the coarsest tier that still gives enough points for the requested range.
Deep dive 3: the query path and percentiles
A query like "p99 latency of checkout, across all pods, last 6 hours" touches many series. The query engine looks up matching series in the inverted index, fans out to every ingester and storage shard that might hold them, and merges the results. Two techniques keep this fast. Query sharding splits one big query by series hash and time range and runs the pieces in parallel. A results cache keeps answers for past time ranges, which never change, so a dashboard refresh only computes the newest few minutes.
Percentiles need special care. Each pod could report its own p99, but you cannot average percentiles. If one pod's p99 is 2 s and 99 others report 100 ms, the true fleet p99 is not their average. What can be merged is a histogram: counts of requests in latency buckets (le="0.1", le="0.5", le="1", and so on). Bucket counts add up across pods, and you estimate the percentile from the summed buckets:
histogram_quantile(0.99,
sum by (le) (rate(http_request_duration_seconds_bucket{service="checkout"}[5m])))The estimate is only as precise as the bucket edges, which is why Prometheus added native histograms with exponential buckets. Check the current docs for their status in your version.
avg(p99_latency). What is wrong?Deep dive 4: alerting without alert storms
The ruler evaluates each rule on a timer, often every 30 to 60 seconds:
groups:
- name: checkout
rules:
- alert: CheckoutHighErrorRate
expr: |
sum(rate(http_requests_total{service="checkout", status=~"5.."}[5m]))
/ sum(rate(http_requests_total{service="checkout"}[5m])) > 0.02
for: 5m
labels:
severity: page
annotations:
summary: "Checkout 5xx above 2% for 5 minutes"The for: 5m clause keeps the alert pending until the condition has held for five minutes, so a single bad scrape does not wake anyone. A firing alert is not sent straight to a phone. It goes to Alertmanager, which does four jobs:
- Deduplicate. You run two rulers for availability, so every alert arrives twice. Alertmanager merges identical alerts by their labels.
- Group. When a database dies, 300 services alert at once. Grouping by
clusterandalertnameturns 300 pages into one notification that lists them. - Inhibit. If
DatacenterDownis firing, suppress every alert from that datacenter, because they are symptoms. - Silence. Engineers mute known alerts during planned maintenance.
Order what happens between a bug shipping and the on-call phone ringing.
- Tap the steps below in the right order.
Two more ideas mark a senior answer. First, alert on symptoms, not causes: page on user-facing error rate and latency against an SLO, and leave "CPU at 90%" for dashboards. The Observability, SLIs, and SLOs lesson covers burn-rate alerts in depth. Second, who watches the watcher? If the alerting path dies, silence looks exactly like health. Run a dead man's switch: an alert that always fires (Prometheus calls the convention Watchdog), sent to an external service that pages you if it stops arriving. And keep a small, independent monitoring stack for the monitoring platform itself.
Bottlenecks, failures, and 10x scale
- Cardinality explosion. The number one outage cause. Enforce per-tenant series limits at the distributor, reject new series past the limit, and give teams a dashboard of their top series by label.
- Ingester failure. Replicate each series to 3 ingesters (or rely on the Kafka log to replay), so losing one ingester loses no data and queries dedupe the copies.
- Expensive queries. One dashboard with
{__name__=~".+"}can scan everything. Set limits on series touched and samples loaded per query, and cancel long-running ones. - Slow central store. Agents buffer to disk and retry, so a 10-minute outage becomes a 10-minute delay, not a 10-minute hole.
- 10x (100M points a second): add distributor, Kafka partition, and ingester capacity. Writes scale linearly because series are independent. Query fan-out grows, so lean harder on query sharding, the results cache, and rollups. At this scale, teams also aggregate at the edge (recording rules that drop the
podlabel before shipping) so the central store never sees most raw series.
Match each problem to the part of the design that solves it.
- time series
- A metric name plus one exact set of label values, with its sequence of (timestamp, value) samples.
- cardinality
- The number of distinct series. It grows multiplicatively with label values and is the main scaling limit.
- Gorilla encoding
- Delta-of-delta timestamps and XOR-compressed floats, about 1.37 bytes per point on Facebook's data instead of 16.
- head block
- The in-memory, WAL-protected part of a time-series store that holds the newest samples before they are flushed to an immutable block.
- downsampling
- Rewriting old data at coarser resolution (min, max, sum, count per bucket) so long-range queries stay fast and cheap.
- histogram_quantile
- Estimates a percentile from summed bucket counts, the only correct way to get a fleet-wide percentile.
- Alertmanager
- The Prometheus component that dedupes, groups, inhibits, silences, and routes firing alerts.