Design a High-Throughput Telemetry Collection Platform
System DesignModel answerLast updated
Build a system to aggregate and store operational telemetry from a large distributed fleet, supporting real-time writes and historical analytics.
Problem
You're building a centralized observability platform for a cloud environment running tens of thousands of services across many data centers. The system must continuously collect operational telemetry—CPU utilization, memory pressure, API response times, failure rates—from all running processes and infrastructure components, then make this data available for real-time monitoring and historical analysis.
Design this telemetry aggregation and query platform with an emphasis on the collection pipeline, write throughput, storage strategy, and keeping heavy analytical queries from interfering with data ingestion.
What You Need to Support
Core Capabilities
- Data Collection: Accept timestamped numeric observations tagged with arbitrary key-value metadata (e.g.,
hostname,service_name,region). - Client Integration: Provide a lightweight reporting mechanism that applications and operating systems can use without blocking or consuming significant resources.
- Analytics: Enable time-range queries with filtering by tags, statistical aggregations (
mean,max,95th percentile), and grouping. - Lifecycle Management: Keep fine-grained raw observations for short-term debugging, then transition to summarized views for capacity planning and trend analysis over months or years.
Operational Targets
- Reliability: The ingestion path should remain available through most failures. Data loss should be rare and observable when it occurs.
- Write Optimization: The architecture should favor write throughput. Read-heavy analytics workloads must not starve the write pipeline.
- Growth: Adding more hosts or services should scale linearly without architectural changes.
Scale Context
- Deployment Size: 100,000 compute instances (physical servers, VMs, containers).
- Data Rate: Each instance emits roughly 50 distinct measurements every 10 seconds, yielding approximately 500,000 observations per second on average, with peaks reaching 1,000,000 per second.
- Storage Tiers: Full-resolution data retained for 7 days; minute-level summaries for 30 days; hourly summaries for 1 year.
- Query Performance: Dashboard queries covering the past 6 hours should complete in under 500ms at the 95th percentile.
What to Cover
Your design should address:
- Client Strategy: How instances report data—push versus pull, local buffering, dealing with backpressure, and resource isolation.
- Ingestion Pipeline: Load distribution, durable buffering, and storage write path.
- Storage Design: How to organize telemetry for efficient writes and queries; sharding and partitioning strategies.
- Isolation: Architectural techniques to prevent query load from degrading ingestion throughput.
Hints
Hint 1
Consider how to batch and compress observations on the client to reduce network overhead and request volume.
Hint 2
A durable message queue between ingestion frontends and storage can decouple reliability concerns and allow independent scaling.
Hint 3
Time-series databases often partition data both by metric identity and by time window; each choice has different trade-offs for write distribution and query fan-out.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
1. Scoping and Capacity Planning
Begin by confirming the data model and working through the numbers:
Data Model
Each observation is a tuple: (metric_name, tags_map, timestamp, value). Tags are arbitrary key-value pairs like {service: "api", region: "us-west"}. The unique combination of metric name and sorted tags defines a series.
Estimates
- Series count: 100k hosts × 50 metrics = 5 million active series. With container churn and tag explosion, plan for 20 million.
- Write throughput: 500k observations/sec average, 1M/sec peak.
- Network bandwidth: Uncompressed observations are ~100 bytes each, so 1M/sec = 100 MB/sec. With batching and compression (zstd), this drops to ~25 MB/sec.
- Storage for 7-day raw data: 500k points/sec × 86,400 sec/day × 7 ≈ 300 billion points. Time-series compression (delta encoding for timestamps, XOR for floats) achieves ~1.5–2 bytes per point, giving ~600 GB. With replication factor 3, that's ~1.8 TB.
- Minute-level rollups, 30 days: 5M series × 1,440 min/day × 30 ≈ 220 billion aggregate rows (min, max, sum, count per minute). Approximately 4 TB.
- Hourly rollups, 1 year: 5M series × 8,760 hours ≈ 44 billion rows, plus percentile sketches, ~2–3 TB.
Key takeaway: The working set for recent data (last few hours) fits in memory across a modest cluster. Long-term data belongs in object storage. The real scaling challenge is series cardinality, not byte volume.
2. High-Level Architecture
[Agent on host] --batch--> [Load Balancer]
|
v
[Ingestion Gateways]
(stateless, autoscaled)
|
v
[Message Queue: partitioned by series hash]
/ \
/ \
[Storage Writers] [Rollup Workers]
(replicated, sharded) |
| |
v v
[Object Storage: raw blocks + aggregated blocks]
^
|
[Monitoring UI] --> [Query Layer] --> recent data from writers + historical from object storage
3. Client Agent Design
Push Model
Use push rather than pull. With 100k dynamic endpoints and short-lived containers, centralized scraping becomes a service-discovery and network-traversal nightmare. Push allows the client to batch and compress efficiently.
Agent Implementation
- Local aggregation: Applications write observations to the agent over a local Unix socket or shared memory. The agent aggregates counter increments and histogram buckets within each 10-second interval. Application threads never block on remote I/O.
- Batching: The agent sends one compressed request per interval containing all observations, reducing per-request overhead by ~1000×.
- Buffering: A bounded in-memory ring buffer (32–64 MB) with optional disk overflow (a few hundred MB). When full, drop the oldest data and increment a
telemetry_droppedcounter so loss is observable. - Resource isolation: Run the agent in a separate cgroup with CPU and memory limits. It must not compete with the primary workload.
- Retries: Exponential backoff with jitter. Respect
429 Retry-Afterresponses.
Why not pull? Pull is useful for liveness ("is the endpoint reachable?"), but for high-volume data collection, push reduces operational complexity and allows agents to control their own send rate.
4. Ingestion Pipeline
Gateways
Stateless HTTP frontends behind a layer-4 load balancer across multiple availability zones. They:
- Authenticate and authorize each request.
- Enforce per-tenant rate limits and cardinality quotas (reject writes that would create unbounded new series).
- Forward accepted batches to the message queue.
Message Queue (Kafka)
Kafka acts as the durability boundary and decouples ingestion from storage writes.
- Partitioning: Partition by
hash(series_key)so all observations for one series go to the same partition, preserving order and enabling efficient compression. - Replication: Use
acks=allwith replication factor 3 andmin.insync.replicas=2for durability. - Retention: Keep 24 hours in Kafka to allow downstream consumers to rebuild or replay.
- Sizing: 1M points/sec across 256 partitions is ~4k points/sec per partition, leaving 4× headroom.
Once Kafka acknowledges the write, the agent can discard the batch. Kafka provides at-least-once delivery; the storage layer deduplicates by (series, timestamp).
5. Storage Engine
Write Path
Storage nodes consume assigned Kafka partitions. Each write goes to:
- Write-ahead log (WAL) for crash recovery.
- In-memory head block for active data.
Every 2 hours, the head block is flushed to an immutable columnar block and uploaded to object storage. Blocks are self-contained with their own inverted index (tag=value → list of series IDs).
Compression
Use delta-of-delta encoding for timestamps and XOR encoding for float values (Gorilla compression), achieving ~1.5 bytes per point.
Compaction
Background workers merge small blocks into larger ones (2h → 12h → daily). Compaction improves query performance and reduces metadata overhead.
Retention
Delete entire blocks older than the retention policy. No per-row tombstones needed.
Replication
Each Kafka partition is consumed by 3 storage replicas, so queries over recent data remain available during single-node failures.
6. Sharding Strategy
Hash by Series Key
Partition by hash(metric_name + sorted(tags)) using consistent hashing. This distributes writes evenly across nodes and keeps all observations for a series together, improving compression.
Alternative: Time Sharding
Sharding by time window sends all current writes to a single "hot" node, creating a bottleneck. Rejected.
Trade-off: Query Fan-out
A query like http_latency{service="auth"} must scatter-gather across all shards. Mitigation strategies:
- Use fast per-shard inverted indexes to prune irrelevant series quickly.
- Route long-range queries to pre-aggregated rollups instead of raw data.
7. Read/Write Isolation
Separation Mechanisms
- Kafka as buffer: Query load cannot block writes. If storage nodes are overwhelmed by queries, Kafka simply accumulates lag, and writes continue to be acknowledged.
- Separate query tier: Query nodes are distinct processes that read from storage nodes and object storage. They autoscale independently.
- Query frontend:
- Splits large time-range queries into smaller sub-queries and caches immutable results.
- Enforces per-user concurrency limits, series cardinality caps, and query timeouts.
- Admission control on storage nodes: Reserve CPU quota for the write path. Throttle or queue read requests when resources are scarce.
Resolution-Based Routing
- Queries over the last 6 hours use raw data from storage nodes.
- Queries spanning days or weeks use minute-level or hourly rollups from object storage.
- This keeps query latency under 500ms by reducing the data scanned.
8. Rollups and Downsampling
Background workers consume from Kafka and produce pre-aggregated data:
- 1-minute rollups: Store min, max, sum, count, and a mergeable percentile sketch (e.g., DDSketch) for each series per minute.
- 1-hour rollups: Further aggregate minute rollups into hourly summaries.
Why sketches for percentiles? You cannot average percentiles. Use mergeable data structures like DDSketch or t-digest so p95 can be computed correctly across hosts and time ranges.
9. API Design
Write Endpoint (Agent → Gateway)
POST /v1/ingest
Content-Type: application/x-protobuf
Content-Encoding: zstd
{ series: [{ name: "cpu_usage", tags: {host: "web01"}, samples: [{ts: 1700000000, val: 45.2}] }] }
→ 202 Accepted | 429 Too Many Requests | 503 Service Unavailable
Query Endpoint (UI → Query Layer)
GET /v1/query?metric=http_latency&filter=service:auth&agg=p95&group_by=region&start=1700000000&end=1700010000&step=60
→ JSON with timestamp-value pairs per group
10. Common Pitfalls
- Unbounded cardinality: User-generated tag values (e.g.,
user_id) create millions of series. Enforce cardinality limits and provide tooling to detect high-cardinality sources. - Late data: Accept writes up to 1 hour in the past. Reject older data to avoid rewriting immutable blocks.
- Query of death: A query touching millions of series can exhaust memory. Enforce max-series limits and fail fast.
- Hot shards: Poorly distributed hash functions or unbalanced tag distributions create hot nodes. Use high-quality hashing and monitor shard load.
11. Complexity Analysis
- Write latency: O(1) per observation once batched. Gateway → Kafka → storage is pipelined.
- Query latency: O(S × T / B) where S = matching series, T = time range, B = block size. Inverted indexes reduce S; block skipping reduces T.
- Storage: O(N × D) where N = series count, D = retention days. Compression and rollups reduce the constant factor by 10–100×.
This architecture handles the 1M points/sec peak, keeps writes isolated from queries, and scales horizontally by adding storage nodes and Kafka partitions.