Build a Multi-Tenant Time-Series Telemetry Backend
System DesignModel answerLast updated
Design a horizontally scalable telemetry backend that ingests millions of labeled data points per second, stores 30 days of history, and serves fast label-filtered range queries.
Build a Multi-Tenant Time-Series Telemetry Backend
Your organization wants an internal platform where services can report numeric measurements, such as CPU load, request totals, or latency distributions, and where engineers can chart them on dashboards. Design the backend. Alerting is explicitly out of scope.
What the platform must do
- Accept measurements made up of a metric name, a timestamp, a numeric value, and a set of key-value labels (for example
service=feed,region=us-east). - Support three kinds of metric:
- Counters: values that only go up (they may reset on restart).
- Gauges: point-in-time readings that can go up or down.
- Histograms: distributions of observed values over time, such as request latencies.
- Offer a query interface that returns trends over a chosen time window, with the ability to filter and group by labels.
Quality targets
- Very high write throughput (millions of points per second) and low query latency.
- At least 30 days of retention.
- Horizontal scalability, high availability, and isolation between many tenants (teams).
What your answer should cover
- Capacity estimates that justify your choices.
- The write and query APIs.
- The data model and your choice of storage technology (purpose-built time-series store, columnar store, key-value store, etc.), with reasoning.
- The main components: ingestion pipeline, storage layer, and query engine.
- How you would cope with high label cardinality, for example a label that holds a unique user ID.
Be ready to discuss trade-offs and what happens when components fail.
Hints
Hint 1
Start from numbers: points per second, number of active series, and bytes per point after time-series compression. Storage and memory costs follow from series count and point count respectively.
Hint 2
Think about the access pattern: writes are almost always for the current moment, reads are time-range scans filtered by labels, and old data never changes. What storage layout does that favor?
Hint 3
Separate the problem into an index (labels to series) and the sample data (series to compressed chunks). Then consider which components handle recent data versus historical data.
Hint 4
Cardinality cost grows with the number of distinct label combinations, not the number of points. Consider limits, rejection, and aggregation at the edge.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scale first
State assumptions explicitly, since they drive the design:
- Writes: about 5M points/s steady, with 3x burst headroom.
- Active series: about 50M distinct (name + label set) combinations reporting every 10 s, which gives roughly 5M points/s.
- Reads: around 10K queries/s, but each may touch millions of points. Target p99 under 1 s for 24 h windows.
- Retention: 30 days raw, with downsampled data for longer horizons.
- Tenants: hundreds of teams, each with quotas.
Storage math. With delta-of-delta timestamps and XOR-compressed floats (Gorilla style), a point costs about 1.5 bytes. 5M/s × 86,400 s is about 432B points/day, or roughly 650 GB/day. Over 30 days that is about 20 TB, or about 60 TB with 3x replication. This is affordable if older data sits on object storage.
2. APIs
Write is batched, compressed, and idempotent per (series, timestamp):
POST /v1/write
Headers: X-Tenant-ID, Content-Encoding: snappy
Body (protobuf): repeated Series { labels[], type, samples[{ts_ms, value}] }
-> 204 OK | 429 (back off and retry) | 400 (validation or cardinality limit)
Read uses an expression language so that filtering and aggregation run server-side rather than shipping raw points to clients:
GET /v1/query_range?expr=sum by (region)(rate(requests_total{service="feed"}[5m]))&start=&end=&step=60s
GET /v1/series?match={service="feed"}
GET /v1/label/{name}/values
Metric types
- Counters are stored raw.
rate()handles resets by detecting decreases. - Gauges are stored raw.
- Histograms are stored as per-bucket cumulative counters plus sum and count, or as native exponential histograms. Percentiles are computed at query time from merged buckets. Never average percentiles across hosts.
3. Data model and storage choice
A series is identified by hash(tenant, sorted labels). Storage has two parts:
- Inverted index:
(tenant, label=value) -> sorted list of series IDs. A selector with several matchers is answered by intersecting lists. - Chunks:
series ID -> compressed chunks(about 120 samples each), grouped into immutable 2-hour blocks, each with its own index.
Why a purpose-built TSDB layout over general stores
- Key-value (Cassandra, HBase): excellent writes, but label filtering needs secondary indexes that scale poorly, and points are stored less compactly.
- Columnar (ClickHouse, Druid): great for ad-hoc analytics and high-cardinality slicing, but higher per-point cost and a weaker fit for "fetch 10K series for one day".
- Time-partitioned append-only blocks: match the workload. Writes hit "now", reads are range scans, old data is immutable, so compaction, downsampling, and retention (drop whole blocks) are simple.
4. Architecture
Agents/Clients -> LB -> Distributors -> Ingesters (RF=3) -> Object storage
(auth, limits, (WAL + in-memory ^
hash ring) head, cut 2h blocks) |
Query frontend -> Queriers -> Ingesters (recent) + Store gateways -> Compactor
(split, cache) (merge, dedupe,
downsample, TTL)
- Distributors are stateless. They authenticate, enforce per-tenant rate and series limits, validate labels, and route each series to 3 ingesters via a consistent-hash ring. A write succeeds on 2 of 3 acknowledgements.
- Ingesters append to a write-ahead log and keep the recent head block in memory, so fresh queries avoid disk. Every 2 h they flush an immutable block to object storage. After a crash they replay the WAL.
- Compactor merges blocks (2h to 12h to 1d), deduplicates replicas, applies retention, and writes downsampled blocks (for example 5-minute and 1-hour resolutions).
- Query path: the frontend splits long ranges into per-day sub-queries, runs them in parallel, and caches results for completed ranges. Queriers fetch recent data from ingesters and older data from store gateways (which cache block indexes and hot chunks), merge and deduplicate, then evaluate the expression.
Push vs pull. Pull gives health signals (a failed scrape is visible) and server-controlled load, but struggles with short-lived jobs and network boundaries. Push suits batch and serverless work but can flood the server. A good compromise is a local agent that scrapes applications and pushes batches upstream.
Multi-tenancy. Prefix every key, index entry, and object path with the tenant. Apply quotas for ingest rate, active series, query concurrency, and samples scanned. Use shuffle-sharding so each tenant uses only a subset of ingesters, limiting blast radius.
5. Deep dives
High cardinality
Cost scales with series count, not points. A user_id label over 100M users yields 100M series, each with 1-4 KB of head memory overhead, huge postings lists, and chunks with too few samples to compress well.
Mitigations:
- Prevent: per-tenant and per-metric active-series limits with clear 400 errors, label-value-count caps, and denylists for known unbounded labels.
- Reduce: drop or aggregate labels at the agent or in a streaming layer (for example, aggregate away
user_idand keepservice,region). - Isolate: surface per-tenant cardinality dashboards and cost attribution so teams self-correct.
- Escape hatch: high-cardinality needs such as per-user analysis belong in a log or columnar event store, not in the metrics store.
Failure handling
- Ingester loss: replicas serve data, and the WAL restores state.
- Object store slowness: caches and the query frontend absorb it, and queries degrade to partial results with a flag rather than failing.
- Bursts: distributors return 429, and agents buffer locally with jittered exponential backoff.
Downsampling
Keep raw data for 30 days. Beyond that, store min/max/sum/count per window so averages and rates remain correct. Route queries to the coarsest resolution that satisfies the requested step.
Common mistakes
- Averaging percentiles instead of merging histogram buckets.
- Ignoring cardinality and sizing only by points per second.
- Using a general-purpose database without a label index.
- Forgetting counter reset handling in
rate(). - No per-tenant limits, letting one team degrade everyone.
Trade-offs to mention
Replication factor 3 costs storage but provides availability. Quorum writes add latency but avoid data loss. Longer in-memory heads speed recent queries but increase recovery time and RAM.