Design a Time-Series Observability Platform
System DesignModel answerLast updated
Design a platform that ingests, stores, and queries millions of tagged metric streams per second with tiered retention, cardinality guardrails, and sub-second alerting.
Background
A large-scale application platform runs hundreds of microservices across multiple regions. Every service continuously emits telemetry: request counts, latencies, error rates, queue depths, and more. Your task is to design the centralized observability platform that collects this telemetry, stores it efficiently, and serves it to dashboards, alerting rules, and capacity-planning tools.
Functional Requirements
- Metric types: counters (values that only increase, like request totals), gauges (point-in-time readings like memory usage), and histograms / timers (distributions that let you compute p50, p95, p99).
- Labeled dimensions: Every metric can carry arbitrary key-value tags — for example,
api_latency_ms{service="checkout", region="eu-west-1", status_code="200"}. Queries must be able to filter and group by any combination of tags. - Query and alerting interface: Support aggregations (sum, rate, quantile) across any tag subset over sliding time windows (1 min, 5 min, 1 hour, etc.). Alert evaluation must complete in under one second.
- Tiered retention with downsampling:
- Raw resolution: 10-second granularity, retained for 7 days
- Medium rollup: 5-minute granularity, retained for 90 days
- Coarse rollup: 1-hour granularity, retained for 1 year
Non-Functional Requirements
- Throughput: approximately 10 million active time series, translating to roughly 1 million samples per second sustained and 3 million per second at peak.
- Query latency: dashboard queries over the last 1–6 hours under 500 ms; ad-hoc historical queries spanning 30 days under 3 seconds.
- Cardinality safety: the labeling system must not allow a runaway tag (e.g., a developer accidentally attaches a unique user ID or a UUID as a tag value) to exhaust index memory and degrade the platform.
- Resilience: ingestion spikes must not drop critical operational metrics; the system must degrade gracefully.
What to Cover
- Data model and ingestion pipeline — how metrics flow from services to storage, including push vs. pull trade-offs, client-side pre-aggregation, and buffering.
- Storage design — choice of storage engine, how time series are indexed, how data is compressed, and how immutable blocks are managed.
- Cardinality control — concrete mechanisms at each layer to detect and contain high-cardinality label explosions before they cause an outage.
- Downsampling and compaction — how rollup pipelines work and why certain aggregations (like percentiles) require special handling.
- Query path — how large queries are parallelized and how recently ingested data is served before it is flushed to durable storage.
- Failure handling — what happens when ingesters crash, when the buffer is full, or when the metrics platform itself needs to be monitored.
Hints
Hint 1
Before diving into architecture, sanity-check the numbers. 10M active series at a 10-second scrape interval is about 1M samples/sec — not 10M/sec. Stating this correction early signals strong engineering judgment. Then size the storage: at ~1.4 bytes per sample with Gorilla compression, 50 billion samples/day is roughly 70 GB/day raw, or ~210 GB/day with 3x replication. The 7-day raw tier is about…
Hint 2
Separate the index path from the data path mentally. When a sample arrives for an already-known series, it is a fast append — no label parsing, no index write. Only truly new series touch the inverted index. This distinction drives the cardinality threat: each new unique label combination burns index memory. A cardinality leak that inflates 10M series to 100M can exhaust the ~10 GB of index RAM ve…
Hint 3
Percentiles cannot be re-aggregated after the fact — this is a critical constraint for your rollup design. You cannot store a pre-computed p99 and later combine it with another p99 to get a fleet-wide p99. Store histogram bucket counts at every tier instead, so any rollup window can reconstruct accurate quantiles. Similarly, for counters, store reset-adjusted increases rather than raw cumulative v…
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify the Numbers First
"10 million time series per second" is ambiguous. At a 10-second scrape interval, 10M active series produces ~1M samples/second sustained and perhaps 3M/sec at peak. The stated 50 billion samples/day is consistent with ~580K samples/sec average. Design for 1M sustained, 3M peak.
Storage sizing with Gorilla compression (~1.4 bytes/sample):
- 50B samples/day × 1.4 B = ~70 GB/day raw
- With 3× replication: ~210 GB/day
- 7-day raw tier: ~1.5 TB — manageable
Index sizing: 10M series at ~1 KB each (label strings + postings entries) = ~10 GB of RAM across the cluster. That is fine. A cardinality leak that grows this to 100M series is not fine. This risk anchors the entire design.
Core trade-off: availability over consistency. A missing data point is tolerable. A stalled ingest pipeline or dead alert evaluator is not.
2. Data Model
series_id = hash64(metric_name + sorted canonical label set)
sample = (series_id, timestamp_ms int64, value float64)
histogram = (series_id, timestamp_ms, sparse_bucket_counts[], sum, count)
Keep the index path (label set → series_id, runs once per new series) separate from the data path (series_id → append value, runs on every sample). Hot-path writes never touch labels.
3. Ingestion Pipeline
Services → Client Lib (pre-agg) → Node Collector Agent
→ Kafka (partitioned by series_id)
→ Ingesters (in-memory head + WAL, RF=3)
→ Object Store (S3/GCS)
Push over pull. At this scale, short-lived pods and batch jobs make pull-based scrape discovery operationally painful. A local agent scrapes service endpoints and pushes upstream, preserving the "is this target alive?" signal without the discovery complexity.
Client-side pre-aggregation is the highest-leverage cost reduction:
- Counters flush cumulative values every 10 seconds. Cumulative (rather than delta) values survive packet loss without corrupting rates.
- Histograms send mergeable bucket counts, never individual observations.
- Collectors can apply label-dropping rules — for example, strip
pod_idand emit onlyservice-level series — cutting write volume by 10–100×.
Kafka as the ingestion buffer:
- Absorbs ingest spikes, providing backpressure without dropping data.
- Enables replay if an ingester crashes.
- Run two topics:
critical(SLO and alerting inputs, with reserved partition capacity) andbulk(everything else). - Partition by
hash(series_id)so all samples for a series land on one ingester shard, keeping chunk writes sequential.
4. Storage Architecture
Head Block (In Memory, ~2 hours)
Each series maintains an open compressed chunk of ~120 samples using Gorilla encoding:
- Timestamps: delta-of-delta encoding. With regular 10-second scrapes the second-order delta is almost always zero, costing 1 bit.
- Values: XOR with the previous value; encode leading/trailing zero run lengths. Repeated values cost 1 bit.
Result: ~1.37 bytes/sample vs. 16 bytes raw.
A write-ahead log (WAL) on local SSD makes the head block recoverable after a crash without waiting for Kafka replay.
Inverted Index
- Each
label=valuepair maps to a sorted postings list of series_ids. Large lists are stored as Roaring bitmaps. - A query selector like
{service="checkout", status_code="500"}resolves to a bitmap intersection — fast even over millions of series. - Label values are stored in a sorted dictionary (as an FST) to support regex matching without full scans.
- A symbol table deduplicates repeated string values across series.
Persisted Blocks
Every 2 hours the head block is sealed into an immutable block (chunks + index + tombstones) and uploaded to object storage. A background compactor merges blocks: 2h → 12h → 24h → 7d. Retention is enforced by deleting whole blocks — no row-level deletes needed. This is analogous to LSM compaction but time-partitioned.
Why not Cassandra or a columnar store? You could store chunk blobs as wide rows. But the inverted bitmap index and per-series Gorilla compression are what make the 500 ms dashboard latency achievable. A purpose-built TSDB (Prometheus/Mimir/Thanos lineage) wins here.
5. Cardinality Management
Defend in layers, cheapest first:
- Client library: allowlists of permitted label names per metric; CI linting that rejects labels whose values match UUID, numeric-ID, or IP-address patterns.
- Collector agent: per-metric HyperLogLog sketches tracking distinct label-value cardinality over a sliding window. If a metric's cardinality grows more than 10× its baseline or exceeds a tenant quota, the offending label value is rewritten to
__overflow__or dropped before the data reaches Kafka. - Ingester: hard per-tenant and per-metric limits on active series count. A new series beyond the limit is rejected (with a logged error and an incremented overflow counter), but existing series continue ingesting. Dashboards and alerts survive; only new series are blocked.
- Cardinality explorer UI: a tool showing top-N labels by distinct value count per metric, with automated alerts to the owning team when a metric crosses a threshold.
The key principle: protect existing series at all costs. Reject new ones rather than degrading the whole tenant.
6. Downsampling and Rollups
The compactor emits rollup blocks for each sealed raw block. For every series it stores: min, max, sum, count at 5-minute and 1-hour granularities.
Critical rules:
- Never store pre-computed percentiles. A p99 cannot be combined with another p99 to produce a correct aggregate p99. Store histogram bucket counts at every tier so any rollup can reconstruct accurate quantiles.
- Counters: store reset-adjusted increases so
rate()remains correct across rollup boundaries even if the underlying process restarted. - Gauges:
avgis derived assum / countat query time.
| Tier | Granularity | Retention |
|---|---|---|
| Raw | 10 s | 7 days |
| Rollup | 5 min | 90 days |
| Rollup | 1 h | 1 year |
The query planner selects the coarsest tier that satisfies the requested step size, transparently to the user.
7. Query Path
- The query frontend splits requests into time-aligned sub-ranges (e.g., day-aligned chunks), caches results for immutable historical ranges, and fans out sub-queries in parallel.
- Shard-aware pushdown: each querier computes partial aggregates over its assigned series shard; the frontend merges them. A
sum by (region)never requires moving raw samples. - Recent data (last 2 hours) is served directly from ingester head blocks before it has been flushed to object storage — store-gateways handle historical data.
- Alert evaluators query ingesters directly on a short polling interval (~15 seconds) to achieve sub-second effective evaluation latency.
8. Failure Modes and Self-Observability
- Ingester crash: WAL + Kafka offset replay reconstructs the head block. Replication factor 3 means two surviving replicas still serve reads immediately.
- Ingest spike: Kafka absorbs the burst. If Kafka consumer lag grows, the
criticaltopic continues draining at full speed;bulklags but is not dropped. - Object store outage: ingesters continue writing WAL and Kafka buffers. Queries degrade to in-memory data only. Backfill runs when the store recovers.
- The metrics system monitoring itself: emit a separate, lightweight heartbeat metric using a stripped-down agent with a dedicated Kafka topic and isolated ingester capacity. Never route self-observability through the main pipeline it is monitoring.
Common Mistakes to Avoid
- Treating "10M series" as "10M samples/sec" — off by 10× on throughput calculations.
- Storing pre-aggregated percentiles in rollups — makes cross-shard or cross-time aggregation mathematically incorrect.
- Rejecting all writes when a cardinality limit is hit — the right behavior is to reject only new series while protecting existing ones.
- Forgetting that the query frontend must merge data from both live ingesters and historical store-gateways for queries spanning the flush boundary.