Skip to content

Design a Metrics Monitoring and Alerting System

Advanced 79 min read Part 17 of 18

Design a Datadog or Prometheus-style platform that ingests 5M metric samples per second, serves dashboards in seconds and fires alerts within a minute.

The Problem#

A metrics monitoring and alerting system collects numbers that describe how computers and software are behaving, stores them over time, draws them on dashboards, and wakes someone up when a number goes wrong. CPU usage of a server, memory in use, requests per second to an API, the 99th-percentile latency of a checkout service, the length of a queue: each of these is a metric, measured every few seconds on every machine. Products in this space include Datadog, Prometheus with Grafana, AWS CloudWatch, New Relic and Google Cloud Monitoring.

This is an infrastructure design question. The users are engineers, and the system is what they rely on during an outage, so it must keep working when everything else is breaking. The hard parts are:

  • A firehose of tiny writes. A large fleet emits millions of data points per second. Each is tiny (a timestamp and a number), but the volume is relentless and never pauses.
  • Fast reads over long ranges. An engineer opens a dashboard that shows two weeks of latency for 500 hosts and expects it in a couple of seconds.
  • Timely, reliable alerts. An alert must fire within about a minute of a problem starting, and must not be lost or fire a thousand times.
  • Cardinality. Every distinct combination of labels (host, region, endpoint, status code) creates a new time series. A careless label, such as a user id, can multiply the number of series by millions and take the whole system down.

Analogy. Think of the monitors in a hospital intensive care unit. Every patient is wired to sensors that measure heart rate, blood pressure and oxygen every few seconds. The readings scroll across a screen by the bed (the dashboard), and the history is kept so a doctor can see how the night went (the time-series storage). Each monitor has thresholds set by the doctor: if oxygen drops below 90% for more than a minute, an alarm sounds and a nurse is paged (the alert rule and the notification). A good unit avoids two failures. It must never miss a real emergency, and it must not ring so often for nothing that the nurses learn to ignore it. It also has to keep working when the power flickers, because that is exactly when it is needed. A metrics platform is the same thing for a fleet of servers.

Background: a few monitoring terms#

  • Metric: a named measurement, such as http_requests_total or cpu_usage_percent.
  • Labels (or tags): key-value pairs that say which thing was measured: host="web-17", region="eu-west", status="500".
  • Time series (series): one metric name plus one exact set of label values, for example http_requests_total{host="web-17", status="500"}. A series is a sequence of points over time.
  • Sample (data point): one (timestamp, value) pair in a series. Usually a 64-bit timestamp and a 64-bit float.
  • Cardinality: the number of distinct series. It is the product of the number of values of each label, in the worst case.
  • Metric types:
    • A counter only goes up (total requests, total errors). You usually look at its rate of increase.
    • A gauge goes up and down (memory in use, queue length, temperature).
    • A histogram counts observations into buckets (how many requests took under 10 ms, under 50 ms, under 100 ms...). It lets you estimate percentiles later.
    • A summary computes percentiles on the client and reports them directly. They cannot be combined across machines, which matters later.
  • Scrape: the act of a collector pulling the current metric values from a service over HTTP.
  • Resolution (or step): the spacing between points, such as every 10 seconds.
  • Downsampling (rollup): replacing fine-grained old data with coarser summaries, such as 1-minute or 1-hour aggregates.
  • Alert rule: a condition over metrics, such as "error rate above 5% for 5 minutes".
  • Service level objective (SLO): a target for reliability, such as "99.9% of requests succeed over 30 days". Modern alerting often pages on how fast the SLO's error budget is being used up.

See Observability: Logs, Metrics and Traces for how metrics fit beside logs and traces, and Time-Series Databases for the storage technology in depth.

Clarifying Questions#

QuestionAssumed answerWhy it matters
What is in scope: metrics only, or also logs and traces?Metrics only. Logs, full-text search and distributed tracing are separate systemsLogs and traces have very different volume and query shapes
How big is the fleet?500,000 servers, each emitting about 100 metrics every 10 secondsGives 5 million samples per second, which drives the whole design
Who are the users? Internal, or a multi-tenant product?Internal teams of one large company first. Multi-tenant SaaS is an extensionMulti-tenancy adds per-tenant limits and isolation
What kinds of queries?Dashboards with filters, aggregations (sum, average, percentiles) and time ranges from minutes to monthsNeeds fast aggregation over many series and long ranges
How fast must dashboards load?A few seconds, even for ranges of days or weeksRequires downsampled data and query caching
How fast must alerts fire?Under 1 minute from the metric being emitted to the alert firingBounds the ingestion delay and the rule evaluation interval
How are alerts delivered?Email, Slack, PagerDuty and webhooksA notification pipeline with routing, deduplication and retries
How long do we keep data?Full resolution for days to weeks, coarser data for a year or moreDrives storage size and the downsampling design
Do we need anomaly detection with ML?No. Threshold and rate rules onlyKeeps the alert engine deterministic
Must we handle late or out-of-order data?Yes. Networks delay data, and agents retryStorage and alerting must tolerate late samples
Push or pull collection?Support both: pull for long-running services, push for short-lived jobs and edge devicesChanges the collection tier and how we detect dead targets
Multiple regions?Single region for the core design. Multi-region is an extensionAvoids cross-region replication in the core answer

Requirements#

Functional#

  1. Ingest metrics (CPU, memory, latency, custom counters and histograms) from services and servers.
  2. Query and visualise metrics on dashboards, with label filters, aggregations and time ranges.
  3. Define alert rules with thresholds over time windows, for example "alert if p99 latency is above 500 ms for 5 minutes".
  4. Notify the right people when alerts fire and when they resolve, by email, Slack, PagerDuty or webhook.

Out of scope: log aggregation and full-text search, distributed tracing, ML-based anomaly detection, multi-region replication in the core design, and strong consistency for dashboards.

Non-Functional#

  • Ingest scale: about 5 million samples per second from 500,000 servers, with headroom for spikes.
  • Query latency: dashboard queries return in a few seconds (p95 under 2 seconds for common panels), even for ranges of days or weeks.
  • Alert latency: under 1 minute from emission to the alert firing.
  • Availability: the system is highly available. Dashboards can be eventually consistent (a few seconds behind). Alert evaluation must be reliable, because missed alerts mean undetected outages.
  • Late and out-of-order data: handled gracefully, without data loss or false alerts.
  • Cost efficiency: storage per sample must be small, because the raw volume is enormous.

What matters most. The alerting path matters more than the dashboard path. A slow dashboard is annoying. A missed alert can turn a five-minute blip into an hour-long outage. So when they compete, we protect ingestion and alert evaluation first, and let dashboards degrade.

Why "under a minute" and not "instantly"? Most useful alerts are on trends, not single points: an average over a few minutes, a rate over a window, a percentile over many requests. One bad sample is usually noise. So an alert typically needs a minute or more of data before it can sensibly fire, and a pipeline delay of 10 to 30 seconds is not the limiting factor. When a team truly needs near-instant detection, they usually design a special metric rather than a faster pipeline. A well-known trick is to measure time since the last success. A high-volume business emits orders constantly, so "seconds since the last order" sits at a tiny, stable value, and any jump is a reliable, immediate signal that orders have stopped. Designing metrics like this is an art. It is rarely the focus of an interview, but mentioning it shows you understand what alert latency really depends on.

Capacity Estimation#

Round numbers, as on a whiteboard (see Back-of-the-Envelope Estimation).

Ingest rate.

  • 500,000 servers × 100 metrics each = 50 million active series from hosts alone. Application metrics with labels (endpoint, status code, histogram buckets) often add several times more. Plan for 100 to 200 million active series.
  • Each series reports every 10 seconds. 50 million / 10 = 5 million samples per second for host metrics. That is our design point. Peaks during deploys or incidents (more series, retries, bursty agents) can be 1.5 to 2 times higher.

Bytes on the wire.

  • A sample with its labels, sent individually in a text or JSON format, is about 100 to 200 bytes: the metric name and labels dominate, the timestamp and value are only 16 bytes.
  • 5 million × 150 bytes ≈ 750 MB per second, call it about 1 GB per second of raw ingest. That is the crux of the problem. Batching and compression on the wire (Protocol Buffers plus Snappy, as in Prometheus remote write) cut this several-fold, because labels repeat heavily within a batch.

Storage.

  • Samples per day: 5 million × 86,400 ≈ 430 billion samples per day.
  • Stored naively, as a row with full labels (as in a plain relational table), at 50 to 100 bytes per sample: 20 to 40 TB per day. Unworkable.
  • Stored the way time-series databases do, with labels kept once per series and samples compressed with delta-of-delta timestamps and XOR-encoded floats: about 1.4 bytes per sample on typical data (the figure reported in Facebook's Gorilla paper). 430 billion × 1.4 bytes ≈ 600 GB per day, about 4 TB per week and 18 TB per month at full resolution.
  • With replication factor 3 for durability, that is about 1.8 TB per day of disk across the cluster.

Downsampled storage. If we keep 10-second data for 15 days, 1-minute rollups for 3 months and 1-hour rollups for 2 years:

TierPoints per series per dayRetentionApproximate size
Raw, 10 s8,64015 daysabout 9 TB
1-minute rollup (min, max, sum, count)1,440 × 4 values90 daysabout 40 to 50 TB
1-hour rollup (min, max, sum, count)24 × 4 values2 yearsabout 5 to 10 TB

Each rollup point stores four values and compresses less well than raw data (about 2 bytes per value), so a day of 1-minute rollups is roughly as large as a day of raw data, even though it has 6 times fewer points. The saving comes from what we no longer keep: raw data is dropped after 15 days. Rollups that keep only sum and count (enough for averages and rates) would be half the size. The total stays in the tens of terabytes, which fits easily in object storage at low cost.

Series index. Each active series needs an entry in the label index: its labels (perhaps 200 to 500 bytes) and postings-list entries. At 150 million active series and roughly 1 KB of index memory each, that is around 150 GB of index memory across the cluster. This is why cardinality is the real scaling limit: the number of samples is handled by compression, but every new series costs memory.

Queries.

  • Assume 20,000 engineers, 5,000 dashboards open at peak, each with 10 to 20 panels, refreshing every 30 to 60 seconds: roughly 2,000 to 5,000 panel queries per second.
  • A panel showing one week of a metric across 500 hosts at 1-minute resolution reads 500 series × 10,080 points ≈ 5 million points. From raw 10-second data it would read 30 million. Downsampling and caching decide whether this takes 200 ms or 20 seconds.

Alert rules.

  • Assume 500,000 alert rules (many generated from templates, one per service per condition), each evaluated every 30 to 60 seconds: about 10,000 to 20,000 rule evaluations per second. Each evaluation is a small query over recent data. Rule evaluation is therefore a significant query load in its own right, and it must be isolated from dashboard traffic.

Summary.

QuantityEstimateConsequence
Samples per second5M, peaks about 10MBatch, partition and buffer ingestion
Raw ingest bandwidthAbout 1 GB/s before compressionCompress on the wire, batch per series
Active series100M to 200MIndex memory and cardinality limits
Stored per dayAbout 600 GB compressed (before replication)Time-series compression is mandatory
Panel queries per second2k to 5kDownsampling, query caching, fan-out
Rule evaluations per second10k to 20kDedicated, sharded rule evaluators

Core Entities#

  • Metric: a name and type (counter, gauge, histogram), with optional help text and unit.
  • Series: a metric plus a full set of label values. Identified internally by a series id, often a hash of the sorted labels.
  • Sample: a timestamp and a value belonging to one series.
  • Dashboard and panel: a saved layout of queries and visualisations.
  • Alert rule: a query expression, a threshold or condition, a duration (for 5 minutes), a severity and labels used for routing.
  • Alert instance: one firing (or pending) occurrence of a rule for one set of labels, for example "HighErrorRate for service=checkout". It has a state (pending, firing, resolved), start time and the value that triggered it.
  • Notification policy and contact point: who gets notified, how (email, Slack, PagerDuty, webhook), grouping and repeat intervals.
  • Silence: a time-bounded mute for alerts matching certain labels, used during maintenance.

API Design#

Ingestion (push). Agents or services send batches:

POST /v1/metrics/write
Content-Type: application/x-protobuf
Content-Encoding: snappy

WriteRequest {
  series: [
    { labels: {__name__: "http_requests_total", service: "checkout",
               host: "web-17", status: "500"},
      samples: [ {t: 1764756000000, v: 18231}, {t: 1764756010000, v: 18240} ] },
    ...
  ]
}
→ 204 No Content    (or 429 Too Many Requests with Retry-After when throttled)

Ingestion (pull). Each service exposes a plain-text endpoint that collectors scrape:

GET /metrics
# TYPE http_requests_total counter
http_requests_total{service="checkout",status="200"} 9182311
http_requests_total{service="checkout",status="500"} 18240

Query.

GET /v1/query_range?expr=sum by (region) (rate(http_requests_total{status="500"}[5m]))
                    &start=2026-12-01T00:00:00Z&end=2026-12-03T00:00:00Z&step=60s
→ { "series": [ { "labels": {"region": "eu-west"}, "points": [[t, v], ...] }, ... ] }
  • expr is a query in a PromQL-like language: select series by labels, apply functions such as rate, and aggregate with sum by (...).
  • step is the resolution of the result. The server can raise it to match the downsampled tier it reads from. A two-week chart 1,000 pixels wide never needs more than about 1,000 points per series.

Alert rules and notifications.

POST /v1/alert-rules
{ "name": "CheckoutHighErrorRate",
  "expr": "sum(rate(http_requests_total{service=\"checkout\",status=~\"5..\"}[5m]))
           / sum(rate(http_requests_total{service=\"checkout\"}[5m])) > 0.05",
  "for": "5m", "severity": "page",
  "labels": { "team": "payments" },
  "annotations": { "summary": "Checkout 5xx above 5%", "runbook": "https://..." } }

POST /v1/silences   { "matchers": {"service": "checkout"}, "startsAt": ..., "endsAt": ..., "comment": "deploy" }
GET  /v1/alerts?state=firing

Outgoing notifications are webhooks and integrations (Slack API, PagerDuty Events API, SMTP), not part of our public API.

High-Level Design#

We build the system one functional requirement at a time, then assemble the full picture.

1) The platform can ingest metrics from services#

Metrics start on the machines being monitored. An agent runs on each host (or as a sidecar or library inside each service). It reads host statistics (CPU, memory, disk, network) and exposes or forwards application metrics. From there, there are two ways to get data into the platform:

  • Pull (scrape): collectors discover targets (from a service registry, Kubernetes, or a cloud API) and fetch each target's /metrics endpoint every 10 seconds. This is how Prometheus works.
  • Push: agents batch samples and send them to an ingestion endpoint. This is how Datadog agents, StatsD, CloudWatch agents and the OpenTelemetry protocol (OTLP) usually work.

We support both, with a collector tier that does the scraping and accepts pushes, so the rest of the pipeline sees one uniform stream (Deep Dive 1 compares the two). Collectors validate samples, apply label rules (drop or rename labels, enforce limits), batch them, and write to Kafka.

Why put Kafka in the middle, instead of writing straight into the database?

  • Buffering spikes. During an incident, metric volume jumps, and that is exactly when the storage tier is most likely to be slow. Kafka absorbs the burst and lets the storage catch up, rather than forcing collectors to drop data.
  • Decoupling. Storage nodes can be restarted, upgraded or rebalanced without losing samples. Collectors only need Kafka to be up.
  • Multiple consumers. The same stream feeds the storage writers, a streaming alert evaluator (Deep Dive 6) and any downstream analytics, each reading at its own pace.

See Apache Kafka in Practice. On the other side of Kafka, ingester processes consume samples and write them into the time-series database (TSDB).

2) Users can query and visualise metrics on dashboards#

A query service accepts expressions such as sum by (region) (rate(http_requests_total{status="500"}[5m])) over a time range. It:

  1. Parses the expression and finds which series match the label selectors, using the TSDB's label index (an inverted index from each label value to the series that have it).
  2. Determines which time partitions and which storage nodes hold those series.
  3. Fetches the samples (or pre-aggregated rollups for long ranges), applies functions such as rate, and aggregates across series.
  4. Returns one result series per group, at the requested step.

A dashboard service (Grafana is the common open-source choice) stores dashboard definitions in a small relational database and calls the query service for each panel.

A plain version (query engine straight to the TSDB) works for small ranges. For weeks of data across many hosts, it is too slow. The query frontend and rollups fix that (Deep Dive 5): the frontend splits long queries into day-sized pieces, serves the unchanged past pieces from a results cache, and the engine reads coarse rollups for long ranges instead of raw samples.

3) Users can define alert rules with thresholds#

Alert rules are stored in the config database. A rule evaluator runs each rule on a schedule, every 30 or 60 seconds:

  1. Run the rule's expression as a query over the most recent data.
  2. For each resulting series (for example, one per service), compare the value with the threshold.
  3. Track state per series. A condition that becomes true moves the alert to pending. If it stays true for the rule's for duration (say 5 minutes), the alert moves to firing. When it stops being true, it becomes resolved.
  4. Send firing and resolved alerts to the notification pipeline.

The for duration prevents one noisy sample from waking someone up. Rule evaluation is a heavy, steady query load, so evaluators query the TSDB through a separate path with its own capacity, not the dashboard frontend, so that a burst of dashboard users during an incident cannot slow down alerting.

4) Users receive notifications when alerts fire#

An alert manager turns raw alert events into useful notifications:

  • Deduplication: evaluators resend firing alerts every cycle (so a lost message is repaired). The alert manager notifies once per alert, not once per cycle.
  • Grouping: 200 hosts failing at once should produce one page that says "200 hosts down in eu-west", not 200 pages.
  • Routing: a routing tree decides, from the alert's labels (team, severity, service), which contact points receive it: the payments team's PagerDuty for severity=page, a Slack channel for warnings.
  • Silences and inhibition: silences mute matching alerts during maintenance. Inhibition suppresses dependent alerts: if a whole data centre is down, do not also page for every service in it.
  • Delivery with retries: notifications go through a durable queue to sender workers for email, Slack, PagerDuty and webhooks, with retries and backoff.

PagerDuty-style tools then handle on-call schedules and escalation. Our system integrates with them rather than rebuilding them (the notification-system case covers delivery at scale in depth).

The full high-level design#

Components:

  • Agents and client libraries: expose application metrics on /metrics, collect host statistics, and (in push mode) batch and send samples. Libraries pre-aggregate inside the process: a counter increment is a memory operation, not a network call.
  • Collectors: scrape pull targets found by service discovery, accept pushes, authenticate senders, apply relabelling (drop, rename or hash labels), enforce per-team series and rate limits, and write compressed batches to Kafka.
  • Kafka: the durable buffer between collection and storage, partitioned by a hash of the series labels so that all samples of one series land in one partition, in order. A few days of retention allow replay after storage failures (Deep Dive 2).
  • Ingesters: consume Kafka, append each sample to a write-ahead log and to an in-memory head block per series, and every 2 hours flush the head to an immutable, compressed block on disk. Each series is handled by more than one ingester (replication factor 3) so the loss of one ingester loses nothing.
  • Recent blocks and object storage: blocks older than a few hours are uploaded to object storage (S3 or GCS), which is cheap and effectively unlimited. Ingesters keep only recent data locally.
  • Compactor and downsampler: merges small blocks into large ones (fewer files to search), removes duplicate samples written by replicas, builds 1-minute and 1-hour rollups, and deletes data past its retention (Deep Dive 4).
  • Query frontend: splits long queries by day, caches results for completed days, queues and limits queries per user, and shards big queries across queriers (Deep Dive 5).
  • Queriers: evaluate expressions, fetching recent data from ingesters and older data from store gateways that read blocks in object storage (with cached indexes).
  • Rule evaluators: run alert and recording rules (precomputed queries) on a schedule, sharded so each rule is owned by one evaluator (Deep Dive 6).
  • Alert manager cluster: deduplicates, groups, inhibits, silences and routes alerts. Runs as a small replicated cluster so a single failure does not stop paging (Deep Dive 7).
  • Senders: deliver notifications to email, Slack, PagerDuty and webhooks with retries.
  • Config database: a small relational database (PostgreSQL) for dashboards, alert rules, routing policies, silences and users.

This is, in outline, the architecture of horizontally scalable Prometheus-compatible systems such as Cortex, Grafana Mimir and Thanos, and of commercial platforms. We will refer to the ideas, not to any one product's exact implementation.

Key Flows#

Flow 1: a sample travels from a service to storage#

  1. The collector scrapes the service's metrics endpoint every 10 seconds. The scrape timestamp becomes the sample time.
  2. The service returns its current values for all its series. A counter's value is its running total, not the increase.
  3. The collector applies relabelling rules (for example, drops a debug label), checks the team's series limit, and attaches target labels such as job, instance and region.
  4. It produces a compressed batch to Kafka, keyed by a hash of each series' labels, so each series always lands in the same partition.
  5. Kafka acknowledges after the batch is replicated to in-sync replicas (acks=all).
  6. An ingester that owns that partition consumes the batch.
  7. It appends each sample to its write-ahead log (WAL) and to the series' in-memory chunk, which is compressed as it grows.
  8. Only after the WAL is safely on disk does it commit the Kafka offset. A crash before this point means the batch is consumed again, and duplicate samples (same series, same timestamp, same value) are simply ignored.
  9. Every 2 hours, the head block is cut into an immutable block, written to local disk, and uploaded to object storage.

Flow 2: an engineer loads a two-week dashboard panel#

  1. The browser opens a dashboard with 12 panels. Each panel becomes one range query.
  2. For one panel, the dashboard service asks for 14 days at a 5-minute step.
  3. The frontend splits the range into 14 day-aligned pieces. The 13 complete past days are already in the results cache from earlier views.
  4. It sends only today's piece to a querier.
  5. The querier asks the ingesters for the last 24 hours of the matching series (recent data lives there).
  6. If part of today is older than the ingesters keep, it reads it from the store gateway.
  7. Ingesters return raw samples.
  8. The store gateway returns samples, or 5-minute rollups for the older range.
  9. The querier applies rate and sum by, and returns one small result.
  10. The frontend merges the cached days with today and caches today's piece briefly.
  11. The panel renders. Typical end-to-end time is a few hundred milliseconds, because only one day was computed.

Flow 3: an alert fires and pages the on-call engineer#

  1. The evaluator runs the checkout error-rate rule every 30 seconds.
  2. The query returns 7.2%, above the 5% threshold.
  3. The alert becomes pending. Nobody is notified yet.
  4. The evaluator keeps checking every 30 seconds.
  5. Five minutes later the condition still holds, so the alert becomes firing.
  6. The evaluator sends the firing alert to the alert manager, and resends it every cycle while it keeps firing. Resending makes the path self-healing if a message is lost.
  7. The alert manager deduplicates, waits a short group_wait (30 seconds) to collect related alerts into one group, and applies routing.
  8. One notification for the group is enqueued.
  9. The PagerDuty sender creates an incident with a deduplication key derived from the alert group, so a retried request does not create a second incident.
  10. PagerDuty accepts it and pages the on-call engineer according to their schedule.

Total time from the error starting to the page: about 5 minutes of for duration plus about 1 minute of pipeline and grouping delay. The 5 minutes is a deliberate choice in the rule. The platform's own contribution is under a minute, which is the requirement.

Data Model#

There are two very different kinds of data: the time-series data itself (enormous, append-only, stored in a purpose-built format), and the configuration (small, relational, edited by people). The entity diagram covers both at a logical level.

How time-series data is laid out. This is the important part, and it is not a relational schema.

  • Series identity. A series is identified by its sorted label set, for example {__name__="http_requests_total", host="web-17", service="checkout", status="500"}. The storage engine assigns it a numeric series id (often derived from a hash of the labels), and stores the label set once, not with every sample.
  • Inverted label index. For each label pair, the engine keeps a postings list: the sorted list of series ids that have that label. service="checkout" → [12, 57, 91, ...]. A selector with several labels is answered by intersecting postings lists, exactly like a search engine intersects the documents that contain each word.
  • Chunks. Samples for one series are stored together in chunks of about 120 samples (20 minutes at 10-second resolution in Prometheus' engine), compressed with delta-of-delta timestamps and XOR floats (Deep Dive 3).
  • Blocks. Chunks for all series in one time range (2 hours, later compacted into larger ranges) are packed into an immutable block: a directory with the chunk files, the label index for that range, and metadata (min and max time, number of series, resolution). Blocks are the unit of upload, compaction, downsampling and deletion.

Compare this with the naive relational layout, which a candidate might reach for first:

-- Naive: one row per sample, labels repeated in every row. Do not do this at scale.
CREATE TABLE samples (
  ts          TIMESTAMPTZ NOT NULL,
  metric_name TEXT NOT NULL,
  host        TEXT NOT NULL,
  labels      JSONB,
  value       DOUBLE PRECISION NOT NULL
);
CREATE INDEX ON samples (metric_name, host, ts);

At 430 billion rows per day, each 50 to 100 bytes plus index entries, this is tens of terabytes per day, and every insert updates a B-tree. Even "average CPU of one host over the past hour" means fetching rows scattered across the disk. Time-series engines win by 10 to 100 times on this workload because they store each series' samples contiguously and compressed, and keep labels once.

The configuration schema is ordinary relational data:

CREATE TABLE alert_rules (
  rule_id      BIGSERIAL PRIMARY KEY,
  name         TEXT NOT NULL,
  expr         TEXT NOT NULL,           -- e.g. error ratio > 0.05
  for_seconds  INT  NOT NULL DEFAULT 0,
  eval_seconds INT  NOT NULL DEFAULT 30,
  severity     TEXT NOT NULL,           -- page | ticket | info
  labels       JSONB NOT NULL,          -- used by routing
  annotations  JSONB NOT NULL,          -- summary, runbook URL
  owner_team   TEXT NOT NULL,
  updated_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);
 
CREATE TABLE alert_instances (
  rule_id      BIGINT REFERENCES alert_rules,
  labels_hash  TEXT NOT NULL,           -- identity of the alerting series
  labels       JSONB NOT NULL,
  state        TEXT NOT NULL,           -- pending | firing | resolved
  active_since TIMESTAMPTZ NOT NULL,
  last_value   DOUBLE PRECISION,
  PRIMARY KEY (rule_id, labels_hash)
);
 
CREATE TABLE silences (
  silence_id  UUID PRIMARY KEY,
  matchers    JSONB NOT NULL,           -- {"service": "checkout"}
  starts_at   TIMESTAMPTZ NOT NULL,
  ends_at     TIMESTAMPTZ NOT NULL,
  created_by  TEXT NOT NULL,
  comment     TEXT
);

Design notes.

  • Alert state is persisted. If an evaluator restarts, it reloads pending and firing instances, so a rule that has been pending for 4 minutes does not restart its 5-minute clock (which would delay the page) and firing alerts do not re-notify. Prometheus, for example, keeps this state as a synthetic ALERTS_FOR_STATE series in its own storage for the same reason.
  • Rules are versioned. Teams usually manage rules as code (YAML in a Git repository) and deploy them through CI, with the config database as the deployed copy. That gives review, history and rollback for the rules that wake people up.
  • Silences need expiry. A silence without an end time is how real outages go unnoticed. Require ends_at, and alert on long silences.

Database choice. The time-series data needs a purpose-built engine: Prometheus' TSDB format inside a horizontally scalable system (Cortex, Mimir, Thanos), VictoriaMetrics, M3, InfluxDB, or a managed service. TimescaleDB is a good choice when the volume is moderate and SQL matters. A columnar store such as ClickHouse fits when cardinality is very high (Deep Dive 8). The configuration data is small and relational, so PostgreSQL is the natural choice, replicated for availability. For the general method, see Choosing a Database: A Decision Guide.

StoreWhat it holdsWhy this store
KafkaSamples in flight, 1 to 3 daysBuffer spikes, decouple collection from storage, replay
Ingester memory and local diskHead blocks and WAL, recent hoursFast writes and queries for the freshest data
Object storageImmutable blocks and rollups, months to yearsCheap, durable, unlimited, separate from compute
Cache (Memcached or Redis)Query results, block indexes, chunk cachesFast repeated dashboard queries over old data
PostgreSQLDashboards, rules, alert state, silences, routingSmall relational data edited by people

Deep Dives#

1. Collection: push or pull?#

This is the most classic debate in metrics design, and both sides are used in production at very large scale. A good answer explains the trade-offs and picks per use case.

Pull (scraping). The monitoring system knows the list of targets (from service discovery) and asks each one for its metrics on a fixed interval. Prometheus is the best-known pull system.

Advantages:

  • Health comes for free. If a scrape fails, the system knows the target is down or unreachable. Prometheus records a synthetic up series per target (1 or 0), which is the simplest and most reliable "is it alive?" alert.
  • The monitoring system controls the load. It decides the scrape interval and how many targets each scraper handles, so a misbehaving service cannot flood it by sending too often.
  • Easy debugging. An engineer can open a service's /metrics endpoint in a browser and see exactly what it exposes.
  • Consistent timing. Samples arrive on a regular grid, which compresses well (delta-of-delta of timestamps is mostly zero).

Disadvantages:

  • Targets must be reachable. The scraper needs network access to every target. That is awkward across firewalls, NAT, customer networks and edge devices.
  • Short-lived jobs are missed. A batch job that runs for 5 seconds may finish between two scrapes and never be seen. Prometheus' answer is the Pushgateway, a small service the job pushes to and the scraper pulls from, but it is a workaround with its own pitfalls (stale values persist after the job ends).
  • Service discovery must be accurate. The scraper is only as good as its target list. In fast-changing environments (autoscaling, Kubernetes), discovery integration is essential.

Push. Each agent or service sends its samples to the platform. Datadog, CloudWatch, StatsD, Graphite and the OpenTelemetry protocol (OTLP) usually push.

Advantages:

  • Works anywhere. Behind firewalls and NAT, from mobile apps, IoT devices, serverless functions and short-lived jobs. Only outbound connections are needed.
  • Lower latency for events. A sample can be sent the moment it is produced, which matters for event-like data.
  • Simple for multi-tenant SaaS. Customers push to an endpoint with an API key. The provider does not need to reach into customer networks.

Disadvantages:

  • Detecting dead sources is harder. Silence could mean "nothing to report" or "the host is dead". You need an explicit heartbeat metric and an "absent" alert (alert if no data has arrived from a host for 2 minutes), plus an inventory of what should be reporting.
  • Load control is on the server side. A buggy client can push too much or too often, so the ingestion tier needs authentication, rate limits and per-tenant quotas (see Rate Limiting and Throttling).
  • Retries create duplicates. A client that times out and retries can send the same batch twice. Storage must treat a repeated (series, timestamp) sample as a no-op.

Our choice: both, behind one collector tier. Long-running services in our own data centres are scraped, because pull gives us health detection, load control and debuggability. Short-lived jobs, serverless functions, edge devices and anything across a network boundary push. Both paths converge at the collectors, which apply the same relabelling and limits and write to the same Kafka topic. Modern agents such as the OpenTelemetry Collector can do both: scrape local Prometheus endpoints and push the results onward with OTLP or Prometheus remote write, which is a common way to get pull semantics locally and push semantics across the network.

Scaling the scrapers. One scraper can handle thousands of targets (a Prometheus server commonly scrapes several thousand targets and a few million active series). For 500,000 hosts and many more service endpoints, targets are sharded across scrapers by a hash of the target address, with each scraper scraping only its share. Two scrapers per shard (active-active, both scraping the same targets) give redundancy, and the storage tier deduplicates their samples, or keeps one replica's samples and drops the other's (a "high-availability tracker" that elects one replica per cluster as the writer is a common implementation).

Pre-aggregation at the source. Agents can reduce volume before anything leaves the host:

  • Client libraries aggregate in memory. A service that handles 50,000 requests per second does not send 50,000 events. It increments an in-memory counter and a histogram, and exposes the current totals every 10 seconds. This is the single most important volume reduction in metrics, and it is why metrics are so much cheaper than logs.
  • StatsD-style aggregation does the same in a local daemon: applications send UDP packets per event to a local agent, which aggregates them and flushes every 10 seconds.
  • Histograms instead of raw latencies. Sending a histogram of 10 to 20 buckets every 10 seconds replaces sending every latency value, and still allows percentile estimates (Deep Dive 12).

2. The ingestion pipeline with Kafka#

At 5 million samples per second (about 1 GB per second before compression), the ingestion pipeline is where most of the engineering effort goes.

Batching and compression. Collectors never send one sample per request. They group samples by series into batches of a few thousand samples, encode them in Protocol Buffers and compress them (Snappy or LZ4 are favoured for low CPU cost; gzip or zstd for better ratio). Because label sets repeat heavily within a batch, compression ratios of 5 to 10 times are common. After batching, 5 million samples per second becomes a few thousand Kafka messages per second of a few hundred kilobytes each. Keep messages well under 1 MB, which is the comfortable size for Kafka.

Partitioning. The key decision. We key each record by a hash of the series' sorted label set (optionally prefixed by tenant). This gives:

  • Ordering per series. All samples of one series go to one partition in order, so the ingester can append them to the series' chunk in time order, which is what the compression scheme assumes.
  • Even spread. There are tens of millions of series, so the hash spreads them evenly. No single series is hot: even the busiest series produces only one sample every 10 seconds. That is a pleasant property of metrics: hot partitions come from hot tenants, not hot keys.

The trap is partitioning by something coarse, such as metric name or host. Partitioning by metric name sends every http_requests_total sample (perhaps 10% of all traffic) to one partition. Partitioning by tenant makes the biggest tenant's partition hot. If tenant locality is needed (to keep one tenant's series on a subset of ingesters), use shuffle sharding: each tenant gets a small random subset of partitions or ingesters, and series are hashed within that subset (Deep Dive 11).

Sizing Kafka. A single broker on good hardware can handle on the order of hundreds of thousands to a million small messages per second and a few hundred MB per second of throughput, depending on message size, replication and disks. With 200 to 300 MB per second after compression, and replication factor 3, a cluster of perhaps 10 to 20 brokers handles the load with headroom. Partitions are the unit of parallelism for consumers, so we want enough of them (say 512 to 1,024) that ingesters can scale out, and we must create them up front, because adding partitions later changes which partition a key hashes to.

Durability settings. Producers use acks=all with idempotence enabled, so retries do not duplicate records within Kafka. Topics use replication factor 3 and min.insync.replicas=2. Retention of 1 to 3 days is enough to replay after a storage outage without the cost of a long-term log.

Consumers and offsets. Ingesters form a consumer group. Each ingester owns some partitions, appends samples to its WAL, and commits the Kafka offset only after the WAL write is durable. If it crashes, the partition is reassigned (Kafka rebalancing) and the new owner resumes from the last committed offset. Some samples are processed twice, which is harmless: a repeated (series, timestamp, value) is dropped, so the end result is effectively exactly-once (see Delivery Guarantees: At-Most, At-Least and Exactly-Once).

Bad data. Samples that fail validation (malformed labels, a timestamp far in the future, a series over the tenant's limit) are not retried forever. They are counted in a "discarded samples" metric with a reason label, and a sample of them goes to a dead-letter topic for debugging. The pipeline must never block on one bad batch.

Backpressure. If ingesters fall behind, Kafka lag grows. That is fine for minutes: Kafka is the buffer. If lag grows toward the retention limit, the system must shed load deliberately rather than lose data randomly: lower the scrape frequency for low-priority jobs, drop debug-level metrics first, and protect the metrics that alert rules depend on (Deep Dive 9).

Is Kafka required? No. Prometheus' own remote-write protocol sends samples directly to ingesters, and systems such as Cortex and Mimir originally used that path, replicating each sample to 3 ingesters chosen from a hash ring and waiting for a quorum of 2 to acknowledge (see Consistent Hashing). Grafana has described a newer Mimir architecture that places a Kafka-compatible log in front of ingesters, for the same decoupling reasons discussed here. Either way, the key properties are the same: partition by series, replicate, tolerate duplicates. In an interview, Kafka is a clear, defensible choice: say why it is there (spikes, decoupling, replay, multiple consumers) and what it costs (one more system to run, a few hundred milliseconds of extra latency).

3. Inside the time-series storage engine#

Why can a time-series database ingest millions of samples per second on modest hardware when a general-purpose database struggles at tens of thousands? Not because of one trick, but because it combines several simple ideas, each exploiting a property of metrics data: writes are append-only, recent data is hot, consecutive values are similar, and queries select series by labels and then scan a time range. See Storage Engines: B-Trees vs LSM Trees for the general background.

Append-only writes. A traditional database updates data in place: find the page, read it, modify it, write it back. That is random I/O. A spinning disk manages roughly 100 to 200 random operations per second; SSDs do far better but still prefer sequential access. A time-series engine never updates a sample. Every write appends to the end of a log or an in-memory buffer, so the disk sees long sequential writes. That turns the hardest part of the workload (volume) into the easiest kind of I/O.

An LSM-like structure. Samples first go to a write-ahead log (for crash recovery) and to an in-memory head: one open chunk per series, kept in time order. When the head covers a fixed time span (2 hours in Prometheus' engine), it is written out as an immutable, sorted, compressed block, and the WAL segment is discarded. In the background, compaction merges small adjacent blocks into larger ones (for example, 2-hour blocks into 6-hour, then 24-hour, up to a few weeks), so queries over long ranges open few files. This is the log-structured merge idea, with time as the natural sort order. The cost is write amplification: each sample is rewritten a few times during compaction. That is a good trade for a write-heavy workload.

Compression that exploits regularity. The Gorilla paper (Tuomas Pelkonen and co-authors at Facebook, "Gorilla: A Fast, Scalable, In-Memory Time Series Database", VLDB 2015) introduced the two schemes most engines now use:

  • Timestamps: delta-of-delta. Samples arrive on a grid, every 10 seconds. Store the first timestamp, then the first delta (10 s), then only the change in the delta, which is almost always zero. Raw: 1000, 1010, 1020, 1030. Deltas: 10, 10, 10. Delta-of-deltas: 0, 0. Gorilla encodes a zero in a single bit, so regular timestamps cost about 1 bit each.
  • Values: XOR of consecutive floats. Consecutive values of a metric are usually close (CPU 45.2%, then 45.3%). XOR the 64-bit representation of each value with the previous one. Similar floats share their sign, exponent and leading mantissa bits, so the XOR has long runs of leading and trailing zeros. Store only the position and length of the "meaningful" middle bits. If the value did not change at all (very common for gauges), the XOR is zero and costs one bit.

Together these brought Facebook's data to about 1.37 bytes per sample on average, versus 16 bytes for a raw (timestamp, double) pair: almost 12 times smaller. The exact figure varies with the data (noisy values compress worse), but 1 to 2 bytes per sample is the right order of magnitude to quote. Values that are integers (counters) can use varint encoding of deltas, where a small number fits in one byte.

Time partitioning. Blocks cover fixed time ranges, so:

  • Writes are localised: everything new goes to the current head.
  • Reads prune by time: a query for the last 2 hours touches only the head and maybe one block, never last month's data.
  • Retention is cheap: deleting data older than 15 days means deleting whole block directories, not running a DELETE over billions of rows (see Data Lifecycle, Tiering and Retention).

The label index. Each block contains an inverted index from label pairs to postings lists of series ids, plus a symbol table that stores each distinct label string once. Selecting series is a set operation:

Query: avg CPU for env="prod" and region="us-west"

Postings:  region="us-west" -> [1, 2]
           env="prod"       -> [1, 2, 3]
Intersect: [1, 2] ∩ [1, 2, 3] = [1, 2]
Read:      only the chunks for series 1 and 2, skip 3 and 4
Aggregate: mean of their samples in the time range

Postings lists are sorted, so intersection is a linear merge, and regular expressions on labels (status=~"5..") are answered by scanning the (small) list of distinct values of that label first.

Bloom filters and block metadata. In engines built on general LSM storage (for example, a time-series layer over HBase, Cassandra or RocksDB), each sorted file keeps a Bloom filter of the series keys it contains, so a lookup for one series skips files that definitely do not contain it. A typical filter uses about 10 bits per key for a 1% false-positive rate (see Probabilistic Data Structures for Big Data). Every block and chunk also carries min and max timestamps (and some engines keep min and max values), so the query engine skips chunks outside the time range without decompressing them.

Worked example: one block, four series. Suppose eight samples arrive over 10 seconds for cpu_usage on four hosts (two in us-west/prod, one in us-east/prod, one in us-east/staging), two samples each. The engine creates four series and stores each series' two samples together:

SeriesRaw size (2 timestamps + 2 values)Stored size
host=server-1, us-west, prod32 bytesabout 13 bytes (base time, one delta, a zero delta-of-delta, first value, one XOR)
host=server-2, us-west, prod32 bytesabout 13 bytes
host=server-3, us-east, prod32 bytesabout 13 bytes
host=server-4, us-east, staging32 bytesabout 13 bytes

A 60% saving with only two samples per series; with 120 samples per chunk, the per-sample cost falls toward 1 to 2 bytes because the base values are amortised. Querying "mean CPU of prod servers in us-west" intersects the postings for region="us-west" (series 1, 2) and env="prod" (series 1, 2, 3), reads only two chunks, and computes the mean as it decodes, without ever materialising rows.

The equivalent in a plain relational table would use an index on region and environment to find row ids, then fetch each row from wherever it sits on disk. With millions of rows, those scattered reads dominate. Series-oriented, compressed, time-partitioned storage puts the data a query needs physically together. That is the whole reason time-series databases exist.

Where it breaks. All of these optimisations assume a bounded number of series with regular samples. Every series costs index memory, a head chunk and per-series overhead (several kilobytes in total for an active series). If a label such as user_id creates millions of new series, the engine runs out of memory long before it runs out of disk. That is the cardinality problem, Deep Dive 8.

4. Downsampling, rollups and retention#

Raw 10-second data is essential when debugging an incident from the last hour. Nobody needs it for last year: a one-year chart is at most a few thousand pixels wide, so 10-second data would be averaged into pixels anyway. Downsampling replaces old fine-grained data with coarser summaries, trading precision on old data for much less storage and much faster long-range queries.

A typical policy.

Age of dataResolution keptTypical use
Last 1 to 2 daysRaw (10 s)Live dashboards, incident debugging
Up to 15 daysRaw, from object storageRecent investigations
Up to 90 days1-minute rollupsWeek and month dashboards
Up to 2 years1-hour rollupsCapacity planning, trends, year-over-year

A one-month chart from 1-minute rollups reads 6 times fewer points than from 10-second raw data. A one-year chart from 1-hour rollups reads 360 times fewer.

What a rollup stores. Not just an average. An average of averages is wrong whenever the underlying counts differ, and an average hides spikes. For each series and each rollup interval, store several aggregates:

  • min and max, so a chart can still show that a spike happened,
  • sum and count, so averages can be computed correctly at any coarser level (sum of sums divided by sum of counts),
  • for counters, the increase over the interval (handling resets), so rate still works,
  • for histograms, the per-bucket counts summed over the interval, so percentiles can still be estimated (Deep Dive 12).

Example: six raw samples in one minute, 45.2, 45.3, 45.1, 45.4, 45.0, 45.5, become one 1-minute rollup: min 45.0, max 45.5, sum 271.5, count 6 (average 45.25). Sixty of those become one 1-hour rollup: min of the mins, max of the maxes, sum of the sums, sum of the counts.

Percentiles cannot be rolled up from percentiles. The p99 latency for an hour is not the average, or the max, of the sixty per-minute p99s. To keep percentiles over long ranges you need a mergeable representation: histogram bucket counts (add them), or a mergeable sketch such as t-digest (Ted Dunning and Otmar Ertl, "Computing Extremely Accurate Quantiles Using t-Digests", 2019) or DDSketch (Charles Masson, Jee E. Rim and Homin K. Lee, "DDSketch: A Fast and Fully-Mergeable Quantile Sketch with Relative-Error Guarantees", VLDB 2019, from Datadog). Store the sketch in the rollup and compute percentiles from the merged sketch at query time.

Who computes rollups, and when. Two choices:

  • Batch, after the fact: the compactor reads completed blocks from object storage and writes downsampled blocks next to them. This is simple and cheap, and it is how Thanos' compactor downsamples (to 5-minute and 1-hour resolution, as documented). The rollup is only available some hours after the data was written, which is fine because rollups are only used for old data.
  • Streaming, at ingest: a stream processor computes 1-minute aggregates as samples arrive (see Apache Flink and Stream Processing). This is needed when you want to drop raw data immediately (for example, high-cardinality labels aggregated away at ingest, Deep Dive 8), or serve rollups for recent data. It costs a stateful streaming job.

Recording rules: rollups across series. Downsampling reduces resolution over time. Recording rules reduce width across series: a rule such as job:http_requests:rate5m = sum by (job) (rate(http_requests_total[5m])) is evaluated every 30 seconds and stored as a new, much smaller series. A dashboard that would have aggregated 10,000 series at query time now reads one. Recording rules are the most effective single tool for fast dashboards and cheap alert rules, and they are evaluated by the same rule evaluators as alerts.

Downsampling as a requirements negotiation. Interviewers often state "keep 10-second data for a year". A strong answer anticipates the cost (about 200 TB for a year at our scale before replication), explains it, and offers an alternative: "We probably need full resolution for a couple of weeks, 1-minute data for a few months, and 1-hour data for long-term trends. Does that meet the need?" Even if the interviewer insists on the original requirement, they are scoring your ability to spot a costly requirement and propose a better one, which is a hallmark of senior and staff candidates.

5. Low-latency dashboard queries over weeks of data#

A two-week panel over 500 hosts can easily touch tens of millions of samples. To return it in a second or two, the read path combines five techniques. Each removes a different kind of work.

1. Read less: pick the right resolution. The query planner looks at the range and the step. A panel 1,000 pixels wide showing 14 days needs at most about 1,000 points per series, a step of roughly 20 minutes. Reading raw 10-second data (120 samples per step) would waste 99% of the work. The planner reads the coarsest rollup that still has at least one point per step: 1-minute or 1-hour rollups for long ranges, raw data for short ones. Grafana-style dashboards help by automatically choosing a step from the panel width ($__interval).

2. Compute less: precompute with recording rules. If a dashboard shows sum by (service) (rate(http_requests_total[5m])) across 50,000 series, compute that once every 30 seconds as a recording rule and store the result, about 200 series. Every viewer then reads 200 series instead of aggregating 50,000. Teams typically create recording rules for every expensive, frequently viewed panel and for every expression used in alerts.

3. Do not recompute the past: split and cache. A query frontend in front of the query engine (Cortex and Mimir both have one, as does Thanos) splits a range query into day-aligned sub-queries, runs them in parallel, and caches each result in Memcached or Redis keyed by (query, day, step). Completed past days never change (apart from late data, which the frontend handles by not caching the most recent few minutes), so a dashboard refreshed every 30 seconds only recomputes the newest slice. Step alignment matters: the frontend rounds start and end to multiples of the step, so two users opening the same dashboard a few seconds apart produce identical, cacheable sub-queries.

4. Spread the work: shard and fan out. Series are distributed across many ingesters and store gateways, so a querier fetches from many nodes in parallel. For very heavy queries, the frontend can also shard by series: run sum by (service) on 16 disjoint subsets of series (selected by a hash of the series id) and combine the 16 partial sums. This works for aggregations that are associative, such as sum, count, min and max; average is computed as sum divided by count; percentiles from histograms work by summing bucket counts.

5. Protect the system: limits and isolation.

  • Per-query limits: maximum series fetched, maximum samples, maximum range for raw data, query timeout. A query that would read 100 million series is rejected with a clear error, not allowed to take down queriers.
  • Per-user and per-tenant queues: a fair queue in the frontend ensures one user's runaway dashboard cannot starve others.
  • Separate read paths for alerting and dashboards: rule evaluators get dedicated queriers, so an incident that brings 500 engineers to the dashboards does not slow the alerts that tell them what is wrong.

Caching the index and chunks. Long-range queries over object storage are dominated by fetching index sections and chunks. Store gateways keep index headers (a compact summary of each block's index) in memory or on local disk, and cache postings lists and chunks in Memcached. Object storage latency (tens of milliseconds per request) is then paid once per block, not per query.

A worked latency budget for a 14-day panel.

StepWorkTime
Frontend splits into 14 days13 days found in results cache5 ms
Today's sub-query500 series × 1 day of 1-minute data = 720,000 points from ingesters150 ms
Aggregationrate, then sum by (region)20 ms
Merge and return14 day slices into one result5 ms
Totalabout 200 ms

Without caching and rollups, the same panel would read 500 series × 14 days of 10-second data = 60 million samples, perhaps 5 to 20 seconds. The design brings this down by about two orders of magnitude, and the same techniques apply to any dashboard.

6. The alert rules engine#

Alert evaluation looks simple ("run a query, compare with a threshold") but has to be reliable, timely and quiet: no missed alerts, no flapping, no duplicate pages.

The evaluation loop. Each rule has an expression, a threshold (usually inside the expression, such as > 0.05), an evaluation interval (30 or 60 seconds) and a for duration. On every tick, the evaluator runs the expression as an instant query at the current time. The result is a set of series, one per label combination that meets the condition (for example, one per service whose error ratio exceeds 5%). Each such series is an alert instance, tracked separately: checkout and search can be firing at the same time from one rule.

States.

  • Inactive: the condition is false.
  • Pending: the condition is true but has not yet been true for the whole for duration. No notification. This absorbs brief spikes.
  • Firing: the condition has been continuously true for at least for. Notify.
  • Resolved: the condition is false again after firing. Send a resolved notification, so the on-call engineer knows the problem cleared.

Avoiding flapping. A metric hovering around the threshold (4.9%, 5.1%, 4.8%, 5.2%) can fire and resolve repeatedly, which trains people to ignore alerts. Three remedies:

  • Use a window function, not a raw value: alert on avg_over_time(...[5m]) or on a 5-minute rate, which smooths noise.
  • Hysteresis: fire above 5%, resolve only below 4%. Some systems support a separate "keep firing for" duration, which holds an alert in the firing state for a while after the condition clears.
  • Longer for for low-severity alerts. Warnings can wait 15 minutes. Pages should be reserved for conditions that need a human now.

Handling missing data. If a service stops reporting, its error rate is not 0, it is unknown. A rule on error_ratio > 0.05 silently stops matching and the alert resolves, which is exactly wrong when the service has crashed. Every important service needs a complementary absence alert: absent(up{job="checkout"}) or up{job="checkout"} == 0 for 2 minutes. For push-based sources, use a heartbeat metric with an absence alert.

Evaluation delay and late data. If a rule evaluates at 10:00:30 over the last 5 minutes but some samples for 10:00:20 are still in the Kafka pipeline, the rule sees a partial window. For rate-based rules this causes small dips; for count-based rules, false "too low" alerts. A common fix is to evaluate rules a little in the past: query at now − 30 s so the pipeline delay is covered. This adds 30 seconds to alert latency, which still fits the 1-minute budget, and it eliminates a whole class of false alerts.

Scaling to 500,000 rules. At 10,000 to 20,000 evaluations per second, one evaluator is not enough. Rules are grouped (rules in a group run sequentially, so a recording rule can feed an alert rule in the same group) and groups are sharded across evaluators by a hash of the group name. A hash ring (or a coordination service such as etcd or ZooKeeper, see ZooKeeper and etcd) assigns groups; when an evaluator dies, its groups move to others within a few seconds. To avoid all rules hitting the TSDB at the same instant, each group's start time is offset by a hash of its name, spreading evaluations evenly over the interval.

Two evaluators, or one? Running each group on two evaluators gives redundancy, and duplicates are harmless because the alert manager deduplicates identical alerts. That is Prometheus' standard high-availability pattern: two identical Prometheus servers, both evaluating the same rules, both sending to the alert manager cluster. In a sharded system, a single owner per group plus fast failover is usually enough, because a restarted owner reloads persisted alert state.

Getting below a minute: streaming evaluation. Query-based evaluation has a latency floor of roughly (pipeline delay + evaluation interval + evaluation offset). For most alerts that is 30 to 90 seconds, which meets the requirement. If an interviewer pushes for alerts within 10 seconds, the alternative is to evaluate on the ingest stream: a stream processor (Flink, or a custom consumer) reads the Kafka samples topic, keeps windowed aggregates for the series referenced by fast-path rules, and emits alerts as soon as a window crosses its threshold. Trade-offs:

  • Faster: no wait for storage or the evaluation tick, so seconds rather than a minute.
  • Restricted: only simple, local expressions work well in streaming (thresholds and rates on specific series, sums over a known label). Arbitrary queries with joins across metrics are far easier against storage.
  • Duplicated logic: two evaluation engines must agree on semantics, or the same rule can behave differently on the two paths.

A sensible design keeps query-based evaluation as the default and offers a streaming path only for a small set of critical, simple rules.

7. The notification pipeline: from alerts to the right human, once#

The alert manager stands between evaluators and humans. Its job is to turn a stream of raw "this is firing" messages into a small number of actionable notifications.

Deduplication. Evaluators resend every firing alert on every cycle, and with redundant evaluators, twice per cycle. The alert manager keys each alert by its full label set (rule name plus instance labels) and notifies only on state changes, and then periodically (repeat_interval, such as every 4 hours) while it stays firing, as a reminder.

Grouping. Alerts are grouped by chosen labels (group_by: [alertname, cluster]). The first alert in a new group starts a short timer (group_wait, typically 30 seconds) to collect others, and the group is notified as one message: "HostDown: 214 hosts in cluster eu-west-3". Later additions to an active group are batched and sent after group_interval (say 5 minutes). Grouping is what turns a data-centre outage from 5,000 pages into one.

Inhibition. Rules that say "if alert A is firing, suppress alerts B that share these labels". If DatacenterUnreachable{dc="eu-west-3"} fires, inhibit every ServiceDown alert with dc="eu-west-3". The engineer sees the cause, not a thousand symptoms.

Silences. Time-bounded mutes matching labels, created by people (during maintenance) or by automation (during a deploy). They are stored durably and replicated across the alert manager cluster.

Routing. A tree of matchers, evaluated top-down, decides who receives an alert group: team=payments, severity=page → the payments PagerDuty service; severity=warning → the team's Slack channel; everything else → a catch-all channel, so no alert is ever silently dropped for lack of a route.

High availability. The alert manager must not be a single point of failure, but naive replication would send every notification once per replica. Prometheus' Alertmanager solves this with a small cluster that gossips notification and silence state between peers (see Heartbeats, Failure Detection and Gossip). Every replica receives every alert. Before sending, each replica waits a delay proportional to its position in the cluster and checks, via the gossiped log, whether a peer has already sent that notification. Normally the first replica sends and the others see it and skip. If the first replica is down, the second sends a few seconds later. The result is at-least-once delivery with duplicates rare, which is the right bias for paging: a duplicate page is annoying; a missing page is an outage.

Delivery. Notifications are put on a durable queue and sent by workers per channel, with retries, exponential backoff and per-integration rate limits (Slack and PagerDuty both throttle). Each request carries an idempotency or deduplication key derived from the alert group, so a retried request to PagerDuty updates the same incident instead of opening a second one (see Idempotency and Safe Retries). Failed deliveries after all retries go to a dead-letter queue and raise their own alert on a different channel.

  1. Evaluator A sends the firing alert to every alert manager replica.
  2. It sends the same alert to replica 2, so either can deliver.
  3. Evaluator B, the redundant twin, sends the same alert to replica 1.
  4. And to replica 2. Four copies of one alert arrive; all are deduplicated by label set.
  5. Replica 1 (first in the cluster order) waits for group_wait and sends.
  6. It notifies PagerDuty with a deduplication key.
  7. It gossips "sent" for that group to its peer.
  8. Replica 2 waits a little longer, finds the gossiped record, and does not send. Had replica 1 been down, replica 2 would have sent instead.

8. High cardinality: the problem that breaks metrics systems#

Cardinality is the number of distinct series. It is the single most important cost driver in a metrics system, and the most common way such a system falls over.

Why it explodes. The number of series for one metric is the product of the number of distinct values of each label. http_requests_total with labels service (200), endpoint (50), status (10) and pod (20 per service) gives up to 200 × 50 × 10 × 20 = 2,000,000 series, which is already large. Add user_id with a million values and the theoretical product is 2 × 10¹². In practice only combinations that actually occur create series, but a single label with unbounded values (user ids, request ids, full URLs with query strings, session ids, error messages, timestamps) is enough to multiply the series count by orders of magnitude within hours.

Typical causes in practice.

  • A developer adds user_id or order_id as a label "for debugging".
  • A label holds a raw URL path such as /users/12345/orders, instead of the route template /users/:id/orders.
  • Error messages with embedded values become label values.
  • Churn: Kubernetes pods get new names on every deploy, so every rollout of a 500-pod service creates 500 new pod values for every metric that pod exports. Old series stop receiving samples but still sit in the head block and the index until they age out. A team deploying 20 times a day multiplies its effective series count.

Why it hurts. Cost per series is roughly fixed regardless of how many samples it receives:

  • Memory in the head block: each active series needs an entry in the in-memory index, label strings (interned), and an open chunk. A commonly quoted rule of thumb for Prometheus is a few kilobytes per active series. At 3 KB per series, 50 million series need about 150 GB of RAM across ingesters; 500 million would need 1.5 TB.
  • Index size and query cost: postings lists grow with series count, and a query such as sum(rate(http_requests_total[5m])) must touch every matching series.
  • Compaction and storage: each series has its own chunks, and very short-lived series compress badly because a chunk with five samples carries the same overhead as one with 120.

Defences, from source to storage.

  1. Education and review. A label is for dimensions you will filter or group by, with bounded values. Identifiers belong in logs and traces. Metric names and labels can be reviewed in code review like an API.
  2. Client-side and agent-side relabelling. The collector can drop labels, rewrite values (strip ids from paths with a regular expression), or drop whole metrics before they leave the host. In Prometheus this is metric_relabel_configs.
  3. Aggregation at ingest. For metrics where the per-pod dimension is not needed, an aggregation tier sums them over pod before storage, so 500 pod series become 1 service series. This is the streaming version of a recording rule.
  4. Per-tenant limits enforced at the distributor. Maximum active series per tenant (for example 5 million), maximum series per metric (for example 200,000), maximum label count and value length. Samples that would create a new series beyond the limit are rejected with an error the client can see, and the rejection is itself counted and alerted on. Existing series keep working, so a tenant's dashboards do not break because someone deployed a bad label.
  5. Visibility. A cardinality explorer shows, per tenant, the metrics with the most series, the labels with the most values, and how fast they are growing. Exact counts across a cluster are expensive, so systems often estimate distinct series per metric or per label with HyperLogLog sketches (see Probabilistic Data Structures for Big Data): about 12 KB per counter gives about 1% error at any cardinality, and sketches from different ingesters merge by taking register maxima.
  6. Exemplars. Instead of a trace_id label, attach a sampled trace id as an exemplar to a histogram bucket sample. A dashboard can show a dot on a latency spike that links straight to a slow trace, giving per-request drill-down without per-request series.

Worked example: one bad label.

A service with 100 pods exports 30 metrics with about 50 series each per pod: 100 × 30 × 50 = 150,000 series. A developer adds customer_id (20,000 active customers per hour) to the 5 request metrics, of which each pod sees, say, 2,000 customers per hour. New series: 100 pods × 5 metrics × 2,000 customers × about 10 other label combinations = 10 million series, an increase of about 65 times, all from one line of code. At 3 KB per series that is 30 GB of extra ingester memory. Without a per-tenant limit, ingesters run out of memory and restart, losing the alerting path for everyone. With a limit of 1 million series per tenant, the new series are rejected within seconds, a "series limit reached" alert fires for that tenant, and everyone else is unaffected.

When high cardinality is genuinely needed. Some questions need it: "which customers see the most errors?" The answer is not to force that into a TSDB built for millions of series with bounded labels, but to use a store built for high-cardinality analytics: a columnar store such as ClickHouse or Apache Druid over wide events, or a tracing or logging backend. These scan compressed columns and group by any field at query time, trading some freshness and query cost for unlimited dimensions. A practical platform offers both, and the guideline is: metrics for bounded dimensions and alerting; events, logs and traces for unbounded dimensions and investigation (see Observability: Logs, Metrics and Traces).

9. Staying up during spikes and failures#

A monitoring system is most loaded exactly when everything else is failing. An outage produces more errors, more retries, more log lines, more people opening dashboards, and sometimes a storm of reconnecting agents. The platform must degrade gracefully, and the alerting path must be the last thing to degrade.

Absorbing write spikes.

  • Kafka as a buffer. If ingesters slow down, samples accumulate in Kafka (retained for hours to days) instead of being dropped at the edge. Consumers catch up after the spike. Consumer lag, measured in seconds of data, is the key health metric.
  • Agent-side buffering. Collectors keep a bounded on-disk queue (Prometheus' remote write uses a WAL-backed queue) so a short outage of the ingest endpoint loses nothing. Agents back off exponentially with jitter, so thousands of them do not reconnect in the same second.
  • Load shedding with priority. When the system is over capacity, it rejects what matters least. Samples can be tagged with a priority: series referenced by alert rules and SLO metrics are high priority; debug and per-pod detail are low. Distributors under pressure reject low-priority writes first (returning 429 so the client retries later) and keep accepting critical ones.

Surviving node and zone failures.

  • Replication factor 3 with quorum writes. Each series is written to three ingesters on the hash ring (or three Kafka replicas, then one or more consumers). A write succeeds when two of three acknowledge, so one slow or dead ingester does not block ingest (see Quorums and Leaderless Replication).
  • Zone awareness. The three replicas of each series are placed in three different availability zones, so a whole-zone outage loses one replica, never two.
  • Queries read from the replicas and deduplicate. Querying all replicas and merging (deduplicating identical timestamps) gives correct results even if one replica missed some samples.
  • Durable before acknowledgement. An ingester's write-ahead log on local disk means a restart replays recent samples instead of losing them. Blocks are uploaded to object storage every two hours, after which the ingester can drop them.

Protecting the read path.

  • Per-query limits (Deep Dive 5) reject expensive queries before they run.
  • Separate query pools for alerting, dashboards and ad-hoc exploration. During an incident, ad-hoc queries can be throttled without affecting rule evaluation.
  • Results caching absorbs the "500 engineers open the same dashboard" pattern: the first load computes, everyone else reads the cache.

Monitoring the monitoring. A system that alerts on everything else must not fail silently itself.

  • Meta-monitoring: a separate, smaller monitoring stack (in another region or another provider) scrapes the main platform's own metrics: ingestion rate, rejected samples, Kafka lag, rule evaluation duration and failures, notification send failures.
  • Dead man's switch (watchdog alert): a rule that always fires (vector(1)), routed to an external service that expects a notification every few minutes. If the pings stop, the external service pages, because silence means the alerting pipeline itself is broken.
  • End-to-end probes: a synthetic agent writes a known metric and a rule checks that it arrives within N seconds. This measures true ingest-to-alert latency, the number in the non-functional requirements.

Graceful degradation order. When resources run short, give up features in this order: ad-hoc queries and long-range dashboards first, then low-priority ingestion, then dashboards for recent data. Rule evaluation and notification delivery are protected until the end. This ordering is a product decision worth stating in an interview, because it shows an understanding of what the system is for.

10. Late, out-of-order and missing data#

Samples do not always arrive in timestamp order. An agent buffers during a network partition and then flushes 10 minutes of samples; a Kafka consumer restarts and replays; a batch job backfills yesterday's numbers.

Why ordering matters to the engine. The Gorilla-style encoding in each chunk (Deep Dive 3) stores deltas from the previous timestamp, so it naturally supports only appends with increasing time. Classic Prometheus rejected any sample older than the latest one already stored for that series ("out of order sample"), and samples older than the head block's time range were rejected as "out of bounds".

Accepting late data. Newer engines accept samples within a configurable out-of-order window (for example, up to one hour old). Prometheus added experimental support for this around version 2.39, according to its release notes, and Mimir and VictoriaMetrics have their own forms of it. The usual technique is a separate in-memory buffer for out-of-order samples per series, which is sorted and merged into normal chunks at compaction time. Queries merge the in-order and out-of-order data. The cost is memory and some compaction work; the benefit is no silent data loss from agents that buffered.

Older data: backfill as blocks. For historical imports beyond the window, the right tool is not the live write path but offline block creation: build TSDB blocks for the old time range and upload them to object storage, where compaction merges them with existing blocks.

Effects on alerting and caching.

  • Rules evaluated over a window that is still filling see partial data; the evaluation delay from Deep Dive 6 covers normal pipeline lag.
  • The results cache must not cache the most recent minutes, and some systems also invalidate cached days when a backfill lands in them.
  • Rollups computed by batch compaction see late data naturally (they run after the window closes); streaming rollups must allow lateness, using watermarks as in Flink (see Time, Clocks and Ordering).

Missing data and staleness. In a pull model, if a target disappears, Prometheus writes a staleness marker (a special NaN value) for each of its series, so queries stop returning the old value immediately instead of carrying it forward for the default 5-minute lookback. Without staleness handling, a dashboard would show a dead host's CPU flat-lining at its last value for 5 minutes, and an alert on that value would neither fire nor resolve correctly. In push models, the system cannot tell "nothing to report" from "dead", which is another reason to pair push with explicit heartbeats and absence alerts.

Clock skew. Samples carry the source's timestamp, so a host with a clock 5 minutes fast writes samples "in the future". Distributors reject samples too far ahead of server time (a grace period of a few minutes is typical), and agents should run NTP or a similar time sync. For pull, the scraper's own timestamp is used by default, which avoids most skew problems: one more practical advantage of pull.

11. Sharding and multi-tenancy#

A hosted metrics platform serves thousands of tenants (teams or customers) on shared infrastructure. Two questions follow: how to spread series across nodes, and how to stop one tenant from hurting others.

Sharding series with a hash ring. The distributor computes a hash of (tenant id, metric name, sorted labels) and places the series on a consistent hash ring of ingesters (see Consistent Hashing). Each ingester owns many small token ranges, so adding an ingester moves only about 1/N of series, and load spreads evenly. The ring itself is stored in a key-value store (Consul or etcd) or propagated by gossip. With replication factor 3, the next two distinct ingesters (in different zones) on the ring also receive the series.

Why hash the whole series, not only the metric name? Hashing by metric name alone would put all 2 million series of http_requests_total on one ingester, a hot shard. Hashing the full label set spreads them. The cost is that a query for one metric must fan out to every ingester. This is the classic trade-off between write spread and read locality, and for metrics the write side wins, because writes are continuous and enormous while queries are bounded and cacheable.

Shuffle sharding for isolation. Even with per-tenant limits, a tenant can trigger pathological behaviour: a query of death, a burst of new series, a bug in a parser. If every tenant's data spreads across every ingester, one bad tenant affects all of them. Shuffle sharding assigns each tenant a random subset of nodes, such as 6 out of 60 ingesters. Two tenants share all 6 nodes with very low probability: the number of possible 6-node shards out of 60 is C(60, 6), about 50 million. A failure caused by one tenant's traffic affects only the few tenants whose shards overlap heavily. AWS has described this technique for Route 53, and Cortex and Mimir implement it for ingesters, queriers and rulers. The same idea applies to queries: each tenant's queries run on a subset of queriers.

Per-tenant limits (all configurable per tenant, with defaults):

LimitExample defaultProtects
Ingestion rate100,000 samples/s, burst 200,000Distributors and Kafka
Active series5 millionIngester memory
Series per metric200,000One runaway metric
Labels per series, label length30, 2,048 bytesIndex size
Query series and samples500,000 series, 50 million samplesQueriers
Query range for raw data30 daysStore gateways
Rule groups and rules1,000 groups, 20 rules eachRulers

Limits are enforced with token buckets at the distributor (see Rate Limiting and Throttling), and their usage is exported per tenant as metrics, so tenants can alert on approaching their own limits.

Fair queuing on the read path. The query frontend keeps one queue per tenant and the queriers pull round-robin across tenants. A tenant submitting 1,000 queries waits behind its own queries, not in front of everyone else's.

Tenant identity and isolation of data. Every write and query carries a tenant id (an HTTP header set by an authenticating gateway, never by the client directly). All storage is partitioned by tenant: separate index entries, separate blocks in object storage under a tenant prefix, separate cache keys. This makes deletion of a tenant's data and per-tenant retention straightforward. For the broader patterns, see Multi-Tenant SaaS Architecture.

12. Getting the math right: counters, histograms and SLO alerts#

A metrics system that stores data perfectly can still mislead if its functions are wrong. Interviewers at senior level often probe these semantics.

Counters and rate(). Counters only go up, except when a process restarts and the counter resets to 0. rate(x[5m]) computes the per-second increase over the last 5 minutes, and it must detect resets: whenever a sample is lower than the previous one, it assumes a reset and adds the previous value to the running total. Example: samples 100, 160, 220, 10, 70 at 15-second intervals. Naively, the increase is 70 − 100 = −30. With reset handling: (160 − 100) + (220 − 160) + 10 + (70 − 10) = 190 over 60 seconds, about 3.2 per second. Prometheus also extrapolates to the window boundaries, because samples rarely sit exactly at the window edges, which is why increase() of an integer counter can return a non-integer.

Rate then sum, never sum then rate. sum(rate(x[5m])) is correct. rate(sum(x)[5m]) is wrong, because summing counters across pods hides individual resets: one pod restarting makes the sum drop, which rate then misreads.

Gauges. Values that go up and down (memory, queue depth, temperature). Use avg_over_time, max_over_time or quantile_over_time; never rate.

Histograms vs summaries. Latency is the hardest metric to aggregate correctly.

  • A summary computes quantiles (p50, p99) inside each process. They are accurate per process but cannot be aggregated: the average of 100 pods' p99 values is not the fleet p99.
  • A histogram exports a counter per bucket (requests at or below 10 ms, 25 ms, 50 ms, 100 ms, …). Bucket counters from all pods can be summed, and histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))) estimates the fleet p99 by locating the bucket that contains the 99th percentile and interpolating linearly inside it.
  • The estimate is only as good as the buckets: if the p99 falls in the 1 s to 2.5 s bucket, the answer may be off by hundreds of milliseconds. Native (exponential) histograms, introduced experimentally in Prometheus 2.40 according to its release notes, use exponentially spaced buckets with a configurable growth factor, giving bounded relative error with sparse storage. This is the same idea as DDSketch from Deep Dive 4.

Worked p99 estimate. Over 5 minutes across the fleet: 9,000 requests ≤ 100 ms, 9,800 ≤ 250 ms, 9,950 ≤ 500 ms, 10,000 total. The 99th percentile is request number 9,900. It lies in the (250 ms, 500 ms] bucket, which holds 150 requests (9,800 to 9,950). Request 9,900 is 100 of 150 into that bucket, so linear interpolation gives 250 + (100/150) × 250 ≈ 417 ms. The true value could be anywhere from 250 to 500 ms; finer buckets narrow the range.

SLO burn-rate alerts. Alerting on "error ratio above 5% for 5 minutes" is common but crude: it pages for short blips that do not threaten the service level objective and can miss slow, steady burns. The Google SRE Workbook (2018) recommends multiwindow, multi-burn-rate alerts. For a 99.9% availability SLO over 30 days, the error budget is 0.1% of requests. The burn rate is the observed error ratio divided by 0.1%: a burn rate of 1 uses the budget exactly over 30 days; a burn rate of 14.4 uses 2% of the monthly budget in one hour.

SeverityLong windowShort windowBurn rateBudget used when it fires
Page1 hour5 minutes14.42%
Page6 hours30 minutes65%
Ticket3 days6 hours110%

An alert fires only when both windows exceed the burn rate. The long window ensures the problem is significant; the short window ensures it is still happening, so the alert resolves quickly after a fix.

- alert: CheckoutErrorBudgetBurnFast
  expr: |
    (sum(rate(http_requests_total{job="checkout",code=~"5.."}[1h]))
      / sum(rate(http_requests_total{job="checkout"}[1h]))) > (14.4 * 0.001)
    and
    (sum(rate(http_requests_total{job="checkout",code=~"5.."}[5m]))
      / sum(rate(http_requests_total{job="checkout"}[5m]))) > (14.4 * 0.001)
  for: 2m
  labels:
    severity: page
    team: payments
  annotations:
    summary: "Checkout is burning its 30-day error budget 14x too fast"
    runbook: "https://runbooks.example.internal/checkout-errors"

In practice the ratios are computed as recording rules (job:slo_errors_per_request:ratio_rate1h and so on), both to make the alert cheap and to put the same numbers on the SLO dashboard. This connects the design to the reliability practice described in DevOps, SRE and Platform Engineering.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Cardinality explosion from one bad labelIngester memory exhausted, restarts, data and alert gaps for every tenant on those nodesPer-tenant and per-metric series limits at the distributor, relabelling rules, cardinality explorer with HyperLogLog estimates, shuffle sharding to contain the blast radius
Deploy churn creates millions of short-lived seriesHead block and index grow, compaction slows, poor compressionDrop or aggregate the pod label where not needed, shorter head block, limits on series creation rate
Ingest spike during an incidentDistributor CPU saturates, samples dropped, alert inputs missingKafka buffer, agent-side queues with jittered backoff, priority-based load shedding that keeps alert-critical series
Ingester crashRecent samples on that node unavailableReplication factor 3 with quorum writes, WAL replay on restart, queries read all replicas and deduplicate
Whole availability zone lostOne third of replicas goneZone-aware replica placement so every series keeps two replicas, enough headroom in the remaining zones
Kafka consumer lagDashboards and alerts run on stale dataAlert on lag in seconds, autoscale consumers, evaluation delay covers normal lag, rules flag stale inputs
Expensive query, for example a year of raw data across all seriesQuerier memory exhausted, other dashboards slowPer-query series and sample limits, timeouts, automatic rollup tier selection, fair per-tenant queues
Dashboard thundering herd during an outageQuery load multiplies at the worst timeResults cache with day-aligned splits and step alignment, recording rules for heavy panels, separate query pools for alerting
Rule evaluator falls behindAlerts fire late or not at allShard rule groups across evaluators, offset start times, alert on evaluation duration and missed iterations
Silent pipeline failureNo alerts fire, everyone assumes all is wellWatchdog alert to an external dead man's switch, meta-monitoring stack in another region, synthetic end-to-end probes
Duplicate or lost notificationsPager fatigue, or a missed incidentAlert manager cluster with gossip-based deduplication, at-least-once delivery with dedup keys, DLQ with its own alert on a separate channel
Object storage slow or throttledLong-range queries and compaction stallIndex-header and chunk caches on store gateways, retries with backoff, compaction scheduling outside peak hours

What Interviewers Expect#

Mid-level. Produce a working end-to-end design: agents or scrapers collect metrics, a write path stores them in a time-series database, a query API serves dashboards, and a rule evaluator sends alerts through a notification service. Explain what a series is (name plus labels) and why a general-purpose relational table of samples is a poor fit at millions of writes per second. Size the system roughly (millions of samples per second, terabytes per month). Know the difference between push and pull and give one reason for each. Describe an alert rule with a threshold and a for duration.

Senior. Drive a near-optimal design and defend it. Explain the storage engine: an append-only head block with WAL, Gorilla-style compression to under 2 bytes per sample, time-partitioned blocks, an inverted index from labels to series. Use rollups and tiered retention to make two-week dashboards fast, plus a query frontend with splitting and caching. Explain the alert state machine (pending, firing, resolved), flapping and absence alerts, and the alert manager's grouping, inhibition, silences and routing. Treat cardinality as the main scaling risk and propose concrete limits. Use Kafka (or replicated ingesters) for durability and spike absorption, and explain partitioning by series hash. Know rate() semantics and why histograms aggregate but summaries do not.

Staff and above. Frame the system by what it must do when everything else is failing: protect the alerting path, degrade dashboards first, monitor the monitoring with a dead man's switch and a separate meta-monitoring stack. Design multi-tenancy with shuffle sharding, per-tenant limits and fair queuing. Discuss trade-offs between query-based and streaming evaluation for sub-minute alerts, between pull and push in a hybrid fleet, between exact rollups and mergeable sketches for percentiles, and between a TSDB and a columnar store for high-cardinality questions. Bring in SLO burn-rate alerting as the better default for paging. Reason about cost per series and per sample, and know which real systems made which choices (Prometheus, Thanos, Cortex and Mimir, VictoriaMetrics, M3, Monarch) without overclaiming details.

Deep Dive: how real systems made these choicesShow

The design above is a synthesis. Real systems pick different points in the same space. The descriptions below stick to well-documented, high-level facts.

  • Prometheus (created at SoundCloud in 2012, the second project to join the CNCF after Kubernetes, in 2016). Pull-based scraping with service discovery, a single-node TSDB with head block, WAL and two-hour blocks (the "v3" storage engine shipped with Prometheus 2.0 in 2017), PromQL, local rule evaluation, and a separate Alertmanager. It deliberately does not cluster its storage: high availability is two identical servers, and long-term or global storage is delegated to remote write or to the systems below.
  • Thanos (open-sourced by Improbable in 2018). Keeps Prometheus servers as they are and adds a sidecar that uploads each two-hour block to object storage, a store gateway that serves those blocks, a querier that fans out to sidecars and store gateways and deduplicates HA pairs, and a compactor that merges blocks and produces 5-minute and 1-hour downsampled data. It is the "add durability and global view to existing Prometheus" approach.
  • Cortex and Grafana Mimir. Cortex (started at Weaveworks, a CNCF project) is a horizontally scalable, multi-tenant Prometheus-compatible backend built around distributors, ingesters on a hash ring with replication, queriers, a query frontend and rulers. Grafana Labs forked it as Mimir in 2022. Both reuse the Prometheus TSDB block format and store blocks in object storage. The components in this design, including shuffle sharding and per-tenant limits, follow that architecture closely.
  • VictoriaMetrics. A Prometheus-compatible TSDB available as a single binary or a cluster of vminsert, vmstorage and vmselect nodes, known for efficient compression and low resource usage. It shows that a simpler, shared-nothing cluster can go a long way.
  • M3 (Uber, open-sourced in 2018). M3DB storage, a query engine and a streaming aggregator that performs rollups on ingest, built when Uber's metrics outgrew earlier setups. Its streaming aggregator is the "aggregate at ingest" defence against cardinality from Deep Dive 8.
  • Monarch (Google; "Monarch: Google's Planet-Scale In-Memory Time Series Database", VLDB 2020). Regional zones that keep recent data in memory, with a global query layer above them; designed to keep monitoring available even when other infrastructure (including persistent storage) is degraded. It is a useful reference for the principle that monitoring must have fewer dependencies than the systems it watches.
  • Gorilla (Facebook; Pelkonen et al., VLDB 2015). An in-memory cache of the most recent 26 hours of data in front of a slower persistent store, which introduced the delta-of-delta and XOR compression used by most modern engines.
  • Hosted services such as Datadog, New Relic, Grafana Cloud and the cloud providers' own monitoring products are push-based for their customers, with agents on hosts. Their internal designs are not fully public, so in an interview it is better to discuss the open designs above.

Build or buy. For most companies the right answer is to run Prometheus (or a compatible agent) at the edge and either buy a hosted backend or run Mimir, Thanos or VictoriaMetrics. Building a new TSDB is justified only at a scale or with requirements that existing systems demonstrably cannot meet, which is the situation the interview question imagines.

Deep Dive: a small PromQL toolkitShow

These queries cover most dashboards and alerts. They also show which operations the engine must support efficiently.

# Requests per second per service, over 5-minute windows
sum by (service) (rate(http_requests_total[5m]))
 
# Error ratio per service
sum by (service) (rate(http_requests_total{code=~"5.."}[5m]))
  / sum by (service) (rate(http_requests_total[5m]))
 
# Fleet p99 latency from a histogram
histogram_quantile(0.99,
  sum by (le, service) (rate(http_request_duration_seconds_bucket[5m])))
 
# Disk will be full within 4 hours, extrapolated from the last 6 hours
predict_linear(node_filesystem_avail_bytes[6h], 4 * 3600) < 0
 
# Targets that stopped reporting
up == 0
 
# Top 10 pods by memory
topk(10, container_memory_working_set_bytes)
 
# Compare with the same time last week
sum(rate(http_requests_total[5m])) / sum(rate(http_requests_total[5m] offset 1w))

What each needs from the engine:

  • Label matching (code=~"5.."): postings intersection with regular-expression matching on label values. The index should keep label values sorted so prefix regexes can scan a range.
  • Range functions (rate, predict_linear): access to all samples in a window per series; chunk iteration must be fast.
  • Aggregation with grouping (sum by): hash aggregation across many series; this is where query sharding helps.
  • Offset: reading a past time range in the same query, so a two-range query may hit two different storage tiers.
  • topk: per-step ranking across series, which is cheap after aggregation but expensive over raw high-cardinality metrics.
Deep Dive: one alert, end to end with timingsShow

Scenario: at 14:00:00, a bad deploy makes 8% of checkout requests fail. The rule is "error ratio over 5 minutes above 5%, for 1 minute", evaluated every 30 seconds with a 15-second evaluation delay.

TimeEvent
14:00:00Errors start. Pods' http_requests_total{code="500"} counters climb
14:00:10Next scrape of each pod (10-second interval) captures the higher counters
14:00:12Scrapers batch and send to distributors; samples land in Kafka and then ingesters within about 2 seconds
14:00:30Rule evaluates at 14:00:15 data time. The 5-minute window contains only about 15 seconds of errors, so the ratio is about 8% × 15/300 = 0.4%. Inactive
14:01:30Window now contains about 75 seconds of errors: about 2%. Still inactive
14:03:30About 195 seconds of errors: about 5.2%. Condition true; state becomes Pending
14:04:30Condition has been true for 1 minute. State becomes Firing; alert sent to the alert manager cluster
14:05:00group_wait of 30 seconds ends; one notification for the checkout group goes to PagerDuty with a dedup key
14:05:05On-call engineer's phone rings

Total: about 5 minutes from first error to page. Notice where the time goes: most of it is the 5-minute averaging window, not the pipeline. The pipeline contributes seconds; the 1-minute for, the evaluation interval and group_wait add about 2 minutes. This is why "alert latency under 1 minute" in the requirements is measured from the moment the condition is met in the data, and why SLO burn-rate alerts with a 5-minute short window, or a shorter-window rule for severe failures (such as an error ratio above 50% over 1 minute), are used to page faster on catastrophic failures while keeping slower, quieter rules for minor ones.

Deep Dive: rough cost of the designShow

All figures are order-of-magnitude, to show which parts dominate.

  • Ingester memory. About 150 million active series (with churn headroom) at a few kilobytes each, times replication factor 3: on the order of 1 to 1.5 TB of RAM, for example 40 to 60 machines with 32 GB to 64 GB each after leaving headroom. Memory, driven by series count, is the largest single cost, which is why cardinality limits matter commercially as well as technically.
  • Kafka. About 1 GB/s before compression; with batching and compression perhaps 200 MB/s, times replication 3 is 600 MB/s of broker writes. Six hours of retention is about 13 TB across brokers. A dozen or two brokers with fast disks.
  • Object storage. Raw data for 15 days about 9 TB, 1-minute rollups for 90 days about 40 to 50 TB, 1-hour rollups for 2 years about 5 to 10 TB: about 60 to 70 TB. At list prices of roughly $0.02 per GB-month for standard object storage, about $1,200 to $1,400 per month, small compared with compute.
  • Queriers, store gateways, caches and rulers. Sized by query load; tens of machines, plus Memcached clusters for results, chunks and index caches.
  • Distributors and compactors. Distributors are stateless and CPU-bound (parsing, validation, hashing); compactors are batch jobs with bursts of object-storage I/O.

The cost lesson applies beyond this system. Amazon's Prime Video team wrote in 2023 that moving a stream-quality monitoring service from a distributed serverless design to a single process per stream cut its infrastructure cost by over 90%, mainly by avoiding per-step orchestration charges and intermediate object storage. The point is not "monoliths are better", but that at high, continuous data rates, per-call and per-transfer costs dominate, so data should stay in memory and move as little as possible. A metrics pipeline is exactly such a workload.

Deep Dive: testing a monitoring platformShow
  • Rule unit tests. Rules are code: test them with synthetic input series and expected alerts (promtool test rules does this for Prometheus rules). Test that an alert fires, that it does not fire on a short spike, and that it resolves.
  • Encoding and query correctness. Property-based tests: random series written and read back must be identical; rate over random counters with random resets must match a reference implementation; rollups must equal aggregates computed directly from raw data.
  • Load and soak tests. Replay recorded production traffic at 2× and 3× rate; run for days to catch memory growth from churn and compaction backlogs (see Capacity Planning and Load Testing).
  • Chaos tests. Kill ingesters, partition a zone, slow object storage, inject consumer lag, and check that quorum writes, replay and deduplication keep data complete and alerts on time.
  • Cardinality bombs. A test tenant that suddenly creates 10 million series must be throttled without affecting others.
  • End-to-end alert drills. A scheduled synthetic failure must produce a page within the target time, and the watchdog must page when the alert pipeline is deliberately broken. The drill is the only way to know the meta-monitoring works.
Deep Dive: the write path inside the cluster, step by stepShow

Following one remote-write request of 2,000 samples shows where each check and cost sits.

  1. Gateway. TLS termination and authentication. The gateway resolves the API key to a tenant id and sets it as a header. Requests without a valid key never reach the distributors.
  2. Distributor: decode and validate. The distributor decompresses the Snappy-compressed protobuf and checks each series: metric name present and valid, label names valid, label count and value lengths within limits, timestamps not too far in the future or past. Invalid series are dropped and counted per reason (discarded_samples_total{reason="label_value_too_long"}), so tenants can see why data went missing.
  3. Distributor: rate and series limits. The tenant's token bucket is charged 2,000 samples. If empty, the whole request gets HTTP 429 and the agent retries later from its queue.
  4. Distributor: HA deduplication. If the tenant runs Prometheus in an HA pair, each request carries cluster and replica labels. The distributor keeps an elected replica per cluster (in a key-value store) and accepts samples only from that one, failing over if it stops sending for a timeout (tens of seconds). This halves storage for HA pairs without losing data when one replica dies.
  5. Distributor: hash and route. For each series, hash (tenant, sorted labels) to a ring token and find the three ingesters (in three zones) that own it, or the Kafka partition in a Kafka-based design. Series are regrouped into one batch per destination.
  6. Ingester: append. For each series, look up its id in the in-memory series map (creating the series and its index entries if new, which is the expensive case), append the sample to the open chunk, and write the sample to the WAL. Samples older than the latest for that series go to the out-of-order buffer if within the window, or are rejected.
  7. Acknowledge. The distributor returns 200 once two of three ingesters (or the Kafka produce with acks from all in-sync replicas) succeed. The agent removes the batch from its queue.

The cheap path is step 6 for an existing series: a hash lookup and a few bytes appended. Everything that makes the system expensive, new series, invalid data, oversized labels, is caught in steps 2 to 4, before it reaches memory. That ordering is the essence of a robust write path.

Deep Dive: what deserves a pageShow

A technically perfect alerting system still fails if it pages people for the wrong things. Pager fatigue is a real reliability risk: engineers who are woken nightly by noise start ignoring pages, and the one real alert is missed. Guidance that most mature SRE teams converge on:

  • Page on symptoms, not causes. Users feel errors and latency, not CPU at 90%. Page on "checkout error ratio is burning the SLO budget", and show CPU, memory and queue depth on the dashboard the page links to. Cause-based alerts (disk filling, certificate expiring) become tickets unless they will become user-visible within hours.
  • Every page must be actionable and urgent. If the right response is "wait and see", it is not a page. If there is no runbook step, write one or delete the alert.
  • Severity maps to channel. page goes to the on-call phone; ticket creates a work item; info goes to a chat channel or nowhere. Routing in the alert manager enforces this.
  • Measure the alerting itself. Track pages per on-call shift, the fraction acknowledged and acted on, and time to acknowledge. An alert that fired 30 times last month with no action is a candidate for deletion. The alert manager's own history is the data source.
  • Review after incidents. Every incident review should ask: did an alert fire, how long after the start, was it the right alert, and was it routed to the right team? Gaps become new rules; noise becomes deleted rules (see Incident Management and Postmortems).

These practices are why the design puts so much weight on grouping, inhibition, silences, burn-rate rules and per-team routing: the platform should make the good practice the easy default.

Deep Dive: a 45-minute interview planShow
MinutesWhat to do
0 to 5Clarify: who sends metrics, push or pull, scale (series and samples per second), retention, dashboard and alert latency targets, multi-tenancy
5 to 10Estimates: 5M samples/s, about 600 GB/day compressed, series count and index memory, query and rule-evaluation load
10 to 18High-level design: collection, ingest through Kafka, TSDB, query layer, rule evaluator, alert manager, notifications
18 to 26Storage engine: series model, inverted index, head block and WAL, compressed chunks, blocks in object storage, compaction
26 to 33Fast dashboards: rollups and tiered retention, query frontend splitting and caching, recording rules, limits
33 to 39Alerting: evaluation loop, pending and firing, absence alerts, grouping, inhibition, HA dedup of notifications
39 to 43Cardinality and reliability: per-tenant limits, load shedding, replication, meta-monitoring
43 to 45Summary and extensions: SLO burn-rate alerts, logs and traces, high-cardinality analytics

The most common mistake is designing a generic "store events in a database" system. Name the time-series data model and its storage engine early; everything else follows from it.

Deep Dive: follow-up questions and short answersShow
  • "Why not store metrics in Cassandra?" It is possible (early versions of several systems did, and M3DB is Cassandra-inspired), and Cassandra handles the write volume. But it does not compress time series as well as a dedicated engine, has no inverted index for label queries, and its compaction is not designed around time-partitioned immutable blocks. A TSDB with object storage is cheaper and faster for this workload (see Apache Cassandra in Practice).
  • "How do you delete a tenant's data or a sensitive series?" Write tombstones, filter them at query time, and physically remove the data in the next compaction. Deletion is eventually complete, which should be stated in data-retention policies.
  • "How do you support a one-year query over raw data?" Usually you do not: you read 1-hour rollups, which give 8,760 points per series. If raw data is truly needed, run it as an asynchronous job against object storage.
  • "How do you get alert latency down to 5 seconds?" Streaming evaluation on the Kafka stream for a small set of simple rules, a 1-second scrape or push interval for those series, short windows, and no group_wait. Accept more noise and cost for those alerts only.
  • "What if Kafka itself is down?" Agents buffer to disk; distributors can fall back to writing directly to ingesters if the design supports it, or reject with 503 so agents keep buffering. Meta-monitoring pages on broker health.
  • "How would you add logs and traces?" Separate pipelines and stores (logs in an inverted-index or columnar log store, traces in a trace store), shared labels for correlation, and exemplars linking metrics to traces. Do not force logs into the metrics TSDB.

Key Takeaways#

  • Metrics are series, not rows. A series is a metric name plus labels; samples are (timestamp, value) pairs appended to it. Design the storage engine around that model.
  • Compression and time partitioning make storage cheap. Delta-of-delta timestamps and XOR-encoded values bring samples to about 1.4 bytes; time-partitioned immutable blocks in object storage make retention a matter of deleting old blocks.
  • Cardinality is the real limit. Samples are cheap; series cost memory and index space. Enforce per-tenant and per-metric limits, relabel ids away, aggregate at ingest, and send unbounded dimensions to logs, traces or columnar stores.
  • Fast dashboards come from reading less and recomputing less. Rollups chosen by range and step, recording rules, day-aligned query splitting with results caching, and per-query limits.
  • Alerts are a state machine. Pending, firing and resolved, with for durations, hysteresis, absence alerts and evaluation delay for late data. Shard rule groups across evaluators and isolate them from dashboard load.
  • The alert manager turns alerts into a few good notifications. Deduplicate, group, inhibit, silence, route, and deliver at least once with dedup keys across an HA cluster.
  • Protect the alerting path above everything. Buffers, priority load shedding, quorum replication across zones, separate query pools, and a dead man's switch plus meta-monitoring so the monitoring system cannot fail silently.
  • Get the math right. rate before sum, counter resets, histograms over summaries for fleet percentiles, and multiwindow burn-rate alerts for SLOs.