Design a Time-Series Metrics Collection and Alerting Platform
System DesignModel answerLast updated
Build a system that ingests numeric measurements from distributed services, persists them efficiently, powers query dashboards, and triggers alerts.
You need to architect a platform that handles observability data from a large-scale distributed infrastructure. Machines and applications continuously generate numeric measurements—things like throughput counters, failure rates, response times, and resource utilization figures. Your platform must ingest these observations, maintain them as queryable time-indexed data, enable visualization through dashboards, and notify operators when thresholds are violated.
The scope is broad, so you should outline the full architecture at a high level, then select one or two critical subsystems to design thoroughly.
Questions to Consider
- Which component(s) should receive the most detailed treatment: ingestion, persistence, query execution, or alert delivery?
- What is the scale? How many reporting entities exist, what volume of measurements does each produce per minute, and how many unique data streams result?
- Does the architecture use a push model where sources send data, or pull where the platform scrapes endpoints?
- What retention policy applies, and should older data be downsampled or aggregated?
- What latency is acceptable for dashboard updates and alert firing? Can occasional data loss be tolerated?
- Is the system limited to numeric telemetry, or must it also handle structured logs and distributed traces?
- How are notifications delivered, and what management features (grouping, suppression, escalation) are needed?
Hints
Hint 1
Start with a clear data model: what fields identify a unique series, and how are individual observations structured?
Hint 2
Time-series workloads have distinct characteristics—mostly appends, time-range queries, and high compression potential. Storage design should exploit these patterns.
Hint 3
Alert evaluation must remain reliable even when the system is degraded or data arrives late. Consider how to detect and handle missing measurements.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Data Model and Scale Estimation
Each measurement is a tuple: (metric_name, labels, timestamp, value). For example, (http_requests_total, {service: "checkout", status: "200"}, 1672531200, 4523). A series is the unique combination of metric name and label set.
Assume 10,000 hosts, each emitting 500 series at 15-second intervals. That's 5 million active series generating ~20 million points per minute (333k/sec). At 16 bytes per point (compressed), ingestion is ~5 MB/sec raw, and daily storage is ~460 GB before compression. With time-series compression achieving 10:1, daily footprint is ~46 GB.
High-Level Architecture
Ingestion: Agents on each host scrape local service endpoints every 15 seconds and forward batches to a load-balanced ingestion tier. The ingestion layer validates, deduplicates, and writes to storage.
Storage: A distributed time-series database partitioned by time and series hash. Data is written in append-only chunks, compressed using delta-of-delta encoding and XOR compression. Retention tiers: full resolution for 7 days, 1-minute aggregates for 30 days, 1-hour aggregates for 1 year.
Query: A separate query layer reads from storage, executes aggregation functions (rate, quantile, moving average), and serves dashboard requests. Results are cached with short TTLs.
Alerting: A dedicated alert evaluator periodically runs configured rules (e.g., "error_rate > 0.05 for 5 minutes"), maintains firing state, and sends notifications via integration with paging systems.
I'll now dive deep into storage design and alert evaluation.
Deep Dive: Time-Series Storage
Write Path
Incoming points are buffered in memory in a write-ahead log (WAL) for durability. Every 2 hours, the active in-memory block is flushed to disk as an immutable chunk. Each chunk contains multiple series, indexed by label hash. Within a series, timestamps are delta-encoded (store differences rather than absolute values) and values use XOR compression since consecutive readings often differ only slightly.
Partitioning
Data is horizontally partitioned by time (2-hour blocks) and vertically by series hash (consistent hashing across nodes). This enables time-range queries to hit only relevant nodes and blocks. Each block is replicated 3x for durability.
Downsampling
A background job processes blocks older than 7 days, computing 1-minute rollups (min, max, avg, count) and discarding raw points. After 30 days, 1-hour rollups replace 1-minute data. This exponentially reduces storage while preserving trend visibility.
Cardinality Control
Unbounded label combinations (e.g., including user IDs as labels) can explode series count. The ingestion layer enforces cardinality limits per metric: reject new series once a metric exceeds 10,000 unique label sets. A separate tracking system monitors cardinality growth and alerts when thresholds approach.
Read Path
Queries specify a metric, label filters, time range, and aggregation. The query planner identifies relevant blocks and nodes, fetches chunks in parallel, decompresses them, applies filters, and aggregates results. Recent data (last 2 hours) is served from memory; older queries hit disk with the assistance of block indexes (inverted indexes mapping labels to series IDs).
Deep Dive: Alert Evaluation
Rule Definition
An alert rule specifies a query expression (e.g., rate(http_errors[5m]) / rate(http_requests[5m]) > 0.05), a duration condition (breach must persist for 5 minutes), and routing (which team receives the page).
Evaluation Loop
The alert manager runs each rule every 30 seconds. For each evaluation, it queries the storage layer for the latest data window, computes the expression, and updates the rule's state:
- Inactive: condition not met
- Pending: condition met but duration not yet exceeded
- Firing: condition met for required duration
Handling Missing Data
A common pitfall is firing false alerts when data is temporarily unavailable. To mitigate:
- Treat missing data as explicit absence, not zero. If a series is expected but absent, mark the rule as "insufficient data" rather than firing or resolving.
- Use staleness markers: if no data arrives for a series within 2× the expected scrape interval, consider it stale and exclude from evaluations rather than treating as zero.
- Require a minimum number of samples within the evaluation window to prevent spurious alerts from sparse data.
Notification and Deduplication
When a rule transitions to firing, the alert manager groups related alerts (e.g., same service, same failure mode) and sends a single notification. It tracks notification state to avoid repeated pages for the same incident. Silencing rules (e.g., during planned maintenance) suppress matching alerts without deleting them.
Failure Modes
If the alert evaluator itself fails, active alerts may stop firing. To address this:
- Run multiple evaluator replicas, each owning a subset of rules via consistent hashing. If one fails, remaining replicas take over its rules.
- Separate the evaluator from the storage layer. If storage is degraded, the evaluator can still query recent in-memory data.
- Implement a "dead man's switch" alert that fires if it stops receiving a heartbeat metric, detecting evaluator outages.
Trade-offs and Common Mistakes
Push vs. Pull: Push is simpler for ephemeral workloads (short-lived tasks that can't be scraped), but pull provides better control over cardinality and scrape timing, and makes it easier to detect down hosts (failed scrapes are observable).
Retention Cost: Keeping full-resolution data indefinitely is expensive. Downsampling strikes a balance, but loses the ability to query fine-grained historical patterns. Consider customer tier: premium users get longer retention.
Alert Fatigue: Overly sensitive rules create noise and train engineers to ignore pages. Rules should be tuned to signal actual user impact, not transient blips. Use percentile-based thresholds rather than absolute values to adapt to changing traffic.
Self-Monitoring: The metrics system must monitor itself. Export its own ingestion rate, query latency, storage usage, and alert evaluation lag. If the monitoring system fails, external "canary" checks (probing from outside) should detect the outage.
Complexity and Scale
- Write throughput: 333k points/sec sustained, peaking at 2–3× during bursts
- Storage: ~17 TB/year at full scale with compression and downsampling
- Query latency: <2s for dashboard queries over recent 1-hour windows; slower for deep historical analysis
- Alert latency: Evaluations complete within 30 seconds; notifications deliver within 1 minute of condition breach
This architecture supports a large production environment while remaining cost-effective through aggressive compression, tiered retention, and careful cardinality management.