Course contents

17. Real-World System Design Lesson 17 of 20

Metrics Platform

Design a metrics platform: ingest estimates, a buffer against storage stalls, cardinality limits, a cached query path, downsampling and reliable alerting.

25 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Active series drive memory and index size; samples per second drive writes and disk.
  • A durable buffer decouples acknowledgement from storage: slowdowns cost freshness, not data.
  • Cardinality is the product of label values; one unbounded label can take the platform down, so limit it per tenant.
  • Metric queries repeat over immutable past data, so a results cache removes most read load.
  • Blocks in object storage plus downsampled tiers keep long history cheap.
  • Alerting depends on ingestion, so monitor the pipeline and keep an external dead man’s switch.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A metrics platform collects numeric time series from every host and service (CPU, request rates, latency histograms, queue depths), stores them compactly, answers queries for dashboards, and evaluates alert rules. A series is a metric name plus a unique set of labels, for example http_requests_total{service="checkout", route="/pay", code="500"}; each scrape adds one sample (timestamp, value) to every series.

This case study builds one end to end: requirements and estimates, the ingestion path, its failure under storage stalls and cardinality explosions, the query path, long-term storage, alerting, and a component failure.

Why it exists

Every other system's reliability depends on it. When checkout is slow at 03:00, metrics are how on-call finds out (an alert) and how they find where (a dashboard). That gives the platform unusual requirements: it must keep accepting writes while things around it break, it must stay cheap at very high write rates, and its alerting must notice when it is itself unhealthy.

How it works

Requirements and estimates. Example: 10,000 hosts × ~1,000 series each = 10 million active series. Scraped every 15 s, that is about 667,000 samples per second. Time-series encodings (delta-of-delta timestamps, XOR-compressed floats, as in Facebook's Gorilla paper and the Prometheus TSDB) store a sample in roughly 1–2 bytes, so a day is on the order of 667k × 86,400 × 1.5 B ≈ 86 GB and 15 days ≈ 1.3 TB, before replication. Memory scales with active series: each needs an in-memory head chunk and index entries, a few KB per series in practice, so 10M series is tens of GB across ingesters. All of these are illustrative orders of magnitude.

Ingestion. Agents (Prometheus in agent mode, the OpenTelemetry Collector, vendor agents) scrape or receive metrics and push batches using remote-write. A load balancer spreads them over stateless collectors (also called distributors) that authenticate the tenant, validate and relabel, enforce limits, and hand batches on. Writing synchronously into storage from here couples agent success to storage health. Instead, collectors append to a durable buffer, a replicated log such as Kafka or a write-ahead log on replicated ingesters, and acknowledge. Ingesters consume the buffer, keep recent data in an in-memory head (backed by a WAL), and every two hours cut an immutable block.

Cardinality. Series count is the product of label cardinalities. A label with unbounded values (user id, request id, raw URL, pod name with high churn) multiplies it. Defences sit at the collectors: per-tenant limits on active series and samples per second, per-metric series limits, and relabel rules that drop or aggregate offending labels. Rejected writes return HTTP 429 so the offender sees it. High-cardinality detail belongs in logs and traces, linked from metrics through exemplars.

Query path. Dashboards send PromQL-style range queries to a query frontend that splits long ranges into time-aligned pieces, runs them in parallel, and caches results. Past pieces are immutable once ingestion is complete for that range, so repeated dashboard refreshes hit the cache and only the newest piece or a cold query reaches the queriers. Queriers merge recent data from ingesters with older blocks from object storage.

Long-term storage. Blocks go to object storage. A compactor merges small blocks into larger ones, deduplicates replicas, applies retention, and writes downsampled copies (for example 5-minute and 1-hour resolution, storing min, max, sum and count per window). Typical tiers: raw for days to weeks, 5-minute for months, 1-hour for a year or more. A one-year query at 1-hour resolution reads about 8,760 points per series instead of ~2.1 million raw 15-second samples.

Alerting. A rule evaluator (the Prometheus ruler) runs alert expressions every 15–60 s; a condition must hold for a for: duration before it fires. Rule evaluators run as replicas, so both fire; Alertmanager deduplicates, groups related alerts, applies silences and inhibitions, and routes notifications.

When to use it

Whenever you run more than a handful of services: metrics are the cheapest signal for alerting and capacity planning because they are pre-aggregated. A self-hosted platform like this makes sense at a scale where per-series vendor pricing hurts, or where data residency rules require it; below that, a single Prometheus with a remote backend or a managed service is simpler.

When not to

  • For per-request debugging: use traces and logs. Metrics deliberately aggregate away individual requests.
  • For business analytics with arbitrary dimensions (per customer, per order): that is an OLAP or event-analytics workload with columnar storage, not a TSDB.
  • For a single team with a few hundred hosts: one Prometheus server with local storage handles millions of series; the distributed design is overhead.

Trade-offs

Choice You gain You pay
Durable buffer before storage Storage stalls cost delay, not samples Freshness lag; another system to run and monitor
Per-tenant series limits One team cannot take the platform down Legitimate growth gets rejected until limits are raised
Results cache in the query frontend Most dashboard load never reaches storage Cache invalidation for late or backfilled data
Downsampling and tiered retention Long history at low cost and fast long-range queries Detail lost permanently; rollups must keep min/max to show spikes
Push (remote-write) Central, scalable ingestion; works across networks No built-in "target is down" signal that pull scraping gives

Alternatives

  • Single Prometheus per cluster with federation or remote-write to a managed backend. Simple; limited by one machine's memory per shard.
  • Managed metrics services. No operations; cost grows with active series and samples.
  • Columnar analytics stores (ClickHouse-style) for metrics plus events in one place. Flexible queries over high cardinality; less specialised compression and PromQL support.
  • Pre-aggregation at the edge (statsd-style or OpenTelemetry views) to cut series before they leave the host.

Failure modes

  • Storage stall without a buffer: writes back up into collectors, which reject them; samples are gone for good.
  • Cardinality explosion: ingester memory and index size grow until out-of-memory crashes, which then move the series to the remaining ingesters and crash them too.
  • Backlog unnoticed: ingestion is intact but minutes behind; alert rules evaluate stale data and miss incidents.
  • Silent alerting: missing data makes rules return nothing, so nothing fires exactly when the pipeline is broken.
  • Query of death: an unbounded query (all series, one year, raw) exhausts querier memory. Limit series per query, samples per query, and range.
  • Collector or ingester failure: stateless collectors fail cheaply if clients retry; ingesters need replication (or the buffer) so their in-memory head is not lost.

In production

Run collectors stateless behind a balancer with health checks; have agents retry with exponential backoff and jitter and keep a local WAL so they can ride out outages. Replicate the buffer or ingest with a replication factor of three across zones. Enforce per-tenant limits from day one and publish them. Alert on the platform's own health: samples/s per tenant, buffer lag, ingester memory, rejected samples, rule evaluation failures. Route an always-firing watchdog alert to an external dead man's switch that pages when it stops. Prometheus, Grafana Mimir, Thanos, Cortex and VictoriaMetrics implement variations of this design.

Common misconceptions

  • "Hosts determine cost." Active series do. One label can change cost more than doubling the fleet.
  • "A queue fixes overload." It absorbs bursts and stalls; if writes exceed drain rate for good, the backlog grows until the buffer is full.
  • "No alerts means everything is fine." It can also mean no data. Alert on absence and on the pipeline.
  • "Downsampling is just averaging." Averages hide spikes; good rollups keep min, max, sum and count.

Interview angle

Start with numbers: series, samples per second, bytes per sample, retention, memory per series. Then draw ingestion with a buffer and explain what happens when storage slows down. Interviewers almost always ask about cardinality: name the cause, the limits, and where you enforce them. Cover the query path (splitting, caching), long-term storage (blocks, compaction, downsampling), multi-tenancy, and how alerting stays trustworthy when the platform itself is degraded. Mentioning freshness lag as the price of buffering shows you understand the trade-off rather than just the boxes.

Model assumptions

The simulation is a simplified model, not a benchmark. One simulated request is one remote-write batch of ~5,500 samples, so 120 batches/s stands for ~667k samples/s. Collectors have 8 workers with a 10 ms mean service time; the TSDB has 8 connections, 30 ms writes and 150 ms range reads, and its compaction is modelled as an 8× slowdown. Ingesters have 4 slots each with a 30 ms mean service time, which stands for appending to the TSDB head (about 266 batches/s for two); a TSDB slowdown behind the buffer is modelled as ingesters running 4× slower. The cardinality explosion is modelled as more write traffic (120 → 400 batches/s); index memory growth is described, not simulated. The per-tenant series limit is modelled as a token bucket of 200 batches/s on the collector balancer. The results cache answers a fixed 80% of queries. Health checks run every 500 ms; 2 failures eject, 2 successes restore. Agent retries use up to 3 attempts with exponential backoff and full jitter. Block upload, downsampling, rule evaluation and alert deduplication are scripted illustrations, not simulated. Arrivals are Poisson; service times are lognormal. Utilisation is busy-worker fraction, not CPU.

The lesson as textEvery step of the simulation, written out.
  1. 1. Requirements and the first numbers

    We are building metrics for 10,000 hosts, each exposing about 1,000 time series (CPU per core, request counts per route, latency buckets…). Agents scrape every 15 s and push the samples to us.

    That is 10 million active series and 10M ÷ 15 s ≈ 667,000 samples per second. With Gorilla-style compression a sample costs roughly 1.3–2 bytes on disk, so one day is about 667k × 86,400 × 1.5 B ≈ 86 GB, and 15 days of raw data about 1.3 TB before replication. These are illustrative estimates, not benchmarks.

    The first design is the obvious one: a balancer, two stateless collectors, and collectors writing straight into the time-series database. In the model one request is one batch of ~5,500 samples, so 120 batches/s ≈ 667k samples/s. The TSDB is about half busy and nothing fails.

    Scene: Agents send 120 batches per second through the collector load balancer to two collectors, which write directly into the TSDB. The TSDB uses about half its connections and every write succeeds.

    Key idea: Size a metrics system by active series and samples per second, not by hosts: series drive memory, samples drive writes and disk.

  2. 2. The database slows down, and samples are lost

    One second in, the TSDB starts a heavy compaction and every write takes about 8× longer.

    The collectors write synchronously, so each one holds a worker until the TSDB answers. Its 8 connections are all busy and writes queue up for a connection. The collectors’ workers sit waiting, their own queues fill up, and they start rejecting batches with 503.

    Red packets are samples that never get stored. Metrics have no second chance: a sample from 14:03 that is dropped is a permanent gap in every graph and every alert that reads it.

    Scene: The TSDB is degraded. Its connections are all busy, the collectors fill up and reject batches, and the error rate climbs.

    Key idea: If the write path is synchronous end to end, any slowdown in storage becomes data loss at the edge.

  3. 3. A durable buffer between collectors and storage

    The collectors now only append each batch to a durable queue (a Kafka-like log) and answer at once. Two ingesters consume the queue and write into the TSDB head at their own pace. Together they drain about 266 batches/s, so at 120 they are under half busy.

    One second in the TSDB slows down again, so each ingester write takes 4× longer and they can drain only ~66 batches/s. This time nothing is rejected: the backlog grows in the queue while agents keep getting fast answers. When storage recovers, the ingesters catch up.

    The cost: data in the queue is not queryable yet. Ingestion is safe, but freshness now depends on backlog.

    Scene: Collectors append to a buffer queue; two ingesters drain it into the TSDB. When the ingesters slow down, the queue backlog grows but no batch is rejected and agents still get fast answers.

    Key idea: A buffer turns a storage slowdown from lost samples into delayed samples.

  4. 4. A label explodes the series count

    A team ships a change that adds a user_id label to its request-latency histogram. Every distinct user now creates new series for every bucket. The active series count more than triples, and so does the write load: one second in, agents send 400 batches/s instead of 120.

    The ingesters can drain about 266. They run close to flat out and the backlog grows by well over a hundred batches every second. Nothing is rejected yet, but every second the data on dashboards and in alert rules gets older. In a real TSDB the head index also grows with every new series, so memory runs out long before the queue does.

    This is a cardinality explosion: the number of label combinations, not the number of hosts, is what breaks metrics systems.

    Scene: Write load jumps from 120 to 400 batches per second. Both ingesters are fully busy and the buffer backlog grows steadily; no batch is rejected yet but data freshness gets worse every second.

    Key idea: Series count is the product of label values. One unbounded label (user id, request id, URL with ids) multiplies it.

  5. 5. Limits at the edge protect everyone else

    The collectors now enforce a per-tenant limit. In real systems it is a cap on active series per tenant (and per metric), plus relabel rules that drop known-bad labels before they are stored. Writes that would create series beyond the cap are refused with HTTP 429.

    In the model a token bucket of 200 batches/s on the balancer stands in for that series limit. The excess comes back as rate-limited errors, counted and visible to the offending team, and the ingesters drop to about two-thirds busy, so the backlog stays near zero for everyone.

    The real fix is in the code that emits the metric: drop user_id from the label set (put it in logs or traces, where high cardinality is cheap).

    Scene: The collector balancer limits the tenant to 200 batches per second. About half of the 400 batches per second are rejected as rate-limited, the ingesters run at about two-thirds of capacity and the buffer stays nearly empty.

    Key idea: Cardinality limits fail the one noisy tenant loudly instead of failing the whole platform quietly.

  6. 6. Dashboards: a query frontend and a results cache

    The team has dropped the label, so writes are back to 120 batches/s; the limit stays as a guardrail.

    Now the read side. Dashboards refresh every few seconds and ask mostly the same questions ("p99 latency, last 6 h, per service"). A query frontend splits long ranges into day-aligned pieces and keeps a results cache: pieces already computed for a past time range do not change, so only the newest piece, or a cold query, goes to the TSDB.

    In the model the cache answers about 80% of queries. Only the misses, about one in five, reach the TSDB, where a range query is expensive (150 ms here).

    Scene: Dashboards query the query frontend, which checks the results cache first. About 80% of queries are cache hits; only the misses are sent to the TSDB. Writes are back at 120 batches per second.

    Key idea: Metric queries repeat and past data is immutable, so a results cache in front of the TSDB removes most of the read load.

  7. 7. Blocks, downsampling and retention tiers

    Keeping 15 days of raw samples on the ingesters’ disks is fine; keeping a year is not. Every 2 hours each ingester cuts its in-memory head into an immutable block and uploads it to object storage. A compactor merges blocks and writes downsampled copies: one point per 5 minutes and one per hour (min, max, sum, count, so averages and peaks survive).

    Retention is tiered, for example raw for 15 days, 5-minute rollups for 90 days, 1-hour rollups for 13 months (illustrative). A query over the last year reads 1-hour rollups: about 8,800 points per series instead of ~2.1 million raw samples.

    The animation is a scripted illustration: two block uploads, the compactor reading them and writing two rollups, then a long-range query reading rollups.

    Scene: Scripted: both ingesters upload a two-hour block to object storage; the compactor reads it and writes a 5-minute and a 1-hour rollup back; then the query frontend reads rollups for a long-range query.

    Key idea: Old data is read at coarse resolution, so store it at coarse resolution: tiered retention keeps long history cheap.

  8. 8. Alert rules, deduplication and watching the watcher

    Alert rules are queries evaluated on a schedule (every 15–60 s). Two rule evaluator replicas run the same rules for availability, so when a condition holds for its for: duration, both fire. Alertmanager groups and deduplicates them and sends one page.

    Alerts read the same TSDB, so they share its failure modes: if ingestion is behind or stopped, rules evaluate stale or missing data and stay silent. Defences: alert on ingestion health itself (buffer backlog, samples/s per tenant), use absent() for metrics that must exist, and keep an always-firing watchdog alert routed to an external dead man’s switch that pages when the heartbeat stops.

    The animation is a scripted illustration: two evaluation rounds per replica, two identical alerts, one page.

    Scene: Scripted: two rule evaluator replicas each query the TSDB twice; both send the same alert to Alertmanager, which deduplicates them and sends a single page to the on-call engineer.

    Key idea: Alerting is only as fresh as ingestion: monitor the pipeline itself, and have something outside it page when it goes quiet.

  9. 9. A collector crashes

    Agents now send like Prometheus remote-write does: a failed batch is retried with exponential backoff and jitter (up to 3 attempts here).

    One second in, Collector 1 crashes. The balancer keeps sending it batches until its health checks fail twice in a row (500 ms apart), then takes it out of rotation, about a second after the crash. Batches that hit the dead collector in that window are retried, and most of the retries land on Collector 2; a handful are unlucky three times and fail. After the ejection there are no more errors.

    After ejection, Collector 2 alone carries all 120 batches/s; collectors are cheap and stateless, so one has plenty of headroom. Because collectors hold no data (the buffer does), losing one loses nothing that was already acknowledged.

    Scene: Collector 1 crashes. Batches sent to it fail and are retried by the agents until the balancer’s health checks eject it about a second later; then Collector 2 handles all traffic without errors.

    Key idea: Stateless collectors plus client retries turn a crash into a short burst of retries instead of lost samples.

  10. 10. What this design chose

    Collector 1 is back. The finished design: stateless collectors behind a balancer, a durable buffer that absorbs storage slowdowns, ingesters writing the TSDB head, per-tenant series limits at the edge, a query frontend with a results cache, blocks in object storage with downsampled tiers, and replicated rule evaluators with Alertmanager deduplication.

    The trade-offs: the buffer buys durability with freshness lag; limits protect the platform by refusing someone’s data; downsampling saves storage by losing detail (a 30-second spike vanishes in a 1-hour average unless you keep max); push (remote-write) scales ingestion centrally while pull (scraping) gives free up/down detection. Everything here is also a dependency your alerting needs, so watch the pipeline from outside it.

    Scene: The full metrics platform: agents, collector balancer and two collectors, buffer queue, two ingesters, TSDB, object storage with compactor, query frontend with results cache and dashboards, and rule evaluators with Alertmanager. Everything is healthy.

    Key idea: A metrics platform trades freshness, detail and per-tenant freedom for durability, cost and stability.