Build a time-series monitoring platform with alerts
System DesignModel answerLast updated
Design an observability system that ingests high-volume metrics, supports real-time dashboards and historical analysis, and evaluates alerting rules.
You need to design a monitoring platform that collects and stores time-series metrics from distributed services.
Core capabilities:
- Metric ingestion: Accept time-series data (counters, gauges, histograms) from thousands of hosts at high volume.
- Real-time queries: Power live dashboards with low-latency reads over recent time windows.
- Historical analysis: Support slower, deeper queries over months of data for trend analysis and debugging.
- Alerting: Evaluate user-defined conditions (threshold breaches, anomalous rates) and route notifications.
System properties:
- Must scale horizontally to handle write-heavy workloads and traffic surges.
- Remain available during partial component failures.
- Isolate tenants to prevent one noisy workload from affecting others.
- Handle graceful degradation under backpressure.
Describe the end-to-end architecture, data model, storage strategy, and alert evaluation mechanism. Discuss trade-offs in retention policies, query patterns, and high-cardinality scenarios.
Hints
Hint 1
Time-series data is append-only and queries focus heavily on recent intervals. How does this shape storage decisions?
Hint 2
Separating hot (recent) and cold (historical) paths lets you optimize each independently. What does each path prioritize?
Hint 3
High cardinality—when label combinations explode—is the most common scaling bottleneck. What prevents it?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Time-Series Monitoring Platform
What this question evaluates
Interviewers want to see if you understand:
- Time-series characteristics: write-dominated, append-only, with reads concentrated on recent data.
- Path separation: distinguishing real-time requirements (dashboards, alerts) from batch analytics.
- Operational failure modes: cardinality explosions and monitoring failing alongside the systems it observes.
Step 1: Scope and scale estimation
Start by clarifying ambiguities and establishing scale:
Questions to ask:
- Push-based ingestion (agents send data) or pull-based (scrape endpoints)? For containerized, ephemeral workloads, push is simpler.
- Metric resolution? Assume 10-second intervals by default, with 1-second granularity available for critical series.
- Query latency? Dashboards need results within 10 seconds; alerts should fire within 60 seconds of a condition being met.
- Retention? Keep raw samples for 15 days, minute-level rollups for 90 days, hourly rollups for 2 years.
Capacity estimate:
- 100,000 hosts, each emitting ~1,000 unique series → 100 million active series.
- At 10s intervals: 10 million samples/second.
- Each sample is 16 bytes (timestamp + value). After compression (Gorilla encoding): ~1.5 bytes/sample.
- Daily volume: ~15 MB/s × 86,400s ≈ 1.3 TB/day compressed. With replication, ~4 TB/day.
- 15 days of retention: ~60 TB of raw data.
The bottleneck is not storage bytes but series count—the in-memory index that maps labels to series IDs.
Step 2: API design
# Write endpoint (batched, compressed)
POST /api/v1/metrics
Body: { tenant_id, metrics: [{ name, labels, samples: [(timestamp, value)] }] }
# Query endpoints
GET /api/v1/query?expr=...&time=... # instant evaluation (for alerts)
GET /api/v1/query_range?expr=...&start=...&end=...&step=... # time range
# Alert rules
POST /api/v1/alert_rules
Body: { name, expression, duration: "5m", severity, notification_channels }
POST /api/v1/silences
Body: { label_matchers, start_time, end_time, creator }
Metric types:
- Counters: monotonically increasing. Queries apply
rate()to compute per-second change, handling resets. - Gauges: instantaneous values.
- Histograms: bucketed distributions. Agents send bucket counts, not precomputed percentiles—buckets aggregate across hosts, percentiles do not.
Step 3: Data model
Series identity:
series_id = hash(tenant, metric_name, sorted_labels)- Labels are key-value pairs:
{service="api", region="us-east", host="web-42"}
Storage primitives:
- Sample:
(series_id, timestamp, float64_value) - Chunk: ~2 hours of samples for one series, compressed using delta-of-delta timestamps and XOR floating-point encoding (Gorilla algorithm). Immutable once sealed.
- Inverted index: maps
(tenant, label_key=label_value)→ list of matching series IDs. Query{service="api", env="prod"}means intersecting two posting lists. Cardinality explosions destroy this index.
Alert state:
- Stored in a relational database (Postgres), keyed by tenant and rule ID.
- Each alert instance transitions:
inactive → pending → firing → resolved.
Step 4: Architecture overview
[Hosts] → local agent (pre-aggregate, buffer, batch)
↓
Ingestion API (auth, tenant limits, validation)
↓
Kafka (partitioned by series_id, retain ~12h)
↙ ↓ ↘
Ingesters Rollup Archive
(hot path) (stream) (batch)
↓ ↓ ↓
in-memory 1m/1h Parquet
+ WAL rollups (S3)
↓ ↓
S3 blocks S3 blocks
[Query layer]
Query frontend (split, cache, route)
├─ recent data: ingesters + block store
└─ historical: rollup store / analytical engine (Trino)
[Alerting]
Rule evaluator (sharded) → query layer → alert state DB
↓
Alertmanager (dedupe, group, route) → Slack/PagerDuty/email
Step 5: Component deep-dives
Ingestion and backpressure handling
Agents:
- Pre-aggregate metrics locally (e.g., sum counters across threads before sending).
- Batch writes into 1–10 second windows and compress payloads.
- Maintain a bounded on-disk buffer for retries. On 429/503 responses, apply exponential backoff with jitter.
- When the buffer is full, drop low-priority metrics first. Never block the application.
Ingestion API:
- Stateless, horizontally scaled.
- Enforce per-tenant quotas: max ingestion rate, total active series, labels per metric.
- Return clear errors: "Tenant exceeded series limit; top offender: metric=http_requests, label=user_id."
- Rejecting one tenant protects all others.
Kafka:
- Acts as a buffer and replay log. Partition by
hash(series_id)for deterministic routing. - Decouples ingestion from storage: ingesters, rollup jobs, and archival consumers read independently.
- Retention of ~12 hours allows replaying recent data after a deployment issue.
Ingesters:
- Consume from Kafka, write to an append-only WAL, and hold recent samples in memory.
- Commit Kafka offsets only after WAL fsync succeeds.
- On crash, a replacement ingester replays the WAL, then resumes from Kafka. Writes are idempotent because samples carry their own timestamps—duplicates are discarded.
- Accept out-of-order samples within a 1-hour window. Reject older samples or route them to cold storage only.
Storage tiers
| Tier | Data | Medium | Latency | Purpose |
|---|---|---|---|---|
| Hot (0–2h) | raw in-memory + WAL | ingester memory | <50ms | dashboards, alerts |
| Warm (≤15d) | raw compressed blocks | S3 + local cache | ~200ms | dashboards, debugging |
| Rollups (90d/2y) | 1m/1h aggregates | S3 blocks | ~500ms | long-range dashboards |
| Archive | Parquet (raw or rolled) | S3 + query engine | seconds | ad-hoc analysis, compliance |
Rollup details:
- Stream processing (Flink) computes windowed aggregates:
min,max,sum,count(not just average). - Preserving these four values lets you reconstruct correct
avg,rate, andmaxafter downsampling.
Query frontend:
- Splits long queries into sub-intervals (e.g., per day) and executes them in parallel.
- Chooses the coarsest resolution that satisfies the query's
stepparameter: a 7-day query withstep=5mcan use 1-minute rollups. - Caches results for closed time ranges (immutable data).
Lambda vs. Kappa architecture
Lambda: separate streaming (fast, approximate) and batch (slow, correct) pipelines. Hard to maintain two codebases.
Kappa: single streaming pipeline; replay the stream to fix errors.
Recommended: Kappa with archival fallback:
- Flink computes rollups as a stream.
- Raw data flows to Parquet in S3 for compliance and exploratory queries (via Trino/Spark).
- If a rollup bug ships, reprocess the Parquet archive in batch mode—no need for a second streaming pipeline.
- The analytical tier tolerates minutes of lag; dashboards and alerts do not.
Alerting
Rule evaluation:
- Rules are sharded across evaluator instances by
hash(rule_id). - Each evaluator runs queries at the rule's interval (e.g., every 30s).
- A rule fires when its condition holds for a specified duration (
for: 5m)—this reduces false positives from transient spikes. - State transitions are stored in Postgres with a lease to handle evaluator crashes.
Alert manager:
- Receives firing alerts from evaluators.
- Deduplicates alerts across replicas and groups related alerts (e.g., "disk full on 20 hosts" becomes one notification).
- Applies silences (user-defined time windows to suppress alerts).
- Routes to notification channels based on severity and labels.
High cardinality mitigation
Cardinality—unique combinations of label values—is the primary scaling threat. A label like request_id or user_id can explode to millions of series.
Prevention:
- Set per-tenant and per-metric series limits at ingestion. Reject writes that exceed the limit with an actionable error message.
- Limit label values to, e.g., 100 characters. Hash or drop excessively long values.
- Provide a cardinality dashboard showing top contributors by metric and label.
Mitigation:
- Use relabel rules to drop or hash high-cardinality labels before ingestion.
- For user-facing labels, use sampling: emit
user_idfor 1% of requests, not 100%. - Archive full-fidelity data to Parquet for forensic analysis without burdening the real-time index.
Trade-offs summary
| Decision | Chosen approach | Alternative | Reason |
|---|---|---|---|
| Ingestion model | Push via agent | Pull (scraping) | Better for ephemeral containers; no service discovery lag |
| Message bus | Kafka in middle | Direct write to storage | Decouples ingestion from storage; replay capability |
| Storage layout | Multi-tier (hot/warm/rollup/archive) | Single TSDB | Optimizes cost and latency per access pattern |
| Rollup method | Streaming (Flink) | Batch | Low latency; Kafka replay covers errors |
| Query cache | Time-range partitioned | Full-query fingerprint | Immutable ranges cache indefinitely |
Common mistakes
- Precomputing percentiles: Percentiles do not aggregate. Send histograms instead.
- Ignoring cardinality limits: One bug emitting
user_idlabels can OOM the index. - Single storage tier: Querying years of raw data at 10s resolution is prohibitively expensive.
- Synchronous writes: The ingestion path must tolerate downstream slowness without blocking agents.
- Not handling counter resets: Counters reset on process restart; use
rate()orincrease()functions that detect and correct for this.
This design balances operational simplicity, cost efficiency, and correctness for a production-grade observability platform.