Design an Observability Metrics Pipeline at Scale
System DesignModel answerLast updated
Design a distributed system that ingests millions of tagged metric data points per second, enforces cardinality safety, tiers storage by age, and serves dashboard queries under 500 ms.
Context
A large engineering organization runs thousands of microservices and batch jobs across multiple distributed clusters. The infrastructure team needs a centralized observability platform that collects runtime metrics from every service, aggregates them into queryable time series, and powers real-time dashboards and alerting for on-call engineers.
You are asked to design this system end to end.
What to Design
Build a metrics collection and query service that covers the full lifecycle: emission from application code, transport to a central store, storage across multiple retention tiers, and query execution for dashboards.
Functional Requirements
- Metric primitives: support counters (monotonically increasing values), gauges (point-in-time readings), and histograms or timing distributions.
- Labeled emission: services attach arbitrary key-value pairs (dimensions) to every metric, allowing slice-and-dice aggregation at query time (e.g., by
service,region,status_code). - Cardinality guardrails: prevent accidental label explosions — for example, a developer who accidentally puts a UUID or a user ID in a label could create billions of unique time series and crash the store.
- Expressive queries: support rate calculations, dimension-scoped aggregations (e.g., sum by service), time-range windowing, and percentile queries (p95, p99) over histogram data.
- Tiered retention and downsampling: keep raw high-resolution data for recent windows, and progressively roll older data up to coarser resolutions for long-term trend analysis.
- Pipeline self-monitoring: detect and alert on ingestion lag, sample drops, and storage backpressure.
Non-Functional Requirements
- Durability and availability: the write path must absorb traffic bursts without dropping metrics, and must stay available even if the query layer is degraded.
- Query latency: typical operational dashboard queries should complete in under 500 ms.
- Horizontal scalability: the system must scale out as new hosts, containers, and services are added.
Scale Targets
| Parameter | Target |
|---|---|
| Peak ingestion rate | 2,000,000 data points per second |
| Active unique time series | ~10,000,000 |
| Raw resolution (10-second samples) | 7-day retention |
| 1-minute rollups | 30-day retention |
| 1-hour rollups | 1-year retention |
Areas to Address
Your answer should cover:
- Data model and ingestion path — how metrics are structured, how they travel from client code to storage (push vs. pull, local agents, message bus), and how you handle bursts.
- Cardinality detection and enforcement — where in the pipeline you detect and reject label explosions, and what data structures make that efficient at scale.
- Storage architecture — how you organize hot in-memory storage, warm immutable block storage, and cold long-term rollup tiers.
- Query execution — how queries fan out across tiers, how caching and result splitting keep p99 latency under the 500 ms target.
- Fault tolerance — how the system handles ingester crashes, consumer lag, and partial failures without losing data.
A strong answer includes capacity estimates, concrete technology choices with stated trade-offs, and an explanation of why each design decision was made.
Hints
Hint 1
Start with a back-of-envelope calculation: at 10s resolution with 10M series, how many points per second does the steady-state write rate imply? What does that mean for storage over 7 days? These numbers determine whether your bottleneck is bandwidth, IOPS, or memory — and the answer shapes every other decision.
Hint 2
Think carefully about where cardinality enforcement lives. Checking at the SDK catches mistakes early but can be bypassed. Checking at the gateway is fast but approximate. Checking at the ingester is authoritative but expensive. A layered approach using Bloom filters and HyperLogLog at the gateway plus exact counts at the ingester gives you both speed and correctness.
Hint 3
For the query path to hit 500 ms on historical range queries, you need more than fast storage — you need a query frontend that splits large time ranges into day-aligned chunks, caches aligned sub-results, and selects the coarsest resolution tier that still satisfies the query step. Without these, even a well-designed storage layer will be too slow for dashboards.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Step 1: Size the Problem First
Never skip this. Raw numbers expose where the real difficulty lies.
Steady-state write rate: 10M series sampled every 10 seconds = 1M points/s. Peak is 2M/s, so design for 2× burst headroom.
Wire volume: ~100 bytes per point uncompressed with labels → ~200 MB/s raw. With batching and zstd compression, roughly 40–60 MB/s onto the message bus.
Raw tier (7 days): 1M/s × 604,800s ≈ 6×10¹¹ points. Gorilla delta-of-delta + XOR compression yields ~1.4 bytes/point → ~0.85 TB, or ~2.5 TB at RF=3. That's modest — IOPS and index size are the harder constraints.
1-minute rollup tier (30 days): 10M series × 1,440 minutes × 30 days ≈ 4.3×10¹¹ rollup points. Each stores {sum, count, min, max} → ~8 bytes compressed → ~3.5 TB.
Hot in-memory head block: 10M series × ~1.5 KB (open chunk + index entry) → ~15 GB, sharded across ~20–30 ingester nodes.
Conclusion: storage volume is manageable. The hard problems are write fan-in, cardinality explosion in the inverted index, and query fan-out latency.
Step 2: Data Model
A time series is uniquely identified by its metric name plus a sorted, normalized set of label key-value pairs:
series_id = hash64(__name__="http_requests_total", service="checkout", region="us-east-1", ...)
A sample is (series_id, timestamp_ms, float64_value).
Metric type encoding:
- Counters: store cumulative values;
rate()and reset handling happen at query time. - Gauges: store the raw value directly.
- Histograms: store a mergeable sketch (DDSketch preferred over fixed-bucket histograms) so percentiles can be aggregated across replicas and services. Avoid client-side pre-computed quantile summaries — they cannot be meaningfully combined at query time.
Step 3: Ingestion Architecture
App / SDK
│ push (batched protobuf + snappy)
▼
Per-host Agent ──── disk-backed buffer (1 GB / 30 min) ────► Ingestion Gateway
(also scrapes /metrics auth, cardinality
from local targets) validation, routing
│
Kafka / Pulsar
(partitioned by series_id)
│
Ingesters (stateful)
in-memory head + WAL
│ flush every 2h
▼
Object Store (S3)
immutable blocks + compactor
Push vs. pull trade-off. A pull model (Prometheus-style) gives free liveness detection and server-controlled scrape rates, but requires network reachability into every pod and breaks for short-lived batch jobs. The recommended hybrid: a per-host agent scrapes local targets and accepts pushes from jobs, then pushes batched data outbound to the gateway. This preserves local service discovery and is NAT/firewall friendly.
Why a message bus in the middle. Kafka decouples write availability from storage health. It absorbs burst traffic, enables replay after an ingester crash, and isolates the query path from ingestion load. Partition by hash(series_id) so all samples for a series land on the same partition — ingesters consume whole partitions, keeping each series on one node for efficient chunking. 256 partitions at ~60 MB/s is trivial for Kafka at RF=3.
Step 4: Cardinality Control
Enforce limits at three layers, cheapest to most authoritative.
Layer 1 — SDK/agent. Reject label values matching UUID, hex-hash, or email patterns. Cap labels per metric at 15 and value length at 128 characters. Maintain a configurable denylist (user_id, trace_id, etc.). This catches 90% of accidents at the source with no network cost.
Layer 2 — Gateway (fast, approximate). For each incoming series, check a Bloom filter of known series_ids. If the series is already known, pass it through with no further cost. For novel series, increment a per-(tenant, metric_name) HyperLogLog. When the estimated distinct-series count exceeds the tenant budget (e.g., 100k per metric, 1M per tenant), reject new series with HTTP 429 and a descriptive error, while continuing to accept samples for existing series. Emit cardinality_limit_hits{tenant, metric} so violations are visible in the pipeline's own dashboards.
Layer 3 — Ingester (authoritative). Ingesters hold exact series counts per tenant and enforce hard limits. The gateway is a fast pre-filter; the ingester is the source of truth.
Also expose a /api/top_cardinality?tenant=X endpoint so teams can self-diagnose before hitting limits.
Step 5: Storage Tiers
Hot tier — ingesters. Each ingester maintains an in-memory head block: per-series Gorilla-compressed chunks (delta-of-delta timestamps, XOR float encoding) plus an inverted index mapping label=value to a postings list of series_ids. Writes are acknowledged after a WAL append; Kafka offsets are committed only after the WAL fsync. Every 2 hours the head is sealed into an immutable block and uploaded to S3. Run 3 replicas per shard by having multiple consumer groups read the same partition, or by quorum-writing.
Warm/cold tier — object storage. A background compactor continuously:
- Merges 2-hour blocks into 1-day and then 2-week blocks (reducing S3 API calls and improving query scan efficiency).
- Deduplicates samples from replicas using
(series_id, timestamp)as the key. - Downsamples to 1-minute and 1-hour resolutions. Each rollup point stores
{sum, count, min, max, last}plus a merged sketch. Storing bothsumandcountseparately is critical — storing onlyavgmakes it impossible to re-aggregate across shards correctly.
Retention is applied by deleting whole blocks once they age past the resolution's window, which is cheap and atomic.
Why not a row-oriented distributed store like Cassandra? Keying by (series_id, time_bucket) works (OpenTSDB, early M3 use this approach) and gives easy horizontal scale. Immutable columnar blocks on object storage win on cost (~10× cheaper), compression ratio, and simplicity of downsampling as an offline batch job. Both approaches are valid; choose deliberately and say which you're picking and why.
Step 6: Query Path Under 500 ms
Query frontend. Sits in front of querier nodes and does three things:
- Splits range queries into day-aligned sub-queries that can be distributed across querier shards.
- Caches sub-query results keyed by
(query_expression, step-aligned_window). Dashboard panels re-run the same query every 30 seconds, so cache hit rates above 80% are typical. - Resolution selection: routes queries to the coarsest tier that satisfies the requested step. A query with
step=1hover the past year should hit the 1-hour rollup tier, not scan raw 10-second data.
Querier fan-out. Each querier fetches from ingesters (recent data) and store-gateway nodes (historical blocks) in parallel, merges the streams, and evaluates the query expression. Per-query limits on series count and total samples prevent runaway scans.
Step 7: Fault Tolerance
- Ingester crash: WAL replay restores uncommitted head state. Kafka offset is not advanced until WAL is flushed, so samples are not lost — they are reprocessed from the bus.
- Consumer lag: monitor
kafka_consumer_lagas a first-class metric. If lag exceeds 5 minutes, page on-call; if it exceeds 30 minutes, the pipeline automatically sheds low-priority tenant traffic (configurable per tenant). - Gateway overload: the disk-backed agent buffer absorbs up to 30 minutes of local traffic, making short gateway outages invisible to emitting services.
- Self-monitoring: the metrics platform must ingest its own metrics. Use a separate, minimal "meta-monitoring" Prometheus instance that scrapes the main pipeline's endpoints so a bug in the main system doesn't silently break its own alerting.
Common Mistakes to Avoid
- Storing pre-computed quantiles in histograms instead of raw sketches — you lose the ability to aggregate across nodes.
- Skipping cardinality enforcement at the gateway — by the time a label explosion reaches ingesters, the index is already corrupted and recovery is expensive.
- Returning average from rollups — always store
sumandcountseparately so cross-shard aggregations remain correct. - No query result cache — without it, every dashboard refresh hits storage and blows through the 500 ms budget.
- Single-tier storage — keeping everything in a hot TSDB is cost-prohibitive; object storage for anything older than a few hours is the standard pattern.