Metrics Platform
1. Executive Summary
A metrics platform ingests, stores, queries, and alerts on time-series numerical measurements (counters, gauges, histograms) from applications and infrastructure at millions of samples per second. Principal-level design covers data model (labels and cardinality), write path (remote write, aggregation), read path (PromQL-style queries), retention tiering, high availability, and multi-tenancy isolation.
This chapter designs a Prometheus/Datadog-class system handling 50M+ active series and 10M+ samples/sec ingest with query p99 under 2 s for dashboard ranges. Cardinality control, downsampling, and explicit behavior during label explosion incidents are mandatory interview topics.
2. Why This Topic Matters
Metrics power SLOs, alerting, capacity planning, and incident response. Architects must explain:
- Pull vs push ingestion models.
- Cardinality explosion and why
user_idlabels destroy systems. - Histogram vs summary for percentiles.
- Retention and compaction for cost.
- Federation and remote write for global views.
Bad metrics design causes on-call fatigue, storage bankruptcy, and blind spots during outages. Review Observability Fundamentals and SLO/SLI/Error Budgets.
3. Problems Being Solved
| Problem | Solution |
|---|---|
| High-volume ingest | Sharded TSDB; batching |
| Fast range queries | Block storage; inverted index |
| Alerting | Rule evaluator on stream |
| Cardinality control | Limits; aggregation; dropping labels |
| Long retention | Downsampling; cold storage |
| Multi-tenant SaaS | Per-tenant isolation and quotas |
| Service discovery | Pull targets from K8s/consul |
| Global view | Federation hierarchy |
4. Assumptions and System Model
Functional:
- Ingest counters, gauges, histograms with labels.
- Query: instant and range; aggregations (rate, sum, histogram_quantile).
- Alert rules with notification routing.
- Dashboard integration (Grafana-compatible).
- Exemplars linking metrics to traces (optional).
Non-functional:
- Ingest 10M samples/sec.
- Active series < 50M (with cardinality governance).
- Query p99 < 2 s for 24h range, 15s step.
- Ingest availability 99.9%; query 99.95%.
- Retention: 15d raw; 1y downsampled.
| Assumption | Implication |
|---|---|
| Metrics are numeric time-series | Not logs or traces |
| Label cardinality bounded | Enforce limits |
| Recent data queried most | Hot/warm tiering |
| Eventually consistent ingest | Brief query gaps OK |
| Pull preferred for K8s | Service discovery native |
5. Essential Terminology
| Term | Definition |
|---|---|
| Time series | Metric name + label set + timestamped values |
| Cardinality | Count of unique label combinations |
| Counter | Monotonically increasing value |
| Gauge | Point-in-time value |
| Histogram | Bucketed observations for percentiles |
| PromQL | Query language for metrics |
| Scrape | Pull metrics from /metrics endpoint |
| Remote write | Push ingest to central TSDB |
| TSDB block | Immutable compressed time chunk |
| Head block | In-memory recent samples |
| Recording rule | Precomputed query saved as metric |
| Exemplar | trace_id attached to histogram sample |
6. Core Mechanism
6.1 Architecture
Figure 1: Scrape and remote-write ingest into sharded TSDB; query frontend serves PromQL.
6.2 APIs
GET /metrics (Prometheus exposition format on apps)
POST /api/v1/write (remote write protobuf)
GET /api/v1/query?query=rate(http_requests[5m])
GET /api/v1/query_range?query=...&start=&end=&step=
POST /api/v1/rules (alert/recording rules)
6.3 Data Model
Sample:
metric_name{label1="v1", label2="v2"} value timestamp_ms
Internal series ID:
hash(metric_name + sorted labels) → series_id
Histogram:
http_request_duration_bucket{le="0.1"} 42
http_request_duration_bucket{le="0.5"} 100
http_request_duration_sum 35.2
http_request_duration_count 100
Sharding:
shard = hash(tenant_id, metric_name) % num_shards
6.4 Deep Dives
Write path:
- Scraper pulls
/metricsevery 15s from target. - Parse text format; validate label count and name length.
- Cardinality limiter drops or aggregates new series beyond quota.
- Append to head block in memory; WAL for durability.
- Every 2h: compact head to immutable block; upload to object store.
Query path:
- Query frontend parses PromQL; splits by time range and shard.
- Parallel fetch from TSDB shards + object store blocks.
- Merge results; return to Grafana.
Figure 2: Query fan-out across shards and cold object storage.
Cardinality explosion prevention:
- Reject labels:
user_id,request_id,trace_idat ingest. - Limit 10K new series/min per tenant.
- Aggregate high-cardinality to
status_codeonly. - Recording rules pre-aggregate before dashboard queries.
Figure 3: Recording rules and ingest limits control cardinality.
Alerting:
- Rule evaluator runs
rate(errors[5m]) > 0.05every eval interval. - Firing alerts → Alertmanager → PagerDuty/Slack with grouping and inhibition.
Downsampling:
- After 15d: 5m resolution aggregates to object store.
- After 90d: 1h resolution for long-term trends.
7. Step-by-Step Walkthrough
7.1 Normal scrape
- K8s pod exposes
http_requests_total{method,status}. - Scraper discovers via annotations; pulls every 15s.
- Samples appended; visible in query within 30s.
7.2 Cardinality incident
- Deploy adds
user_idlabel; 500K new series in 5 min. - Limiter blocks new series; alerts platform team.
- Rollback deploy; recording rule cannot fix historical spike—block retained.
7.3 Long range query
- User queries 30d CPU usage 15s step.
- Query frontend routes >15d portion to downsampled blocks.
- Response in 1.2s vs 30s if raw only.
7.5 Recording rule deployment canary
- New recording rule
service:error_rate:5mdeployed to ruler shard 1 only. - Compare output to ad-hoc query for 24h shadow period.
- Promote to all shards; add to dashboard replacing expensive query.
- Reduces query CPU 10× for 24h range dashboards.
7.6 Multi-tenant noisy neighbor isolation
- Tenant A spikes to 5M new series/hour—limiter blocks at 20K/min.
- Tenant B unaffected on shared cluster—hard isolation requires dedicated TSDB cells for enterprise tier.
- Sales packaging: shared vs dedicated cells pricing.
7B. Histogram Bucket Design Workshop
For HTTP latency SLO 200ms p99:
Suggested buckets (seconds): 0.005, 0.01, 0.025, 0.05, 0.1, 0.2, 0.5, 1, 2, 5
Too few buckets → quantile error; too many → cardinality on le label manageable (typically <20 buckets). Native histograms (OpenMetrics) reduce label cardinality—adoption growing.
10A. Federation Hierarchy Example
Global query frontend
├── region-us (Thanos query)
│ ├── prom-k8s-prod-1
│ └── prom-k8s-prod-2
└── region-eu
└── prom-k8s-eu-1
Global SLO dashboard fans out—cache 1 min at global layer to protect regional queriers.
| Phase | Key decisions |
|---|---|
| Requirements | PromQL, 10M samples/sec, 15d retention |
| Scale | shard TSDB; object store blocks |
| APIs | scrape + remote write + query |
| Data | series_id; histogram buckets |
| Deep dives | cardinality limits; downsampling |
8. Invariants and Guarantees
| Property | Guarantee |
|---|---|
| Sample immutability | Past blocks read-only |
| Counter monotonic | rate() assumes resets handled |
| Tenant isolation | Query cannot cross tenant without admin |
| WAL durability | Recent samples survive process crash |
| Alert eval at-least-once | Possible duplicate notifications—dedupe externally |
9. Failure Scenarios
| Scenario | Mitigation |
|---|---|
| TSDB shard down | Replica; partial query degradation |
| Object store outage | Query recent only; alert |
| Cardinality storm | Hard limits; automatic drop |
| Slow query | Query timeout; recording rules |
| Clock skew | Reject out-of-order beyond tolerance |
| Scrape target down | up metric alert; stale marker |
10. Performance Characteristics
10M samples/sec × 16 bytes ≈ 160 MB/sec ingest
50M series × index overhead ≈ tens of GB RAM per shard
Block compression: 1.5 bytes/sample typical
Query: parallel shard fetch dominates; merge CPU for aggregations
Scrape interval 15s default—balance resolution vs load
11. Scalability Limits
| Limit | Mitigation |
|---|---|
| Cardinality | Label policies; aggregation |
| Query fan-out | Recording rules; query frontend cache |
| Single metric hot shard | Shard by additional label hash |
| Long retention cost | Object store + downsample |
| Alert eval CPU | Sharded ruler |
12. Operational Considerations
- Metrics: ingest lag, samples/sec, active series, query latency, compaction backlog.
- Alerts: cardinality limit hit; WAL corruption; block upload failure.
- Runbooks: tenant series reset; emergency label drop list.
- Capacity plan: series growth per new service.
13. Security Considerations
- Auth on query and remote write APIs.
- Tenant API keys scoped to write or read.
- No PII in labels—enforce via CI lint.
- Network policy: scrape internal only.
- Audit admin queries across tenants.
14. Cost Considerations
Storage scales with series count × retention. Downsampling saves 90%+ for old data. Managed vs self-hosted: ops headcount tradeoff. Chargeback per tenant by active series and ingest volume.
15. Production Implementations
| System | Notes |
|---|---|
| Prometheus | CNCF standard; pull model |
| Thanos/Cortex/Mimir | Horizontally scalable Prometheus |
| Datadog | SaaS metrics + APM |
| InfluxDB | Alternative TSDB |
| VictoriaMetrics | Compression-focused TSDB |
16. Alternatives and Tradeoffs
| Approach | Pros | Cons |
|---|---|---|
| Pull (Prometheus) | Service discovery; target health | NAT/firewall issues |
| Push (StatsD) | Simple agents | Cardinality harder to control |
| Histogram | Aggregatable percentiles | Bucket design matters |
| Summary | Exact quantiles per instance | Not aggregatable |
| Logs as metrics | Reuse pipeline | Expensive; wrong tool |
| Single giant TSDB | Simple | Vertical scale ceiling |
16A. Building an SLO Metrics Package per Service
Minimum viable metrics for each microservice before production:
http_requests_total{method,route_template,status}counterhttp_request_duration_secondshistogram with SLO-aligned bucketsprocess_cpu_seconds_totaland memory (USE method)upor custom health gaugedependency_call_durationhistogram for top 3 downstreams
Route template label uses /users/{id} not raw path—prevents cardinality explosion. Enforce via code review checklist tied to SLO SLI Error Budgets.
16B. On-Call Friendly Dashboards
Dashboard panels should answer in 10 seconds during incident:
- Is ingest healthy? (rate, errors)
- Is query path slow? (p99, queue depth)
- Cardinality growing? (active series derivative)
- Which tenant/job caused spike? (top 10 series by count)
Avoid 50-panel dashboards—on-call ignores them under stress.
| "Logs can replace metrics" | Different cost and query model | | "Summary for global p99" | Use histogram + histogram_quantile | | "Infinite retention cheap" | Downsample required | | "Metrics need strong consistency" | Brief gaps acceptable |
18.1 FinOps Integration
Metrics platform enables chargeback: storage_active_series{team} and samples_ingested_total{team} exported monthly to finance. Teams exceeding cardinality budget pay internal transfer price—drives behavior better than email warnings alone. Principal architects partner with FinOps to set unit economics before self-serve metric onboarding. Sudden cost spike investigation starts with top 10 new series by team label—same workflow as incident response.
18. Principal Architect Perspective
- Cardinality budget per team—enforce in CI and ingest.
- SLO metrics designed before launch—not added after outage.
- Recording rules for dashboard queries—protect TSDB.
- Alert quality over quantity—symptoms not causes where possible.
- Runbooks linked to alerts in Alertmanager annotations.
19. Architecture Review Exercise
Scenario: http_requests{user_id, path} → 20M series; queries timeout.
Review: Drop user_id; aggregate path to route template; recording rule for p95 latency.
20. Whiteboard Explanation
"Apps expose Prometheus metrics; scrapers pull every 15s or agents remote-write to ingest gateways. Cardinality limiter enforces per-tenant series quotas. Samples land in sharded TSDB head blocks with WAL, compacted to immutable blocks in object storage. Query frontend parses PromQL, fans out to shards and cold blocks, merges results. Alert evaluator runs rules; Alertmanager groups notifications. Downsampled tiers for long retention. Never allow unbounded label dimensions."
21. Interview Questions
- Design metrics for 10M samples/sec. — Signals: shard TSDB, object blocks. Red flags: one DB.
- Pull vs push? — Signals: K8s scrape vs agent push. Follow-up: hybrid.
- Cardinality explosion? — Signals: label limits, drop rules. Red flags: ignore.
- Histogram vs summary? — Signals: aggregatable percentiles. Follow-up: bucket design.
- Calculate storage needs? — Signals: samples/sec × bytes × retention.
- PromQL rate() purpose? — Signals: counter reset handling.
- Multi-tenant isolation? — Signals: tenant label; shard; ACL.
- Long query optimization? — Signals: recording rules, downsample, parallel fetch.
- Alert fatigue reduction? — Signals: grouping, inhibition, SLO burn alerts.
- HA for Prometheus? — Signals: Thanos/Mimir; not single replica HA.
- Exemplars why? — Signals: metrics-to-traces correlation.
- WAL purpose? — Signals: crash recovery before compaction.
- Service discovery? — Signals: K8s SD, Consul.
- Detect scrape failure? — Signals:
upmetric, missing samples alert.
21B. Extended Interview Question Deep Dives
Q15 (Principal): Board asks for per-customer p99 latency metric—5000 SaaS tenants.
Strong signals: Reject customer_id label—use exemplar sampling or separate tenant cells for enterprise; aggregate tiers (free/pro/enterprise). Red flags: "Add label." Rubric: 5/5 explains cardinality explosion with mitigation.
Q16 (Principal): Migrate 200 legacy Prometheus to unified Mimir—strategy?
Strong signals: Federation interim; remote write dual-publish; recording rule parity validation; cutover by team; rollback plan. Timeline: quarters not days for 200 clusters.
- SLO burn rate alerts. — Multi-window multi-burn-rate (Google SRE book).
- Federation for multi-cluster. — Hierarchy tradeoffs.
22A. Production Low-Level Design (Interview + Game Day)
Metrics LLD: agents → write path aggregator → TSDB; protect with cardinality governance.
Context diagram
Step-by-step flow:
| Step | Action |
|---|---|
| 1–2 | Collect; drop high-card labels early |
| 3–4 | Governed write |
| 5–6 | Query + alerting |
Production stack
| Layer | Choice | Role |
|---|---|---|
| Collect | OTel / Prometheus | Relabel |
| Gateway | Distributor | Auth + limits |
| TSDB | Mimir / Cortex / Victoria | Multi-tenant |
| Rules | Ruler | Recording + alerts |
| Long-term | Downsample / cold | Cost |
API + schema
POST /api/v1/write (remote_write)
GET /api/v1/query
GET /api/v1/query_range
POST /api/v1/rules
| Concept | Example |
|---|---|
| Metric | http_requests_total |
| Labels | {service, route, status} — not user_id |
| Recording rule | job:http_errors:rate5m |
Happy-path sequence
Failure — cardinality bomb
Observability + SLO
| SLI | Idea |
|---|---|
| Ingest lag | Seconds |
| Query p99 | Dashboard class |
| Active series / tenant | Hard cap |
| Rule eval delay | Alert freshness |
22B. Game Day Playbooks
Catalog
| ID | Drill | Inject | Signal |
|---|---|---|---|
| GD-1 | Cardinality bomb | user_id label | Series spike |
| GD-2 | Compaction stall | Slow store | Ingest backpressure |
| GD-3 | Noisy neighbor | One tenant 10× | Fairness limits |
| GD-4 | Alert storm | Flapping rule | Inhibition |
| GD-5 | Query of death | Unbounded range | Timeout |
| GD-6 | Clock skew scrape | Bad timestamps | Out-of-order |
GD-1 — Cardinality bomb (detailed)
GD-5 — Query of death (detailed)
Pass criteria: cluster query latency for others unchanged; offender informed with rewrite (recording rule).
23. Strong Answer Example
Question: "How prevent cardinality from killing the system?"
Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—label governance + per-tenant series caps + early drop, not bigger TSDB alone.
Figure A: PRACTICE map — walk the board in this order.
Student interview script (PRACTICE)
P — Problem framing
"Metrics die from cardinality: unbounded labels (
user_id,request_id) create billions of series. Memory, compaction, and queries collapse. Prevention is product policy: approved label sets, collector relabel drops, gateway hard caps per tenant, and recording rules for dashboards—not raw high-card queries."
R — Requirements
| Type | Requirement |
|---|---|
| FR | Ingest useful golden signals |
| NFR | Bound active series growth |
| Safety | Isolate noisy tenants |
| Ops | Alert on series churn |
A — Assumptions
| Assumption | Why |
|---|---|
| Prometheus-like model | Labels = identity |
| Multi-tenant | Caps mandatory |
| Devs will invent labels | Linters + review |