Learning pathsPricingChecking sign-in…
GUIDED PRACTICE

Practice: Metrics Monitoring

Design a multi-tenant monitoring service for 100,000 hosts sampled every 15 seconds, with bounded series cardinality, range queries, downsampling, and one-minute alert evaluation.

Design a multi-tenant monitoring service for 100,000 hosts sampled every 15 seconds, with bounded series cardinality, range queries, downsampling, and one-minute alert evaluation.

Write your own design before opening hints or the solution review. The numbers below are exercise assumptions, not claims about any company’s production traffic. You may challenge an assumption, but record the replacement and explain which decision changes.

Scenario and constraints

  • Assumed ingest: 6.67 million samples/s; raw retention: 15 days; label and WAL bytes exceed the two-byte value payload.
  • A request_id label would multiply a 40,000-series metric into 40 billion possible series.
  • Samples may arrive up to two minutes late; future clock skew is limited to 30 seconds.
  • An evaluator can crash after committing firing state and before notification delivery.

Your deliverables

  • Define tenant-scoped canonical series identity and atomic batch retry behavior.
  • Calculate raw value volume, then explain block, WAL, index, replication, and rollup costs.
  • Specify late, duplicate, conflicting, and future timestamp behavior.
  • Merge histogram bucket counts before computing service p95; never average instance percentiles.
  • Show durable alert state, a monotonic evaluation watermark, fencing epoch, and notification outbox.

Reason about this sequence

Collector stops reporting → Last sample age grows → Missing is not zero → No-data policy activates → Independent pipeline alert fires
Metrics Monitoring · scenario walkthrough
Read the diagram

Collector stops reporting → Last sample age grows → Missing is not zero → No-data policy activates → Independent pipeline alert fires

Open original
Metrics Monitoring · scenario walkthrough
Collector stops reporting → Last sample age grows → Missing is not zero → No-data policy activates → Independent pipeline alert fires

Metrics Monitoring · scenario walkthrough

For every step, annotate what is durable, what the caller knows, and which identity survives a retry. Identify the point where two concurrent actors could disagree. Do not assume a timeout means failure or a cache value grants ownership.

Interviewer follow-ups

  • A noisy tenant adds one million request_id values to a stable metric family.
  • A sample arrives after the two-minute lateness window while a dashboard query is running.
  • Evaluator A crashes after the transition transaction; evaluator B resumes while A sends a stale evaluation.

Answer each follow-up using the same design first. If it breaks, change the smallest boundary that repairs the invariant and explain the new cost. Show whether the change adds latency, storage, coordination, or operational work.

Staged hints

Hint 1 — reveal

Answer: Hint 1 — Invariant: every accepted point belongs to exactly one canonical tenant series; alert evaluation advances monotonically, persists state with its transition intent, and distinguishes missing data from zero.

Hint 2 — reveal

Answer: Hint 2 — Identify a series by metric name and labels, and samples by timestamp under the chosen duplicate policy. Buffer short outages within a bounded capacity. Partition ingestion and storage by series and time, while watching hot tenants. Keep high-resolution recent data and lower-resolution historical data if query needs permit.

Hint 3 — reveal

Answer: Hint 3 — The collector stops sending samples. A dashboard that replaces missing values with zero may show no errors and trigger a false recovery. Preserve absence semantics and alert on telemetry freshness. If a counter restarts at zero, rate calculations must handle the reset rather than interpret it as negative traffic. Test collector outage, late samples, clock skew, and alert delivery failure.

Evidence-based self-review

  • Tenant series quotas reject cardinality growth without allowing collisions to merge identities.
  • Dashboards state their time range, step, scan budget, freshness, and missing-data behavior.
  • Rollups preserve mergeable sum/count/extrema and compatible histogram buckets.
  • Late-data policy is explicit and old evaluations cannot regress alert state.
  • Fencing plus stable transition IDs prevents stale evaluator writes and duplicate logical notifications.

Score each item 0 if absent, 1 if named without an enforceable mechanism, or 2 if the mechanism and a failure are explained. Record evidence from your own diagram beside the score. Then choose one weak decision, revise it, and repeat the relevant follow-up. This rubric is a learning tool, not a hiring forecast.

Clarify this prompt before choosing components

Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.

Ask the interviewerWhy the answer changes the design
Counters, gauges, histograms or logs too?Aggregation semantics and storage choices differ.
Cardinality, scrape/ingest rate and retention tiers?Bound labels and size both series and samples.
Alert delay, missing data and regional outage?Distinguish zero from absence; define deduplication, staleness and repair.

Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.

Reveal the full worked solution

Save your attempt before continuing.

Metrics Monitoring: Understand the building blocks

Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.

Metrics Monitoring: Quick vocabulary

TermMeaning and role in this exercise
API: Application Programming InterfaceThe contract for requests, responses and errors between components. An API route does not itself enforce every business invariant.
PK: Primary KeyThe declared row identity in a database schema; it does not automatically enforce every cross-row business rule.

Metrics Monitoring: Histogram, quantile and time series

What it means: A time series identifies timestamped measurements by metric and labels. A histogram summarizes observations into compatible buckets; a quantile such as p99 describes a distribution position.

Why this problem needs it: Fleet latency cannot be recovered by averaging worker percentiles.

How to use it: Bound label cardinality, merge compatible bucket counts and derive the quantile from the merged distribution, preserving missing-data status.

Example in this design: A 100-sample worker and a 10,000-sample worker need a compatible distribution merge.

When it fits: Useful for fleet latency/health when raw observations are too costly.

Alternative and limits: Raw samples retain detail at greater cost. Averaging per-worker p99 values does not compute the fleet p99, and missing telemetry is not zero.

Metrics Monitoring: Write-ahead log (WAL)

What it means: A WAL records changes for recovery before dependent state is acknowledged or persisted under the selected durability policy.

Why this problem needs it: Accepted ingestion needs a named recovery boundary.

How to use it: Specify append/flush/replication acknowledgement, replay position and the boundary that makes an accepted batch recoverable.

Example in this design: A process crash before the selected durable append must not be reported as safely accepted.

When it fits: Useful when buffered ingestion must survive process failure.

Alternative and limits: A durable external queue/log can supply another recovery boundary. Merely buffering data in memory or naming WAL does not establish a crash guarantee.

Metrics Monitoring: Event time, watermark and windows

What it means: Event time is when an event happened; arrival time is when it reached this processor. A window defines the interval grouped for computation, and a watermark expresses progress under a lateness policy.

Why this problem needs it: Out-of-order samples need a declared time/late-data contract.

How to use it: Bind each event to its window identity, deduplicate under a declared horizon, and emit allowed revisions or reject/quarantine events past the finality boundary.

Example in this design: Recompute allowed windows while keeping missing telemetry distinct from zero.

When it fits: Useful when delayed delivery should not silently move activity into the wrong reporting period.

Alternative and limits: Processing-time windows are simpler if arrival time is the intended business meaning. A watermark is not proof no older event can ever arrive.

Metrics Monitoring: Durable work queue and backpressure

What it means: A queue separates accepted work from execution. Backpressure limits admission or consumption when downstream capacity is finite.

Why this problem needs it: Ingestion and alerting must stay bounded under cardinality or outage bursts.

How to use it: Persist a stable job identity, consume with bounded concurrency, acknowledge after the required durable transition, and cap retries/backlog according to policy.

Example in this design: Limit series/labels and backlog; a queue does not create unlimited retention.

When it fits: Useful for asynchronous work that must survive worker failure or absorb a finite burst.

Alternative and limits: A synchronous call is simpler for short bounded work. A queue does not create capacity, strict global ordering or exactly-once external effects.

Interview scope and guarantees

Ingest labeled numeric samples, query time ranges, aggregate dashboards and evaluate alert rules. Define acceptable data loss, lateness and query freshness. The number of unique label combinations is a first-class capacity constraint.

Capacity worksheet

Assume 100,000 targets each expose 1,000 series every 15 seconds: 100 million active series and about 6.67 million samples/s. At an illustrative 2 compressed bytes/sample, values alone consume about 1.15 TB/day; labels, indexes, WAL and replication add more. A user_id label can multiply this dramatically.

Concrete API contract

Contract / pseudocode
POST /write {series:[{labels,samples}]}
GET /query_range?query=...&start=...&end=...&step=...
POST /rules {expression,forDuration,labels}
GET /alerts

Data model and access paths

Contract / pseudocode
series(series_id PK,fingerprint,tenant_id,metric_name,canonical_labels); UNIQUE(tenant_id,metric_name,canonical_labels)
samples(series_id,timestamp,value); PK(series_id,timestamp)
blocks(tenant_id,min_time,max_time,object_key,index_key,checksum)
alert_state(rule_id,rule_version,label_set,pending_since,state,last_transition_id,last_sample_watermark)

Evolve a solution and explain each change

Three architecture decisions for Metrics Monitoring, including the pressure each introduces.
Three architecture decisions for Metrics Monitoring, including the pressure each introduces.
Read the diagram

Ingest samples / Validate metric identity, labels, timestamps, and tenant quota. / Unbounded label combinations can consume memory and storage.; Store and query time series / Partition samples and retain/downsample by an explicit accuracy policy. / Out-of-order samples and counter resets affect query meaning.; Evaluate alerts durably / Define missing-data semantics, pending duration, and notification deduplication. / A stalled collector can resemble a healthy zero-error service.

Open original
Metrics Monitoring · architecture decisions
Three architecture decisions for Metrics Monitoring, including the pressure each introduces.

Three architecture decisions for Metrics Monitoring, including the pressure each introduces.

Step 1: Ingest samples

Validate metric identity, labels, timestamps, and tenant quota. Unbounded label combinations can consume memory and storage.

Step 2: Store and query time series

Partition samples and retain/downsample by an explicit accuracy policy. Out-of-order samples and counter resets affect query meaning.

Step 3: Evaluate alerts durably

Define missing-data semantics, pending duration, and notification deduplication. A stalled collector can resemble a healthy zero-error service.

Responsibility overview

Connected responsibilities for Metrics Monitoring. Trace the authoritative and derived paths separately.
Connected responsibilities for Metrics Monitoring. Trace the authoritative and derived paths separately.
Read the diagram

Agent to Ingest API: timestamped samples; Ingest API to Time-series store: bounded series append; Operator to Time-series store: query time window; Rule evaluator to Time-series store: read evaluation range; Rule evaluator to Alert state: persist alert transition; Alert state to Operator: deduplicated notification

Open original
Metrics Monitoring · connected architecture
Connected responsibilities for Metrics Monitoring. Trace the authoritative and derived paths separately.

Connected responsibilities for Metrics Monitoring. Trace the authoritative and derived paths separately.

Worked end-to-end scenario

A service exposes request_count as a monotonically increasing counter, then restarts and the value returns to zero. The query engine must calculate reset-aware rates rather than reporting negative traffic. An error-rate alert evaluates a window and stays pending for a configured duration before firing. If ingestion stops, absence is not automatically zero errors: show no-data and apply a stated missing-data policy. A tenant includes request IDs as labels, creating millions of series. Reject or constrain the high-cardinality dimension before it exhausts the storage and query fleet.

Why these access paths matter

Metric identity is name plus a canonical label set scoped to tenant. Partition samples by series and time; maintain a label index for queries. Retention and downsampling change the resolution available for historical windows. Alert instances are keyed by rule and label set, with evaluation state and a stable notification transition identity.

Build the baseline first

Metrics Monitoring: baseline request paths.
Metrics Monitoring · working baseline
Read the diagram

Collector → validated ingestion → WAL and head block; Compaction → immutable time blocks → query engine; Rule evaluator → pending/firing state → notifications

Open original
Metrics Monitoring · working baseline
Metrics Monitoring: baseline request paths.

Metrics Monitoring · working baseline

  1. Collector → validated ingestion → WAL and head block.
  2. Compaction → immutable time blocks → query engine.
  3. Rule evaluator → pending/firing state → notifications.

Evolve the design under load

Metrics Monitoring: additional scaling and recovery paths.
Metrics Monitoring · scale and recovery paths
Read the diagram

Tenant and series sharding → ingestion workers; Object storage → block index → distributed queries; Recording rules → precomputed aggregates → dashboards

Open original
Metrics Monitoring · scale and recovery paths
Metrics Monitoring: additional scaling and recovery paths.

Metrics Monitoring · scale and recovery paths

  1. Tenant and series sharding → ingestion workers.
  2. Object storage → block index → distributed queries.
  3. Recording rules → precomputed aggregates → dashboards.

Defend the hardest decision

Counters accumulate and can reset; gauges represent current values. Rates must account for counter resets and sampling intervals. Histograms permit aggregation across instances if bucket definitions match; averaging precomputed percentiles is generally invalid. Query cost depends on series cardinality and time range, so enforce per-tenant limits and bounded fanout.

Failure and recovery analysis

An ingestion replica fails after acknowledging a sample. The durability contract determines whether another replica or a persisted log can recover it. Alert evaluators need stable identities so failover does not create duplicate notifications. Missing data is not automatically zero; an absent target may require a separate availability alert.

Security and privacy boundary

Isolate tenant reads and writes, avoid personal information in labels, and cap expensive queries.

Interview follow-ups with reasoning

Question: How do you control cardinality?

Show answer and explanation

Answer: Reject or relabel unbounded dimensions and report dropped-series counts.

Question: How do you handle delayed samples?

Show answer and explanation

Answer: Define an out-of-order acceptance window and query semantics.

Question: How do you test alerts?

Show answer and explanation

Answer: Replay known incident traces including missing data and counter resets.

Operate and verify the design

Active series, rejected labels, sample lag, query cost and alert evaluation delay.

Introduce high-cardinality labels and verify one tenant cannot exhaust ingestion for all others.

A second scenario to test transfer

A service exports 100 metrics across 20 instances and 5 status classes: an illustrative 10,000 combinations before other labels. Adding a label with a million user values can multiply this dramatically. The exact count depends on which combinations exist, but the direction is clear. Put per-request detail in logs or traces with their own budgets rather than exploding metric labels.

Why is averaging the p99 latency from ten instances not the service-wide p99?

Show answer and explanation

Answer: Percentiles are not generally composable by averaging. Instances can have different volumes and distributions. Aggregate compatible histogram counts or underlying observations and compute the percentile from that combined distribution.

Compare alternatives

ConcernDesign responseSignal
CardinalityBound labels and tenant budgetsActive series count
Query costRange and concurrency limitsScanned series and latency
No dataExplicit stale policyLast sample age
Alert noisePending duration and groupingActionable alert rate

A design-changing exercise

No samples arrived for ten minutes. Does that prove there were no errors?

Show answer and explanation

Answer: No. Missing telemetry is distinct from observed zero errors and needs its own health and alert policy.

Design workshop: store series, then query and alert

Requirements and public contracts

The product collects numeric time series, answers bounded range queries, evaluates alert rules, and delivers deduplicated notifications. Logs hold discrete records and traces hold causality; neither is represented as a metric label. Assume a 15-second scrape interval, one-minute rule evaluation, a two-minute allowed-lateness window, and a 30-second future-clock allowance for the worked model. These are interview assumptions, not universal defaults. Tenant isolation, series limits, clear no-data behavior, and a durable ingest acknowledgment are correctness requirements.

POST /metrics/batch accepts {tenant, batch_id, samples:[{metric, labels, timestamp, value}]}; the same batch ID and payload replay as a no-op, while changed content conflicts. GET /query?expression=…&start=…&end=…&step=… requires a tenant context and enforces range, series, concurrency, and scan budgets. POST /alert-rules stores an immutable rule version including threshold, for, evaluation interval, and a no-data policy. Alert notification delivery is asynchronous; the API reports the durable rule and evaluation state rather than promising a notification has reached a person.

Data model and scale assumption

Series(tenant_id, metric_name, canonical_labels, series_id) owns identity; Sample(series_id, event_time, value) owns a point. A series fingerprint is only an index: compare the canonical full key to detect collisions. Rule(rule_id, version, expression, for, no_data_policy), Evaluation(rule_version, series_id, watermark, owner_epoch), AlertState(pending_since, state, transition_id), and NotificationIntent(transition_id, destination) make alert progress replayable. Store timestamps in UTC with event time and ingest time kept separately. Identical duplicate points are no-ops; conflicting values at one series timestamp are rejected for the exercise.

For a deliberately large assumed fleet of 100,000 hosts, 1,000 metrics per host, and 15-second samples, ingest is 6.67 million samples/s. At an illustrative two raw bytes per value, that is 13.34 MB/s, about 1.15 TB/day, and 17.28 TB for 15 days before labels, indexes, WAL, replicas, compression, and block overhead. This makes block partitioning and retention/downsampling a storage decision rather than a cosmetic optimization. Production sizing must use measured encoded bytes and cardinality distributions.

A series identity is tenant + metric name + canonical sorted label set. A fingerprint locates candidates, but compare full labels to resolve hash collisions; do not silently merge two series. Store a stable series_id mapping, index postings for label/value→series IDs, append samples to a WAL and in-memory head, then compact into immutable time blocks with chunk/index metadata. Query workers select label postings, read matching chunks by time range and merge reset-aware series results. Object-store blocks require a catalog/read path, not just an ingestion database box.

Accept a bounded metric batch durably. Agent to Ingest API: Send tenant, stable batch ID, canonical labels, event timestamps; Ingest API to Ingest API: Validate schema, timestamp window, quotas, and duplicate keys; Ingest API to WAL and series catalog: Commit batch identity, series mapping, and sample records; WAL and series catalog to Head block: Expose samples only after the configured WAL quorum acknowledges; Ingest API to Agent: Return batch cursor and accepted or rejected counts
Accept a bounded metric batch durably.
Read the diagram

Send tenant, stable batch ID, canonical labels, event timestamps; Validate schema, timestamp window, quotas, and duplicate keys; Commit batch identity, series mapping, and sample records; Expose samples only after the configured WAL quorum acknowledges; Return batch cursor and accepted or rejected counts

Open original
Accept a bounded metric batch durably
Accept a bounded metric batch durably. Agent to Ingest API: Send tenant, stable batch ID, canonical labels, event timestamps; Ingest API to Ingest API: Validate schema, timestamp window, quotas, and duplicate keys; Ingest API to WAL and series catalog: Commit batch identity, series mapping, and sample records; WAL and series catalog to Head block: Expose samples only after the configured WAL quorum acknowledges; Ingest API to Agent: Return batch cursor and accepted or rejected counts

Accept a bounded metric batch durably.

Write time chunks and preserve rollup semantics. WAL and head to Compactor: Seal a time range with checksum and label postings; Compactor to Immutable block catalog: Publish block metadata only after objects are verified; Query planner to Immutable block catalog: Prune blocks by time and label index before reading chunks; Query planner to Compactor: Read the recent head for ranges newer than compaction; Query planner to Query planner: Merge raw points or compatible rollup fields for the requested step
Write time chunks and preserve rollup semantics.
Read the diagram

Seal a time range with checksum and label postings; Publish block metadata only after objects are verified; Prune blocks by time and label index before reading chunks; Read the recent head for ranges newer than compaction; Merge raw points or compatible rollup fields for the requested step

Open original
Write time chunks and preserve rollup semantics
Write time chunks and preserve rollup semantics. WAL and head to Compactor: Seal a time range with checksum and label postings; Compactor to Immutable block catalog: Publish block metadata only after objects are verified; Query planner to Immutable block catalog: Prune blocks by time and label index before reading chunks; Query planner to Compactor: Read the recent head for ranges newer than compaction; Query planner to Query planner: Merge raw points or compatible rollup fields for the requested step

Write time chunks and preserve rollup semantics.

Partition storage by tenant and time block, with a series index inside each block; a hot metric/tenant can still skew a shard, so admission quotas and shard-load telemetry remain necessary. Keep a bounded mutable head behind a write-ahead log, then publish immutable blocks through a catalog only after checksums and indexes are durable. Retention deletes raw blocks by policy, while longer rollups retain only fields that downstream queries can merge correctly.

Pull scraping exposes target health independently; a failed scrape is not a numeric zero. Push ingestion supports short-lived jobs but requires lifecycle/expiry policy so old pushed values do not look permanently healthy. A collector outage marks staleness after the selected threshold. Rate queries detect counter resets; a negative delta after restart is not negative request traffic. Out-of-order samples inside the accepted window use a documented duplicate-timestamp policy; older data is rejected/reprocessed under an explicit path.

At 6.67 million samples/s and an illustrative two bytes/value, values alone are about 1.15 TB/day and 17.28 TB over 15 days. Labels, WAL, chunks, indexes, replicas and fragmentation add more. One-minute rollups from 15-second samples reduce point count about 4×, but preserve sum/count for averages, extrema for ranges and bucket counts for histograms. A downsampled average cannot reconstruct a spike or exact p99.

Combine cumulative latency buckets before percentile. 100 ms / 90 / 0 / 90; 200 ms / 99 / 1 / 100; 500 ms / 100 / 100 / 200; p95 target / 0.95 × 200 = 190 / Inside (200,500) bucket; Linear bucket interpolation / 200 + (190-100)/(200-100) × 300 / Estimated 470 ms, not exact raw p95
Combine cumulative latency buckets before percentile.
Read the diagram

Upper bound / Instance A / B / Combined count; 100 ms / 90 / 0 / 90; 200 ms / 99 / 1 / 100; 500 ms / 100 / 100 / 200; p95 target / 0.95 × 200 = 190 / Inside (200,500] bucket; Linear bucket interpolation / 200 + (190-100)/(200-100) × 300 / Estimated 470 ms, not exact raw p95

Open original
Combine cumulative latency buckets before percentile
Combine cumulative latency buckets before percentile. 100 ms / 90 / 0 / 90; 200 ms / 99 / 1 / 100; 500 ms / 100 / 100 / 200; p95 target / 0.95 × 200 = 190 / Inside (200,500) bucket; Linear bucket interpolation / 200 + (190-100)/(200-100) × 300 / Estimated 470 ms, not exact raw p95

Combine cumulative latency buckets before percentile.

The histogram example intentionally estimates within buckets; it does not claim observations were uniform. Compatible bucket boundaries permit count aggregation. Precomputed instance p95/p99 values cannot be averaged into a service percentile, particularly with unequal volumes. A query names aggregation dimensions and compatible units explicitly.

Alert instance key is rule_version+label_set. For expression true with for=120s and 60-second evaluations: true at t=0→pending, t=60→pending, t=120→firing. False clears pending/resolves firing; no-data follows a separate chosen policy, for example unknown plus a target-absent alert rather than healthy. Store pending_since and firing transition ID durably so evaluator failover does not restart the timer or resend the same transition. Notification grouping/silence is separate from evaluating truth.

Two evaluators require fenced shard ownership or a deduplicated transition transaction. Record last evaluated sample watermark; a delayed old evaluation cannot resolve a newer alert. Limit range duration, scanned series, query concurrency and per-tenant active series. Monitor WAL lag, cardinality rejection, query scanned bytes, no-data age and alert transition delay separately.

Cardinality is the product of distinct values across labels, not the number of label keys. A metric with region=4, service=20, and instance=500 already produces 40,000 series; adding a request ID with one million values can multiply this to 40 billion. Reject or quarantine a new series when a tenant budget is exhausted, allow-list bounded dimensions, and keep user/session/request identifiers in logs or traces. A fingerprint collision must compare the canonical label set rather than aliasing identities.

Bound label combinations before creating series. region × service × instance / 4 × 20 × 500 / 40,000 / Accept within budget; Add request_id / 40,000 × 1,000,000 / 40,000,000,000 / Reject or move to logs; Tenant series cap / Configured per tenant / Budgeted / Reject and alert
Bound label combinations before creating series.
Read the diagram

Combination / Input cardinality / Potential series / Action; region × service × instance / 4 × 20 × 500 / 40,000 / Accept within budget; Add request_id / 40,000 × 1,000,000 / 40,000,000,000 / Reject or move to logs; Tenant series cap / Configured per tenant / Budgeted / Reject and alert

Open original
Bound label combinations before creating series
Bound label combinations before creating series. region × service × instance / 4 × 20 × 500 / 40,000 / Accept within budget; Add request_id / 40,000 × 1,000,000 / 40,000,000,000 / Reject or move to logs; Tenant series cap / Configured per tenant / Budgeted / Reject and alert

Bound label combinations before creating series.

Alert evaluation walks a durable shard cursor over due rules. Claim shard ownership with a monotonically increasing fencing epoch; a replacement cannot accept writes from an old owner. Persist pending_since, the latest evaluation timestamp/watermark, and transition ID with each state change. Ignore an evaluation older than the stored watermark. A replay at the same timestamp is idempotent. Late samples inside the two-minute window may trigger reevaluation of affected windows, but do not rewind the authoritative current alert state; late-data policy and query freshness are separate from rule scheduling.

Evaluate a window and fence evaluator failover. WAL and samples to Rule scheduler: Expose the latest committed sample watermark; Rule scheduler to Fenced evaluator: Assign due shard with owner epoch 7; Fenced evaluator to Alert state and outbox: Persist pending_since and evaluation watermark atomically; Fenced evaluator to Alert state and outbox: Emit one transition ID when the for-window reaches firing; Rule scheduler to Fenced evaluator: Replace crashed owner with epoch 8 and resume stored state
Evaluate a window and fence evaluator failover.
Read the diagram

Expose the latest committed sample watermark; Assign due shard with owner epoch 7; Persist pending_since and evaluation watermark atomically; Emit one transition ID when the for-window reaches firing; Replace crashed owner with epoch 8 and resume stored state

Open original
Evaluate a window and fence evaluator failover
Evaluate a window and fence evaluator failover. WAL and samples to Rule scheduler: Expose the latest committed sample watermark; Rule scheduler to Fenced evaluator: Assign due shard with owner epoch 7; Fenced evaluator to Alert state and outbox: Persist pending_since and evaluation watermark atomically; Fenced evaluator to Alert state and outbox: Emit one transition ID when the for-window reaches firing; Rule scheduler to Fenced evaluator: Replace crashed owner with epoch 8 and resume stored state

Evaluate a window and fence evaluator failover.

Final topology: durable ingest and bounded readers. Agent and scrape gateway / Sample source and target-health inventory / Batch size and clock-skew limit; Ingest API and WAL / Accepted batch and series identity / Per-tenant series cap; quorum acknowledgment; Head and immutable blocks / Authoritative raw sample history / Two-minute mutable lateness window; retention tiers; Query and alert workers / Derived read and state transitions / Range/scan budget; one-minute evaluation
Final topology: durable ingest and bounded readers.
Read the diagram

Component / Authority and responsibility / Bound or freshness contract; Agent and scrape gateway / Sample source and target-health inventory / Batch size and clock-skew limit; Ingest API and WAL / Accepted batch and series identity / Per-tenant series cap; quorum acknowledgment; Head and immutable blocks / Authoritative raw sample history / Two-minute mutable lateness window; retention tiers; Query and alert workers / Derived read and state transitions / Range/scan budget; one-minute evaluation

Open original
Final topology: durable ingest and bounded readers
Final topology: durable ingest and bounded readers. Agent and scrape gateway / Sample source and target-health inventory / Batch size and clock-skew limit; Ingest API and WAL / Accepted batch and series identity / Per-tenant series cap; quorum acknowledgment; Head and immutable blocks / Authoritative raw sample history / Two-minute mutable lateness window; retention tiers; Query and alert workers / Derived read and state transitions / Range/scan budget; one-minute evaluation

Final topology: durable ingest and bounded readers.

Late samples and evaluator crash recovery. Agent to WAL and block store: Submit an event within the declared late window; WAL and block store to Evaluator owner: Commit it with event time and ingest watermark; Alert state and notification relay to Evaluator owner: Evaluator A crashes after durable state/outbox transaction; Evaluator owner to Alert state and notification relay: Owner B claims next epoch and resumes after persisted watermark; Alert state and notification relay to Alert state and notification relay: Relay retries transition delivery with the same transition ID; Alert state and notification relay to Alert state and notification relay: Deduplicate notification intent; never reevaluate an older window as current
Late samples and evaluator crash recovery.
Read the diagram

Submit an event within the declared late window; Commit it with event time and ingest watermark; Evaluator A crashes after durable state/outbox transaction; Owner B claims next epoch and resumes after persisted watermark; Relay retries transition delivery with the same transition ID; Deduplicate notification intent; never reevaluate an older window as current

Open original
Late samples and evaluator crash recovery
Late samples and evaluator crash recovery. Agent to WAL and block store: Submit an event within the declared late window; WAL and block store to Evaluator owner: Commit it with event time and ingest watermark; Alert state and notification relay to Evaluator owner: Evaluator A crashes after durable state/outbox transaction; Evaluator owner to Alert state and notification relay: Owner B claims next epoch and resumes after persisted watermark; Alert state and notification relay to Alert state and notification relay: Relay retries transition delivery with the same transition ID; Alert state and notification relay to Alert state and notification relay: Deduplicate notification intent; never reevaluate an older window as current

Late samples and evaluator crash recovery.

Operations and practice

SLIs: accepted-sample WAL acknowledgment latency and rejection rate; ingest-to-query freshness; active series and cardinality rejections per tenant; query p95/scanned bytes; block compaction lag; rule evaluation lag; and notification transition-to-delivery latency. Overload controls: reject oversized batches, cap active series and label dimensions, limit query range/series/concurrency/scanned bytes, and shed dashboards before delaying the durable WAL. Never silently sample away alert inputs without exposing the policy. Recovery: restore a replica from verified immutable blocks, replay WAL after the block watermark, rebuild postings from block metadata, and resume rule shards at the last committed evaluation watermark under a newer epoch. Access: tenant scope is mandatory for ingest, query, rule administration, and notification destinations; redact sensitive label values in logs. Dominant cost: sample volume multiplied by retention and replication; uncontrolled cardinality also amplifies index and query costs.

Practice prompt: Design a monitoring platform for 100,000 hosts at 15-second intervals, 15-day raw retention, one-minute alerts, and a strict per-tenant series quota. Follow-up: one tenant adds a request ID label and an evaluator dies during a firing transition. Rubric: derive ingest and storage pressure; canonicalize and quota labels; define late/future timestamp semantics; preserve mergeable histogram counts rather than averaging p95; fence evaluators and atomically persist alert state plus transition intent; distinguish no data from zero; name freshness, scan, and notification limits. The invariant is that every admitted sample has one tenant-scoped series identity, and each alert transition is monotonic, durable, and delivered with a stable deduplication key.

Exercise: Instance A has 100 requests mostly below 100 ms; B has 100 mostly near 500 ms. Is the average of their p95 values a valid combined p95?

Show answer and explanation

Answer: No. Aggregate compatible bucket counts and estimate from the combined distribution, as above, or use the raw observations. The linear estimate reflects bucket granularity and must be presented as such.

Prometheus storage and histogram practices document primary storage/query concepts used here.

Requirement trace and verification

RequirementImplementing design blockVerification link
R1 — Complete the primary user journey within the stated scope.P01–P04; P09–P10.V1 — Exercise the successful journey and the excluded/boundary case stated in the scope.
R2 — Preserve the problem's authoritative data invariant under concurrency.P05–P06; P11–P12; DD1.V2 — Run the race/replay case below and assert the invariant at the durable authority.
R3 — Meet the declared scale and API behavior without unbounded work.P05–P08; P13–P14; relevant overload deep dives.V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity.
R4 — Recover from the named failure without losing or duplicating the user-visible outcome.P15–P16; deep dives; Operations contract.V4 — Add high-cardinality labels, delay samples, and fail an evaluator; dashboards and alert behavior honor documented freshness and limits.

Operational contract

AreaDecision and signals
SLIsIngestion lag; query p99; cardinality growth; late-sample rate; rule evaluation lag; alert delivery lag.
Overload limitsEnforce label/cardinality quotas, per-tenant ingest budgets, query range/series caps, and bounded alert workers.
RecoveryReplay WAL/checkpoints; restore index/chunk metadata; reevaluate alert windows after evaluator failover.
Access controlsRestrict tenant labels and query scope; separate metrics credentials and prevent secret-bearing labels.
Dominant costTime-series retention/replication, index cardinality, and query compute.

Senior-level interviewer follow-ups

Question: A query requests a percentile across instances. Why can't you average each instance's p95?

Show answer and explanation

Answer: Percentiles are not composable by averaging. Merge compatible histogram buckets or sketches and calculate the percentile from the combined distribution.

Question: An alert series disappears because a target stopped reporting. How do you distinguish no data from a healthy zero?

Show answer and explanation

Answer: Track expected-target inventory and freshness separately from sample values. Alert evaluation needs an explicit no-data policy and a watermark for late or missing series.

A 60-second design answer

I would validate and normalize labels at ingestion, append samples to partitioned time-series blocks, and keep recent data hot with rollups for older ranges. Queries enforce time and cardinality limits; percentiles merge distributions rather than averaging percentiles. Alert rules use explicit no-data and late-sample policies. I would track ingest lag, series cardinality, query cost, retention, and alert evaluation delay.

Time Series Databases Flink

Technical references

Kafka processing and external-sink boundaries.

PostgreSQL transaction isolation and concurrent updates.

Merge observations rather than percentile answers

Use mutually exclusive latency buckets <=10, (10,100], >100 ms. Instance A counts [90,9,1]; B counts [0,90,10]. Merge counts to [90,99,11], total 200. The 99th-percentile rank is 198 under a nearest-rank convention, which lies in >100 ms. The exact value is unknown from these buckets; report the bucket bound/estimator, not an invented precise percentile.

Contract / pseudocode
A buckets: 90,9,1
B buckets: 0,90,10
merged: 90,99,11; total 200
p99 rank 198 -> >100 ms bucket; no exact sample value known
Instance A buckets: 90,9,1; Instance B buckets: 0,90,10; Merged counts: 90,99,11; total 200; Nearest-rank p99: rank 198 -> >100 ms bucket; Exact latency unknown; missing telemetry is not zero
Merge observations rather than percentile answers
Read the diagram

Instance A buckets: 90,9,1; Instance B buckets: 0,90,10; Merged counts: 90,99,11; total 200; Nearest-rank p99: rank 198 -> >100 ms bucket; Exact latency unknown; missing telemetry is not zero

Open original
Merge observations rather than percentile answers
Instance A buckets: 90,9,1; Instance B buckets: 0,90,10; Merged counts: 90,99,11; total 200; Nearest-rank p99: rank 198 -> >100 ms bucket; Exact latency unknown; missing telemetry is not zero

Merge observations rather than percentile answers

Cumulative histograms need their own compatible merge convention; do not add them as though they were mutually exclusive. Averaging instance p99s discards distribution weights. Missing collector samples remain absence, not zero errors; alert on freshness separately. Counter reset, late samples and clock skew need defined rate/window treatment. Label cardinality, retention and query fanout are bounded per tenant/metric.

Show answer and explanation

Answer: A collector outage can create a deceptively quiet chart. Alert state needs missing-data policy, versioned evaluation and deduped delivery rather than automatically declaring recovery.

Decision review: Metrics Monitoring

Metrics Monitoring: What it is

A monitoring design ingests timestamped observations, computes meaningful aggregates and evaluates alert state under missing-data rules.

Metrics Monitoring: Why it is needed

Unbounded label cardinality, average-of-percentile errors and missing samples interpreted as zero can hide incidents.

Metrics Monitoring: When to use it

Use bounded series identity and mergeable statistics when aggregating a fleet. Define counter resets, timestamp policy and data coverage.

Metrics Monitoring: How to use it

Store compatible histogram buckets or other declared distributions, merge observations rather than percentile answers, and preserve freshness/absence information through rollups and alert evaluation.

Metrics Monitoring: Compare an alternative

Coarser rollups lower query cost while losing temporal detail. Approximate distributions have an error contract; neither option justifies silently filling missing observations with zero.

Metrics Monitoring: Worked decision exercise

The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.

Instance A has 100 requests and p99 near 20 ms; B has 10,000 requests and p99 near 200 ms. Averaging 20 and 200 gives 110 ms but cannot establish the combined p99. Compatible bucket counts retain the information needed for a defined estimate.

Metrics Monitoring: A: 100 requests; B: 10,000 requests; Mean of separate p99 values is not fleet p99; Merge compatible observation distributions; Missing telemetry is not a measured zero
Metrics Monitoring: a concrete state and recovery trace under the exercise assumptions.
Read the diagram

A: 100 requests; B: 10,000 requests; Mean of separate p99 values is not fleet p99; Merge compatible observation distributions; Missing telemetry is not a measured zero

Open original
Metrics Monitoring: worked example
Metrics Monitoring: A: 100 requests; B: 10,000 requests; Mean of separate p99 values is not fleet p99; Merge compatible observation distributions; Missing telemetry is not a measured zero

Metrics Monitoring: a concrete state and recovery trace under the exercise assumptions.

Should an alert recover when the collector disappears and sends no more errors?

Show answer and explanation

Answer: Not merely from absence. Apply the declared missing-data policy and monitor telemetry freshness separately. A measured zero and no sample are different states; a counter reset also needs its own rate rule.

Metrics Monitoring: Check the design

Test unequal instance weights, compatible bucket merging, counter resets and telemetry outages. Budget active series per label scheme and observe dropped/admitted measurements.

Screenshot variant: Monitoring evidence beyond a successful query

The original metrics lesson remains the APIs, series model, histogram and alerting baseline. This workshop deepens sample/reset/duplicate meaning, bounded query evidence, missing-data state, ordered evaluator failover and notification recovery. It does not change course-completion or quiz records.

Deep dive: missing samples must not resolve an active incident

The baseline covers series storage, mergeable observations and durable alerts. This workshop makes sample identity/temporality, reset handling, bounded cardinality and high-availability alert transitions explicit. It is distinct from the shared SLO foundation: the question here is how to build the monitoring pipeline that preserves those measurements and incidents during replay, collector loss and evaluator failover.

Define what a sample means before deduplicating it

ContractIdentity/meaningUnsafe operation
GaugeObserved value at a scoped series/time/source boundarySum two HA copies of the same observation
Cumulative counterMonotonic contribution within one declared process/reset epochTreat a restart's lower value as a negative request rate
Delta sampleContribution for a declared interval/event identityAdd every transport retry as new work
Histogram/sketchDistribution with schema, units and temporalityMerge incompatible buckets or average percentile answers

A series key includes trusted tenant/resource and a bounded label set. Define timestamp precision, writer/HA identity, sequence/reset epoch and duplicate-conflict policy. This exercise deduplicates the same observation identity/payload and quarantines conflicting values; genuinely distinct sources remain distinct unless the HA policy establishes equivalence. Dropping the replica label and summing blindly can double a counter when both collectors observed the same target.

For a cumulative counter, values 100 then 130 contribute 30 in one epoch. A new process epoch beginning at 5 cannot be subtracted from 130 as −125. Decide whether enough metadata permits counting the new epoch's initial five from a known zero, or whether that boundary is unknown; do not silently invent a precise cross-reset rate. Apply reset-aware per-series calculations before aggregation so one source's reset is not hidden by another source's increase.

Histograms need compatible units, bucket boundaries and temporality. Cumulative buckets versus disjoint bucket counts are different representations; convert under an explicit rule before merging. Rollups preserve declared count/sum/distribution evidence for a time range, not every exact raw quantile. Weighted rates/ratios need the corresponding populations; a mean of instance percentages or percentile values can misstate a global outcome.

Bound cardinality and query work without fabricating health

A metric with 100 services, 20 regions, 10 statuses and one million arbitrary request IDs can theoretically create twenty billion label combinations if fully populated. The actual populated set matters, but unbounded identifiers remain an uncontrolled growth path. Apply per-tenant active-series/label/ingest limits and explicit rejection/drop evidence rather than silently removing labels and combining unrelated series as if semantics were unchanged.

A one-minute chart over ten million series can require enormous scan/merge work despite a small response. Budget query range, series count, step size, scanned bytes and concurrency; use documented rollup precision and mark partial/time-limited results. A dashboard query that returned no series after quota rejection does not prove a zero error count. Monitor the monitoring pipeline's acceptance, freshness, query completeness and drop/cardinality limits independently of the service metric itself.

Persist the rule state and the data-quality decision

Contract / pseudocode
sample(tenant, series, source_epoch, observation_id, event_time, value, schema)
rule(id, version, expression, required_data_age, pending_duration,
     no_data_policy, late_correction_policy)
alert_state(rule_id, rule_version, subject, evaluation_position,
            evaluator_epoch, state, pending_since, incident_id)
alert_transition(incident_id, transition_sequence, disposition, outbox_id)

Separate good evidence, bad evidence and unknown/incomplete data. For this exercise, a firing incident remains firing-with-data-unknown while required telemetry is missing; unknown does not create a recovery notification. A separate missing-data alert can indicate collector/target failure. For a pending condition, unknown breaks the proof of continuous bad evidence and restarts the pending timer; this is an explicit conservative policy, not a universal alert-engine default.

Metrics unknown-data recovery: an incident is firing; required samples become stale; evaluation records data unknown; no recovery transition is emitted; recovery waits for fresh good evidence
Absence of bad samples is different from evidence of healthy service.
Read the diagram

An incident is firing under a known rule → Required samples become stale or missing → Evaluation records data unknown → No recovery transition is emitted → Recovery waits for fresh good evidence

Open original
Metrics Monitoring: recovery decision
Metrics unknown-data recovery: an incident is firing; required samples become stale; evaluation records data unknown; no recovery transition is emitted; recovery waits for fresh good evidence

Absence of bad samples is different from evidence of healthy service.

Persist evaluation position, rule version and state transitions with notification intent. Two HA evaluators must share/fence one transition authority or otherwise enforce an equivalent deduplication contract. A current evaluator's delayed older evaluation must not regress newer alert state; compare evaluation position/revision as well as owner epoch. Replaying a committed transition resolves the same incident/transition outbox identity instead of sending a new incident for every evaluator restart.

Rule rollout and notification recovery need their own contracts

Changing thresholds or pending duration is a rule-version transition. State whether pending history carries over, resets, migrates or is separately evaluated. This exercise starts new pending proof for a changed rule, and relates any old incident's supersession/recovery under an explicit administrative transition; it does not silently erase an old incident as healthy. An unknown enum or failed expression evaluation becomes an observable evaluation failure, not a default zero.

A state transition committed with its outbox can be published more than once after a lost acknowledgement. Retain stable incident/transition identity through notification retries, group/reminder policy and silences. Local alert-state dedupe cannot guarantee exactly-once paging at an arbitrary external provider; query/retry its original supported operation identity or expose uncertainty under the notification contract. Silencing delivery does not prove the monitored condition resolved.

Late samples may revise historical charts. Decide whether finalized alert evaluations are immutable or can receive audited corrections; this exercise does not retroactively replay old notification transitions merely because a historical rollup changed. Store enough rule/data/version context to explain an incident. A current chart recomputed with a newer rule is not automatically the evidence that triggered the original page.

Work one bounded alert history

With a two-minute continuous-bad pending requirement, bad evidence at minute 0 starts pending; unknown at minute 1 breaks that proof. Bad evidence at minute 2 starts a new timer, and continuous fresh bad evidence through minute 4 can fire. Once firing, missing samples at minute 5 do not resolve it. Fresh good evidence at minute 6 can produce one recovery transition under the chosen rule. Replayed or stale evaluations cannot create another firing/recovery pair.

Track sample rejection/duplication/reset ambiguity, oldest required-data age, active cardinality, query partials, evaluation lag, unknown conditions, transition conflicts and notification uncertainty. A monitoring service that fails silently can make every downstream dashboard look reassuring; its own diagnostic path needs a bounded independent health signal and an owner for incomplete evidence.

Metrics assessment: preserve the incident's evidence

Question: A cumulative counter restarted from 130 to 5 without enough reset metadata. Is −125 a valid request-rate contribution?

Show answer and explanation

Answer: No. Detect/reset-scope the series and apply the declared reset/unknown policy before aggregation; a decrease is not negative traffic.

Question: A firing rule sees no fresh samples. Should it immediately emit recovery because the query found no bad values?

Show answer and explanation

Answer: Not under this policy. Preserve the active incident with data-unknown status and wait for fresh good evidence or an explicit administrative disposition.

Question: A second evaluator or outbox relay retries the same committed incident transition. Should it create another independent page identity?

Show answer and explanation

Answer: No. Fence state progress and preserve incident/transition identity. External provider uncertainty remains a separate delivery boundary.

Score one point for sample/temporality/reset semantics, bounded cardinality/query completeness, explicit unknown/pending policy, ordered versioned alert transitions and replay-safe notification evidence. Compare SLOs and Observability, Time and Identifiers and Notification Delivery.

30:00Self-guided practice timer
The timer resets when you leave this page. Save your design separately.
Your challenge

Why is averaging the p99 latency from ten instances not the service-wide p99?

Your design draft

Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.

Open solution review

Self-review checklist

Self-guided practice. Automated AI feedback and code execution are not connected.