Build a Multi-Tenant Time-Series Telemetry Backend
System DesignModel answerLast updated
Design a telemetry backend that ingests about 1M samples per second from many services, answers aggregate queries fast, runs alerts, and keeps data cheaply for months with tenant isolation.
Scenario
Your company runs many services across several data centers. Each service emits numeric telemetry: counters, gauges and histograms, each labeled with key/value tags. Design the backend that stores this telemetry and serves it to dashboards and alert rules. Several internal teams (tenants) share the platform.
Requirements
Functional
- Accept tagged measurements, for example
cpu_usage{host="web-01", env="prod"}. - Offer a query interface for aggregations such as sum, average and 99th percentile over a time window.
- Support simple alert rules that fire when a query result crosses a threshold for some duration.
Non-functional
- Writes must stay highly available.
- Sustained ingest of about 1 million samples per second.
- Data older than 30 days must be stored in a space-efficient way.
- Tenants must be isolated: one tenant's heavy load or query must not degrade others.
What to cover
- API design: the write payload and the query interface.
- Data model: how tagged series are identified, indexed and laid out on disk.
- Storage strategy: choice of storage engine, retention and downsampling.
- Architecture: the path from a measurement leaving a service to a query result or an alert.
Example interaction
Write:
POST /v1/write with body {"name": "http_requests", "tags": {"service": "auth"}, "value": 12, "ts": 1672531200}
Read:
GET /v1/query?q=sum(http_requests{service='auth'})&start=1h&end=now
Discussion points to address
- How do you cope with tags that have huge numbers of distinct values (e.g.
user_id)? - How does the system absorb traffic spikes?
- During a network partition, how do you trade consistency against availability?
Hints
Hint 1
Start with numbers: 1M samples/sec at a 10s reporting interval implies roughly 10M active series. Estimate bytes per sample before and after time-series compression to see which part (storage, index, query fan-out) is actually the bottleneck.
Hint 2
Treat each unique combination of name plus tags as one series, and use an inverted index (tag pair to sorted list of series IDs) so a selector becomes an intersection of lists. Think about what that implies when a tag has unbounded values.
Hint 3
For long retention, keep rollups that can be re-aggregated correctly (sum, count, min, max, or a mergeable sketch) rather than only averages or precomputed percentiles. Put a durable log in front of ingestion to absorb bursts.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
Metrics data is append-only, time-ordered and very compressible. That means raw throughput is not the hard part. The hard parts are series cardinality (index size and query fan-out) and tenant isolation. Say this early and design around it.
1. Requirements and scale
Assumptions to confirm: 10s reporting interval, up to 1h of late data accepted, dashboard queries over 24h with p99 latency under 1s, 30 days raw retention, then about 13 months of rollups.
- 1M samples/sec at 10s intervals means about 10M active series.
- About 86B samples/day. Raw, at 16 B each, that is about 1.4 TB/day.
- With delta-of-delta timestamps and XOR-compressed floats (Gorilla style), about 1.3-2 B/sample, so roughly 130-170 GB/day. With 3x replication on hot tiers, about 0.5 TB/day.
- 30 days is around 5 TB compressed, which is small for object storage.
- The index at about 1 KB per series is roughly 10 GB, which fits in memory across ingesters.
Conclusion: storage is cheap; the index and query fan-out need the care.
2. API
Write. Batch by default (protobuf plus snappy; JSON for low volume), authenticated, tenant in a header.
POST /v1/write
{ "series": [
{"name":"http_requests","type":"counter","tags":{"service":"auth"},
"samples":[[1672531200,12],[1672531210,15]]},
{"name":"latency_seconds","type":"histogram","tags":{"service":"auth"},
"buckets":{"0.1":40,"0.5":52,"+Inf":55},"sum":9.3,"count":55,"ts":1672531200}
]}
-> 204 | 400 validation | 429 limit hit (Retry-After)
Writes are idempotent on (series, timestamp), so retries with jittered backoff are safe.
Query. A PromQL-like language is composable and familiar: query_range with start, end, step; a series endpoint for metadata and autocomplete; a rules endpoint for alerts (expr, for, labels, receivers). State two semantics explicitly: counters are read through rate() (handles resets), and percentiles come from histograms, never from averaging percentiles.
3. Data model
- Series ID = hash(tenant, name, sorted tags). Each distinct tag combination is its own series.
- Inverted index per tenant and per time block (e.g. 2h):
tag=value -> sorted list of series IDs. A selector is an intersection of lists; regex matchers scan the tag's value dictionary first. Per-block indexes mean churned series age out instead of growing the index forever. - Chunks: about 2h or 120 samples per series, with delta-of-delta timestamps (regular intervals cost about a bit) and XOR float encoding.
- Histograms: either one series per bucket with an
letag, or native exponential histograms / sketches (e.g. DDSketch). Mergeable sketches make cross-host percentiles and rollups correct.
4. Storage strategy
Avoid a general RDBMS; use an LSM-like time-series engine (Prometheus TSDB, Mimir or M3 style).
- Head: ingesters keep recent samples in memory, with a WAL on local SSD for crash recovery.
- Blocks: every 2h, cut an immutable block (index plus chunks) and upload to object storage. This decouples compute from storage and is cheap and durable.
- Compactor: merges blocks into larger ones, deduplicates replicas, enforces retention.
- Downsampling: raw 30 days, 1-minute for 90 days, 1-hour for 13 months. Each rollup point stores min, max, sum, count (plus merged sketch). Never store only an average; sum/count re-aggregates correctly, an average of averages does not.
- Read path: a query frontend splits long ranges by day, caches results and picks the coarsest resolution that satisfies
step. Queriers fan out to ingesters (last ~2h) and store gateways (object-storage blocks with cached indexes).
5. Architecture
Agents/SDKs (batching, local pre-aggregation)
-> Load balancer -> Distributors (auth, validation, per-tenant rate and series limits)
-> Kafka (partition by hash(tenant, series)) # burst buffer + replay
-> Ingesters (RF=3, WAL + head) -> Object storage -> Compactor
Query frontend (split, cache, per-tenant fair queue) -> Queriers -> Ingesters + Store gateways
Ruler (evaluates rules each 15-60s) -> Alert manager (dedup, group, silence, route)
Partitioning by series keeps a series' samples ordered on one ingester, so chunk appends are sequential. The ruler is sharded by tenant or rule group; for: 5m suppresses flapping; the alert manager deduplicates notifications from replicas.
Isolation: per-tenant quotas (write rate, active series, query concurrency, max samples per query), shuffle-sharding tenants onto subsets of ingesters and queriers, and fair queuing at the frontend.
6. Deep dives
High cardinality. Every new tag value makes a new series, costing index memory and fan-out. Defenses:
- Per-tenant and per-metric active-series limits, returning 429 with a clear message.
- Drop or relabel rules at the distributor.
- Pre-aggregate away the tag (
sum without (user_id)) in the agent or a streaming aggregator. - Send per-user analysis to logs or traces; exemplars can link a metric point to a trace ID without creating a series.
Bursts. Clients batch and back off on 429. Distributors are stateless and autoscale. Kafka absorbs spikes for minutes to hours so ingesters consume at a steady pace; lag-based autoscaling handles sustained growth.
Consistency vs availability. Choose AP for writes: replicate each series to 3 ingesters and ack on a quorum of 2. During a partition, keep accepting writes on reachable replicas and deduplicate at query time or compaction (safe because writes are idempotent). Reads may be briefly stale or partial; mark partial results explicitly. Alerting should prefer availability too, but treat "no data" as its own state rather than silently as OK.
Trade-offs and common mistakes
- Skipping the capacity estimate and over-engineering storage while ignoring the index.
- Storing percentiles or averages in rollups, which makes later aggregation wrong.
- Letting unbounded tags through with no limits, which is the usual cause of outages.
- Single-sample writes and no buffering layer.
- One shared query pool, so a single expensive query hurts every tenant.
- Pull vs push is a valid debate; push with agent-side batching fits a multi-tenant shared platform, while pull simplifies liveness detection.