Distributed Metrics System
An exporter creates millions of new label combinations.
Topic tools
Layout updated
Problem statement
Design a distributed metrics system that collects measurements from many services. Users can query historical data, view dashboards, and get alerts when thresholds are crossed.
Functional requirements
- Ingest time-series samples and query dashboards.
- Configure alert rules and track open or resolved incidents.
- Notify users when an incident opens or resolves.
- Recover ingestion, alert state, and notifications after regional failure.
Non-functional requirements
- Aim for alerts within 10 s and bounded queries within 1 s.
- Limit new time series and avoid duplicate incident pages.
- State the data-loss and recovery-time limits of replication.
- Do not replay old input as a new incident.
Back-of-the-envelope estimates
| Illustrative estimate |
|---|
| 1M active series × one sample/10 s = 100k samples/s |
| 32 bytes/sample × 100k/s ≈ 276 GB/day raw |
| 100k samples/s rerouted into a region already handling 100k/s |
| 15-minute backlog at 100k/s = 90M samples |
Entities
| Entity / logical owner |
|---|
| Series(tenant, metric, canonicalLabels, seriesId) |
| Sample(seriesId, timestamp, value, sampleId) |
| Rule(version, expression, duration) and Incident(ruleId, seriesGroup, generation, state) |
| RecoveryManifest(regionEpoch, checkpointURI, inputOffsets, ruleVersions) |
| Incident(ruleId, group, generation, state) |
| DeliveryIntent(incidentId, transition, providerKey) |
API design
| Operation / input | Response and retry contract |
|---|---|
POST/samples {sourceId, batchId, samples[]} | 202 after the selected durability policy commits the batch. Each sample carries a stable sampleId so replay or regional resend can be deduplicated. |
GET/query?metric=...&from=...&to=...&step=... | Bound series/range/work; return data and resolution. |
PUT/rules/{id} {expectedVersion, expression, forDuration} | Versioned rule; transitions carry rule/incident generation to avoid duplicate pages. |
POST/recovery-plans/{id}/activate {expectedEpoch} | Validate /input availability and fence the old evaluator/delivery owner. |
GET/incidents/{id} | Return reconciled state and last delivered transition, not just volatile operator state. |
High-level design
How to draw this design
- Admit measurementsAgents, gateway, series registry, and Kafka
- Process samplesStorage writers, rollup workers, and alert evaluators
- Store query and alert stateTime-series storage, historical rollups, and PostgreSQL rules and incidents
- Serve queries and alertsQuery engine, dashboards, and notification delivery
Accept samples into a durable log. Independent consumers store time series and evaluate alerts.
- State ownership
- The time-series store holds query data. PostgreSQL owns rule versions and durable incident state.
- Scale
- Bound label cardinality and isolate dashboard work from alert evaluation.
- Correctness
- Commit the incident transition and notification intent together.
- Failure and recovery
- Match a recovery to available log offsets and fence the prior notification owner.
Metrics ingestion, queries, and alerting
Follow a sample into the durable log, then trace the separate consumers for dashboard storage and alert evaluation.
- Edge
- Compute
- Messaging
- State
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 16 flow steps
Regional recovery and alert continuity
Pick up with the original stream offsets, evaluator checkpoints, and incident records. The standby restores them before sending alerts.
- Edge
- Messaging
- Compute
- State
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 8 flow steps
High-level design component walkthrough
Agents / Exporters
Collect & batch samples
Why, tradeoff and connected operations
An application or user-facing endpoint starts or receives this flow.
Tradeoff: Local buffers are bounded
Connected operations: batched samples
Regional Gateway
Route agents to healthy region
Why, tradeoff and connected operations
Centralize admission and routing while keeping business-state ownership downstream.
Tradeoff: Failover increases regional load
Connected operations: batched samples; push metrics
Ingestion Service
Validate & normalize metrics
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: CPU / network overhead
Connected operations: push metrics; admit series
Quota + Series Registry
Restrict new high-cardinality series
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: May reject useful new labels
Connected operations: admit series; accepted samples
Kafka / Durable Stream
Buffer burst and support replay
Why, tradeoff and connected operations
Kafka retained partitioned stream. Key events by the domain ordering key; replay and independent consumers motivate this choice. rows remain in the source database; a relay publishes after commit. Buffer independent producers and consumers, with bounded and replay semantics.
Tradeoff: Finite capacity, lag
Connected operations: accepted samples; consumer; independent alert consumer
Cassandra TSDB Writers
Batch writes with
Why, tradeoff and connected operations
Write time-bucketed series partitions; bound cardinality before persistent ingestion. Partition durable state by the documented lookup key; consistency follows the explicit replication policy.
Tradeoff: Can lag when database slows
Connected operations: consumer; persist samples
Flink Alert Evaluators
Evaluate windows independently
Why, tradeoff and connected operations
Compute derived state away from request handlers; checkpoints and govern recovery.
Tradeoff: and replay complexity
Connected operations: independent alert consumer; transition incident; Read versioned alert rules
Cassandra Recent TSDB
Indexed recent sample storage
Why, tradeoff and connected operations
Cassandra stores recent samples by metric series and bounded time bucket. This spreads ingestion and makes common time-range reads predictable. A time-series key model fits these samples; is retained for related alert-rule and incident transactions.
Tradeoff: Partition/hot-key tuning
Connected operations: persist samples; historical rollups; recent time range
Flink Rollup Workers
Aggregate by time and labels
Why, tradeoff and connected operations
Compute derived state away from request handlers; checkpoints and govern recovery.
Tradeoff: Late data needs correction
Connected operations: historical rollups; compact and tier
Historical Rollup Store
Cheap 30-day+ query layer
Why, tradeoff and connected operations
Object storage retains compact historical rollups at lower cost than hot sample storage. Queries can read older time ranges without keeping every raw sample in the recent database. It is a cold archive layer, not a general-purpose transaction store.
Tradeoff: Older points less detailed
Connected operations: compact and tier; historical rollups
PostgreSQL: Alert Rules, Incidents and Outbox
Keep versioned alert rules and durable incident records. Commit incident transitions and delivery intent together.
Why, tradeoff and connected operations
PostgreSQL stores alert rules, incident identity and notification intent together. Transactions prevent an incident transition from losing its event. fits alert correctness, while Cassandra handles the much larger sample stream.
Tradeoff: Cross-region state coordination
Connected operations: transition incident; Relay committed notification intent; Read versioned alert rules
Notification + Outbox
Retry & dedupe each incident
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Exactly-once delivery needs provider
Connected operations: Relay committed notification intent; deduped delivery
PagerDuty / Teams / Email
Reach on-call responders
Why, tradeoff and connected operations
Treat another system as a separate failure and retry domain with a documented contract.
Tradeoff: Delivery dependencies can fail
Connected operations: deduped delivery
Query Engine
Prune, aggregate, cache results
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Expensive high-cardinality queries
Connected operations: recent time range; historical rollups; range query
Dashboards / Clients
View historical and live trends
Why, tradeoff and connected operations
An application or user-facing endpoint starts or receives this flow.
Tradeoff: Freshest bucket may change
Connected operations: range query
US-West Agents
Buffer samples on failure
Why, tradeoff and connected operations
An application or user-facing endpoint starts or receives this flow.
Tradeoff: Bounded buffers may overflow
Connected operations: region unavailable
Global Routing
Switch ingestion to US-East
Why, tradeoff and connected operations
Centralize admission and routing while keeping business-state ownership downstream.
Tradeoff: Detection and propagation delay
Connected operations: region unavailable; reroute and resend
Kafka: Surviving Region Stream
Accept / replay durable events
Why, tradeoff and connected operations
Kafka retained partitioned stream. Key events by the domain ordering key; replay and independent consumers motivate this choice. rows remain in the source database; a relay publishes after commit. Buffer independent producers and consumers, with bounded and replay semantics.
Tradeoff: Requires reserved surge capacity
Connected operations: reroute and resend; resume Kafka offsets; replay backfill
Flink Alert Evaluator
Replay samples and state
Why, tradeoff and connected operations
Compute derived state away from request handlers; checkpoints and govern recovery.
Tradeoff: Late / duplicated samples
Connected operations: resume Kafka offsets; restore ; reconcile transitions
Cassandra TSDB Backfill
Recover historical gaps
Why, tradeoff and connected operations
Replay missing time buckets from durable input using idempotent series/timestamp identity. Partition durable state by the documented lookup key; consistency follows the explicit replication policy.
Tradeoff: Some unreplicated samples lost
Connected operations: replay backfill
Replicated Checkpoints
Restore operator state/offsets
Why, tradeoff and connected operations
Object storage keeps replicated evaluator checkpoints and stream positions. Recovery can restore recent progress instead of rebuilding all operator state from scratch. These are recovery artifacts, not a replacement for the incident database or event stream.
Tradeoff: Replication can lag
Connected operations: restore
PostgreSQL / Durable Incident Store
Incident ID & generation
Why, tradeoff and connected operations
PostgreSQL preserves incident IDs, generations and delivery intent during recovery. Conditional transitions keep a resumed evaluator from creating a second logical incident. This is the recovered incident authority from the main design, not an unrelated new database.
Tradeoff: Must reconcile replicated state
Connected operations: reconcile transitions; durable notification claim
Kafka: Notification Delivery Topic
Carry notifications from the recovered incident with their original delivery keys.
Why, tradeoff and connected operations
Kafka retained partitioned stream. Key events by the domain ordering key; replay and independent consumers motivate this choice. rows remain in the source database; a relay publishes after commit. Buffer independent producers and consumers, with bounded and replay semantics.
Tradeoff: Redelivery remains possible
Connected operations: durable notification claim; same incident key
PagerDuty Dedup Key
Suppress replayed notifications
Why, tradeoff and connected operations
Treat another system as a separate failure and retry domain with a documented contract.
Tradeoff: Depends on provider
Connected operations: same incident key
Engineering control room
Deep dives — decisions, failures and recovery
Open a deep dive to follow the steps, try an example and see how recovery works.
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Stop unbounded metric labels before storage | Reject or explicitly aggregate excess data. Silently changing labels can change what an alert means, so the policy must be visible. |
| Keep alerting separate from slow storage queries | Independent consumers need enough retained input and saved state to catch up. They remain recoverable only while that history is available. |
| Track one incident, then deliver its notifications | The provider still needs to recognize repeated sends after an uncertain delivery. A durable local incident does not control a remote paging side effect by itself. |
| Keep one bad sample from stopping the stream | Skipping bad input restores progress but can weaken completeness; blocking preserves order while increasing alert delay. |
| Restore a and the input it expects | Copying checkpoints and raw events asynchronously keeps ingestion fast but permits regional data loss. Synchronous remote acknowledgement reduces the loss window at a latency and availability cost. |
| Resume regional notifications without paging twice | Waiting for a verified ownership change can delay pages. Sending from both regions reduces some delays but creates duplicates and can produce contradictory incident updates. |
Production scars & failure modes
An exporter creates millions of new label combinations.
Look for: Track active series and allocation rate by tenant and label source.
Recovery and invariant: Enforce cardinality budgets before persistent ingestion, drop or quarantine excess series explicitly and isolate tenants; replay should preserve incident identity.
| Component / failure | Impact | Recovery mechanism | Alternative / tradeoff |
|---|---|---|---|
| writer slowdown | Dashboards lag while the input log grows. | its consumer, retain offsets and recover at a rate above new arrivals. | Alert consumers continue only while their own dependencies and log capacity remain healthy. |
| Flink task failure | Window evaluation pauses or replays. | Restore -consistent state/offsets and preserve incident generation through replay. | durability and rule-version alignment determine correctness. |
| Cardinality attack | Memory/index allocation overwhelms ingestion and storage. | Reject excess new series, isolate tenant budgets and alert on registry growth. | Some telemetry is intentionally rejected to protect platform availability. |
| Notification provider failure | Incidents are durable but pages may not reach on-call. | Retry with stable delivery keys, use a configured escalation policy and reconcile outcomes. | An internal FIRING record does not prove a human was notified. |
| copy incomplete | Recovery can read a but not every state object. | Validate checksums/completeness, select an earlier verified and retain compatible logs. | increases with replay depth. |
| Raw input missing remotely | Some locally acknowledged samples never reached the survivor. | Mark the gap, recover from agents/archive where available and expose nonzero . | No algorithm reconstructs irretrievably lost samples. |
| Old region reconnects | Its state and delivery claims may be stale. | Fence its , rebuild/catch up, and rejoin only through a verified handoff. | Do not independently merge arbitrary operator checkpoints. |
| Provider lost | A recovered may page again. | Retry the same incident transition key and query provider status when possible. | External duplicate suppression depends on provider guarantees. |
90-second interview summary
I would write metric samples to a durable log after validating tenant and label limits. One consumer stores time series for dashboards and another evaluates alert rules. This keeps slow historical queries or writes from delaying every alert. I would store each incident episode and its notification work together.
Each evaluator records the input positions and rule versions it needs. During a regional outage I would restore a complete with the matching replay range and restore open incident state. I would size the surviving region for both rerouted live traffic and replay.
Before resuming notification sends, I would fence the old region and preserve incident and delivery keys. A threshold crossing during replay should update its existing incident, and an uncertain provider response should be reconciled as the same delivery attempt.
The main tradeoff is between low-latency asynchronous copies and stronger durability across regions. I would measure the actual replication gap and recovery drain rate, expose affected data windows, and test regional loss through ingestion, dashboards, and alert delivery.
Explain it without looking
Explain stop unbounded metric labels before storage
Reveal answer
Limit new series per tenant before allocating persistent state.
Adding CPU cannot keep up with a metric that creates a different series for every request ID.
Reject or explicitly aggregate excess data. Silently changing labels can change what an alert means, so the policy must be visible.
Explain keep alerting separate from slow storage queries
Reveal answer
Give storage writers and alert evaluators their own progress and budgets.
A slow historical-query path should not stop detection of a current incident.
Independent consumers need enough retained input and saved state to catch up. They remain recoverable only while that history is available.
Explain track one incident, then deliver its notifications
Reveal answer
Save the incident episode and notification work together.
Replaying the same samples must not create a new incident and page everyone again.
The provider still needs to recognize repeated sends after an uncertain delivery. A durable local incident does not control a remote paging side effect by itself.
Explain keep one bad sample from stopping the stream
Reveal answer
One malformed record must not silently stop unrelated metrics and alerts.
A fleet-wide average lag can hide one stuck partition that contains a critical alert.
Skipping bad input restores progress but can weaken completeness; blocking preserves order while increasing alert delay.
Explain restore a and the input it expects
Reveal answer
Recover alert state at a whose rule versions and following log offsets are available in the recovery region.
A newer is unusable if its state is incomplete or the remote log has a gap after its recorded position.
Copying checkpoints and raw events asynchronously keeps ingestion fast but permits regional data loss. Synchronous remote acknowledgement reduces the loss window at a latency and availability cost.
Explain resume regional notifications without paging twice
Reveal answer
Restore incident identity and fence notification ownership before enabling sends in the new region.
Restored samples can make an existing outage look new. During a partition, both regions might also try to page the same on-call engineer.
Waiting for a verified ownership change can delay pages. Sending from both regions reduces some delays but creates duplicates and can produce contradictory incident updates.
Revision checklist
Revision checklist
- Reconstruct stop unbounded metric labels before storage: Limit new series per tenant before allocating persistent state.
- Reconstruct keep alerting separate from slow storage queries: Give storage writers and alert evaluators their own progress and budgets.
- Reconstruct track one incident, then deliver its notifications: Save the incident episode and notification work together.
- Reconstruct keep one bad sample from stopping the stream: One malformed record must not silently stop unrelated metrics and alerts.
- Reconstruct restore a and the input it expects: Recover alert state at a whose rule versions and following log offsets are available in the recovery region.
- Reconstruct resume regional notifications without paging twice: Restore incident identity and fence notification ownership before enabling sends in the new region.
- Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
- Explain one alternative and exactly which guarantee you would relax.
- Redraw the request and recovery paths without looking; mark what required a hint.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope sample ingestion, historical queries, and alerts. Estimate samples per second and identify the cardinality limit. |
| 15–30 min | High-level design | Draw one durable input log with separate consumers for dashboard storage and alert evaluation. Show incident delivery. |
| 30–45 min | Deep dives | Explain cardinality admission and why incident state and notification intent commit together. |
| 45–55 min | Failure and recovery | Walk through regional recovery. Match checkpoints to available offsets and fence alert delivery before replaying. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |
On this page
- Problem statement
- Functional requirements
- Non-functional requirements
- Back-of-the-envelope estimates
- Entities
- API design
- High-level design
- High-level design component walkthrough
- Engineering control room
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 90-second interview summary
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough