Design an Enterprise Metrics Aggregation and Alerting Platform
System DesignModel answerLast updated
Design a scalable, highly available observability system that ingests 1M data points per second, supports low-latency querying across retention tiers, and executes real-time alert conditions.
Problem Overview
Design a scalable enterprise metrics collection, storage, and alerting platform tailored for a multi-tenant microservices topology. The platform must continuously ingest high-frequency telemetry from thousands of running service hosts, render dashboard visualizations, and trigger alert notifications when metrics breach defined operational parameters.
Core Requirements
Functional Scope
- Ingestion: Accept incoming raw telemetry tuples:
(timestamp, metric_name, service_id, value, labels). - Multi-Resolution Queries: Expose querying APIs for operational dashboards, seamlessly stitching together high-resolution real-time data and aggregated long-term data.
- Automated Alerting: Continuously evaluate complex rule definitions (e.g., Service latency metric exceeds 200 ms across the 95th percentile over a 5-minute sliding window) and deliver notifications.
Non-Functional & Scale Scope
- Ingestion Scale: Sustained load of 1,000,000 metric data points per second (1M events/sec), with capacity for 3x peak bursts during rolling deployments or major incidents.
- Retention Tiers:
- 1-second granularity stored for 7 days.
- 1-minute downsampled rollups stored for 1 year.
- Performance Targets: Dashboard rendering queries must complete in under 1 second. Alert generation latency (time from event occurrence to rule evaluation) must remain within 30 seconds.
- Fault Tolerance: High availability with zero single points of failure. Ingestion pipeline failure must not cause host application degradation. High-precision alerting must execute reliably even if individual ingestion worker nodes crash.
Instructions
Prepare a comprehensive architectural design covering:
- Capacity Planning: Back-of-the-envelope estimations for network bandwidth, uncompressed/compressed storage capacity, and memory footprint.
- Ingestion & Data Flow Architecture: High-level pipeline diagram detailing client-side collection, buffering, stream processing, and storage components. Contrast push vs. pull telemetry architectures.
- Data Model & Storage Engine Selection: Database paradigm choices, time-series storage index structure (e.g., TSDB head blocks, inverted index, columnar layouts), and downsampling strategies.
- Stream-based Alerting Engine: Real-time stream evaluation architecture, window management strategies (tumbling vs. sliding), state persistence, and alert deduplication/flapping management.
- System Resilience & Trade-offs: Fault isolation, backpressure handling, and consistency vs. availability trade-offs under network partition scenarios.
Hints
Hint 1
Calculate total unique time series count by estimating metric cardinality (metric name combined with set of key-value labels). Compression heavily depends on series ordering.
Hint 2
Using standard relational databases (RDBMS) for append-heavy time-series workloads leads to massive index maintenance overhead. Evaluate specialized LSM-tree or Gorilla-compressed columnar engines instead.
Hint 3
For alerting at scale, avoid periodically polling the database for thousands of rules. Evaluate rule definitions directly against incoming event streams in memory using sliding window state stores.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & Scale Estimation
Volume & Storage Math
- Ingestion Rate: $1,000,000 \text{ events/sec}$ (Peak: $3,000,000 \text{ events/sec}$).
- Daily Volume: $1,000,000 \times 86,400 \approx 86.4 \text{ billion events/day}$.
- Uncompressed Event Size:
timestamp(8 bytes) +metric_id / hash(8 bytes) +value(8 bytes) +labels(~40 bytes average overhead) $\approx 64 \text{ bytes}$.- Daily uncompressed storage: $86.4 \text{B} \times 64 \text{ bytes} \approx 5.53 \text{ TB/day}$.
- Compressed Storage (Gorilla TSDB Compression):
- Using XOR-based floating-point compression and Delta-of-Delta timestamp encoding, average footprint drops to $\approx 1.5 \text{ bytes}$ per point for values + timestamps.
- Compressed raw daily volume: $86.4 \text{B} \times 1.5 \text{ bytes} \approx 129.6 \text{ GB/day}$.
- 7-Day Raw Data Requirement: $129.6 \text{ GB} \times 7 \approx 907.2 \text{ GB}$ (with 3x replication factor $\approx 2.72 \text{ TB}$).
- 1-Year Aggregated Volume (1-minute downsampled):
- Reduction factor: 60:1 sample count.
- Aggregated daily volume: $\approx 2.16 \text{ GB/day}$.
- 365-Day Aggregated Requirement: $2.16 \text{ GB} \times 365 \approx 788.4 \text{ GB}$ (with 3x replication factor $\approx 2.36 \text{ TB}$).
Network Throughput
- Ingress Bandwidth: $1 \text{M events/sec} \times 64 \text{ bytes} \approx 64 \text{ MB/sec}$ ($512 \text{ Mbps}$).
- Network compression (e.g., Snappy or zstd over HTTP/2 or gRPC batches) reduces ingress wire traffic by $\approx 70%$, operating comfortably at $\sim 153 \text{ Mbps}$.
2. System Architecture
+----------------------------------+
| Host Node / Kubernetes Pod |
| +----------------------------+ |
| | Microservice App | |
| +-------------+--------------+ |
| | Local Export |
| v |
| +----------------------------+ |
| | Node Agent (DaemonSet) | |
| | - Ring Buffer | |
| | - Local Aggregation | |
+----------------+-----------------+
| Push Batch (gRPC + Snappy)
v
+------------------------------------+
| Edge Load Balancers (L4 / L7) |
+-----------------+------------------+
|
v
+------------------------------------+
| Ingestion Gateway Fleet |
| (Auth, Rate Limiting, Validation) |
+-----------------+------------------+
|
v
+------------------------------------+
| Distributed Event Bus (Kafka) |
| (Partition Key: Hash(SeriesID)) |
+----+-------------------+-------+---+
| | |
+----------------------+ | +-----------------------+
| | |
v v v
+--------------------------+ +--------------------------+ +--------------------------+
| Stateful TSDB Ingesters | | Downsampling Stream Proc | | Alert Evaluation Engine |
| (Short-Term 7d Raw Store)| | (Flink: 1-min Rollups) | | (Sliding Window State) |
| - In-Memory Head Block | +------------+-------------+ +------------+-------------+
| - WAL on Local NVMe | | |
| - Object Store Flush | v v
+------------+-------------+ +--------------------------+ +--------------------------+
| | Long-Term Columnar Store | | Alert Manager |
v | (ClickHouse / Object S3) | | (Dedupe, Route, Notify) |
+--------------------------+ +------------+-------------+ +--------------------------+
| Cloud Object Storage | | |
| (Parquet/TSDB Blocks) | | |
+------------+-------------+ | |
| | |
+------------------+ +--------------+ |
| | |
v v v
+----------------------+ +--------------------------+
| Unified Query Engine | | PagerDuty / Slack / Webhook
| (Dashboards/PromQL) | +--------------------------+
+----------------------+
Telemetry Transport: Hybrid Aggregation Paradigm
- Local Scraping & Remote Push: Instead of central servers directly fetching metrics from thousands of short-lived pods (which creates scrape-target churn and firewall complexities), local Node Agents (e.g., Prometheus Agent running as a Kubernetes DaemonSet) collect telemetry locally via loopback push/pull.
- Batching & Compression: Agents buffer data points locally in a memory ring buffer, batching up to $1,000$ points or $500\text{ ms}$ windows, and transmit compressed payloads over persistent gRPC connections to the Ingestion Gateway Fleet.
Central Stream Ingestion
- Kafka Cluster: The Gateway publishes validated tuples to Kafka topics.
- Partitioning Strategy: Events are partitioned by
SeriesID = Hash(metric_name + sorted(labels)). Partitioning bySeriesIDguarantees that all chronological metrics for a specific time series land on the exact same Kafka partition and downsampling worker node, eliminating cross-node state sync overhead during streaming aggregation.
3. Data Model & Storage Design
Time Series Identification
A single distinct time series is modeled as:
SeriesKey = metric_name + sorted_labels_string
SeriesID = MurmurHash3_64(SeriesKey)
Inverted Label Index:
To enable fast multi-dimensional queries (e.g., sum(rate(http_requests_total{environment="prod", service="payment"}[5m]))), maintain an inverted index mapping label keys and values to matching SeriesID sets:
Label Index Map:
"environment=prod" -> [SeriesID_1, SeriesID_4, SeriesID_99, ...]
"service=payment" -> [SeriesID_4, SeriesID_12, SeriesID_99, ...]
Storage Engine Architecture (Split-Tiered)
| Characteristic | Tier 1: Short-Term Raw (0–7 Days) | Tier 2: Long-Term Rollups (7 Days–1 Year) |
|---|---|---|
| Storage Technology | Custom TSDB Engine (Gorilla / M3 / VictoriaMetrics) | Columnar Storage (ClickHouse / Parquet on Object Store) |
| Resolution | 1 second (Raw) | 1 minute (Aggregated) |
| Write Model | Append-only in-memory Head Block + NVMe Write-Ahead Log | Batch immutable partition commits |
| Format Encoding | Delta-of-Delta (TS), Gorilla XOR (Values) | Dictionary, ZSTD block compression |
| Query Target | High-frequency dashboards, incident debugging | Long-term SLA analytics, year-over-year trends |
In-Memory Head Block Lifecycle (Tier 1)
- Active Write: Incoming data points are written to an active memory chunk (Head Block) and concurrently appended to an NVMe-backed Write-Ahead Log (WAL) for durability.
- Chunk Sealing: Every 2 hours, the memory chunk is frozen (sealed) and transformed into an immutable compressed block.
- Persist & Compact: Immutable 2-hour blocks are flushed to low-cost Cloud Object Storage (e.g., AWS S3 / Google Cloud Storage). The local disk retains an index file for fast block retrieval.
Downsampling Strategy (1-Minute Rollups)
A Apache Flink streaming pipeline consumes from Kafka, maintaining 1-minute tumbling windows per SeriesID. Because structural aggregations cannot be arbitrarily re-averaged, each rollup record persists five distinct statistical primitives:
CREATE TABLE metric_rollups_1m (
series_id UInt64,
timestamp DateTime,
val_min Float64,
val_max Float64,
val_sum Float64,
val_count UInt32,
val_sketch DistributedHistogram -- DDSketch / t-digest for arbitrary percentile calculation
) ENGINE = ReplacingMergeTree()
PARTITION BY toYYYYMM(timestamp)
ORDER BY (series_id, timestamp);
Important: Percentiles (e.g., p95 latency) cannot be computed by taking the average of pre-calculated p95 values. The downsampling engine preserves mergeable distribution sketches (such as DDSketch or T-Digest) to allow accurate global percentile queries over arbitrary dynamic time ranges.
4. Real-Time Alerting Engine
Polling a database containing millions of time series every 10 seconds causes query load spikes and unacceptable disk I/O. The alerting architecture evaluates rules in-stream directly on incoming Kafka metric payloads.
Incoming Stream Tuple -> Stream Rule Engine -> Sliding Window Buffer -> Threshold Check -> Alert Dispatch
Stream-based Rule Evaluation Strategy
- Rule Indexing: Alert rules are registered in memory. Incoming data points are filtered by matching
metric_nameandlabelsagainst active rule predicates. - Sliding Window Storage: Stream evaluation workers maintain an in-memory sliding ring buffer per rule state key (
RuleID + SeriesID).- Example: For a rule "Error Rate > 5% over 5-minute window with 10-second evaluation intervals", the buffer holds 30 discrete sub-buckets (each 10 seconds wide).
- Incoming metrics update the active sub-bucket counters (
error_count,total_count). - The global window value is computed in $\mathcal{O}(1)$ time by maintaining running totals and subtracting sub-buckets as they slide out of the window.
Alert State Machine
To avoid spamming alerts due to transient network blips, rules utilize a state machine:
[ INACTIVE ] --(Condition Breached)--> [ PENDING ] --(Breached for Duration 'For: 5m')--> [ FIRING ]
^ | |
+------------(Condition Cleared)-------+------------------(Condition Cleared)-----------+
- Inactive: Metric operates within normal parameters.
- Pending: Condition breached, but duration metric (
for: 5m) has not elapsed. - Firing: Condition persisted beyond the evaluation threshold. Event dispatched to Alert Manager.
- Hysteresis: A rule returns to
INACTIVEonly after remaining below the breach threshold for a continuous cooldown window (e.g., 2 minutes) to prevent flapping.
High-Availability Alert Processing & Deduplication
- Evaluation Redundancy: Two separate Alerting Worker clusters run identical rule workloads in parallel to handle node failover seamlessly.
- Alert Manager Deduplication: Both clusters emit alert state changes to an Alert Manager Cluster. The Alert Manager deduplicates duplicate events using a sliding deduplication window keyed by
Hash(RuleID + TargetLabels + State).
5. Scalability, Resilience, and Trade-offs
High Availability vs. Consistency
Metrics systems prioritize Availability and Partition Tolerance (AP) over strict consistency (CAP Theorem):
- Stale or Dropped Points: Under severe network partitions or ingestion backpressure, dropping < 0.01% of metric samples is acceptable; blocking host service threads is not.
- Stateless Ingestion Gateways: Gateways do not hold state. If a gateway instance fails, load balancers shift traffic to remaining instances.
- Kafka Partition Redundancy: Kafka topics run with a Replication Factor of 3 ($RF=3$) with
min.insync.replicas=2.
Cardinallity Explosion Mitigation
A primary failure mode in time-series platforms is Cardinality Explosion (e.g., a developer inadvertently attaching a unique User ID or Request UUID as a label key, creating millions of short-lived time series).
Mitigation Layer (Ingestion Gateway Guardrails):
- Label Count & Length Limits: Enforce hard bounds (max 30 labels per metric, max 256 bytes per value).
- Series Tracking Cache: Gateways maintain an in-memory Bloom filter and LRU cache of active
SeriesIDconfigurations. - Rate Limiting / Quotas: If an isolated tenant service exceeds $50,000$ unique active series per hour, the Gateway drops unindexed dynamic labels, falling back to a default aggregate label (e.g.,
overflow_cardinality=true) and firing an internal system alert.
Query Planning & Resolution Auto-Stitching
The Unified Query Engine transparently selects the optimal storage tier based on query time range:
Query Range T <= 7 Days and Step < 1m ---> Read Raw Storage (Tier 1)
Query Range T > 7 Days or Step >= 1m ---> Read 1-min Rollups (Tier 2)
If a dashboard requests a 30-day window, the query planner automatically targets 1-minute aggregate rollups, processing $43,200$ data points per series instead of $2,592,000$ raw points—reducing data scan sizes and query latencies by over 98%.