Prometheus: metric types, cardinality, PromQL, golden signals, and alerting on symptoms

Counters need rate(), gauges do not, histograms let you aggregate quantiles. One unbounded label is how you take Prometheus down.

Read the briefing
About 9 min to read 9 drills

What to remember

  1. rate() on counters, never the raw value. And the range should be at least 4× the scrape interval so a missed scrape does not blank it.
  2. Cardinality is memory. Every unique label set is a series. User ids and request ids belong in logs and traces.
  3. Histograms aggregate; summaries do not. histogram_quantile over summed bucket rates works; averaging pre-computed quantiles is meaningless.
  4. Golden signals: latency, traffic, errors, saturation. A dashboard missing one cannot tell you whether the service is healthy.
  5. Every page needs an owner and a runbook. And any alert nobody acted on gets deleted, not tuned down.

The big picture

Prometheus is the pull-based metrics system most SRE interview loops assume: targets expose /metrics, Prometheus scrapes them on an interval, stores every unique label set as its own time series, and PromQL turns those series into rates, aggregates and quantiles. Interviewers use it to test three things at once — whether you know what each metric type can and cannot tell you, whether you can keep cardinality bounded, and whether you know what deserves to page a human at 03:00.

The mental model

Every unique combination of metric name and label values is one time series: a row that costs memory from the moment it is first scraped, whether or not anyone ever queries it. Scrapes append samples to rows; PromQL reads across rows and across time. Counters are read only through rate(), gauges directly, histograms through bucket arithmetic. An alert is just a query evaluated on a schedule — page on what users feel, ticket what is about to break.

In depth

The scrape model and what `up` means

Prometheus pulls. Service discovery (Kubernetes, EC2, DNS, a file) produces targets; every scrape_interval (15 s is common, 30–60 s is fine for slow-moving fleet metrics) Prometheus performs an HTTP GET on each target's /metrics, parses the text exposition format, and appends one sample per series stamped with the scrape time. A scrape that fails or exceeds scrape_timeout (default 10 s) appends nothing to the target's series and sets the synthetic series up{job, instance} == 0. up is therefore the first thing to look at when a graph goes flat: it separates "the target died" from "the target reports zero".

Three consequences follow from pulling on an interval. First, rate() and its relatives need at least two samples inside their range, so a range shorter than two intervals is always empty and a single lost scrape empties a two-interval range too; the working rule is a range of at least four scrape intervals — [1m] on a 15 s scrape, [5m] as the default habit. Second, when a scrape fails or a series vanishes from a target's output, Prometheus writes a staleness marker so the series drops out of instant queries at once (a series with no marker — say Prometheus itself was down — is ignored after five minutes), which is why a deleted pod does not report its last value forever. Third, alerting rules run on their own evaluation_interval, and for: 10m means the expression must return a result on every consecutive evaluation for ten minutes: an empty result resets the pending timer, which is how an undersized rate() range silently disables an alert.

Storage has the same shape. Samples land in the in-memory head block and in the write-ahead log; every two hours the head is compacted into an immutable block on disk, and old blocks are deleted by retention. Memory is dominated by active series — a few KB each for the head chunk plus index entries — not by retention, which only governs how many blocks stay on disk. That is why a cardinality explosion kills Prometheus in minutes while doubling retention costs only disk.

Metric types and the functions that fit them

The four types are contracts about how a value moves, and each comes with the small set of PromQL functions that respect the contract.

A counter only increases, resetting to zero when the process restarts. Its raw value is nearly useless; you always ask for a rate. rate(http_requests_total[5m]) is the per-second average increase over the window, corrected for resets; increase() is the same quantity multiplied by the window length; irate() uses only the last two samples and belongs on zoomed-in graphs, never in alerts. Applying rate() to anything that can decrease produces garbage, because every decrease is treated as a reset.

A gauge moves both ways: queue depth, temperature, in-flight requests. Query it directly, smooth it with avg_over_time or max_over_time, describe its slope with deriv(), or extrapolate it with predict_linear(node_filesystem_avail_bytes[6h], 4*3600).

A histogram exposes cumulative buckets — http_request_duration_seconds_bucket{le="0.5"} counts every observation at or below 0.5 s — plus _sum and _count. Because the buckets are counters you can rate() them, sum by (le) across instances, and estimate a quantile at query time: histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))). The estimate interpolates linearly inside the bucket where the rank lands, so its precision is the bucket width; choose edges around the thresholds you care about. Note that "fraction of requests under 500 ms" needs no interpolation at all: sum(rate(..._bucket{le="0.5"}[5m])) / sum(rate(..._count[5m])), which is why SLO SLIs are usually written that way.

A summary computes quantiles inside the client process over a sliding window. They are exact for that one instance and mathematically impossible to aggregate — the average of two p99s is not a p99. Prefer histograms whenever more than one instance exists, which in production is always.

Cardinality: the number that takes Prometheus down

A time series is one metric name plus one unique set of label values, so series count is the product of the cardinalities of every label on the metric. http_requests_total with pod (200 values) × endpoint (5) × code (5) is at most 5,000 series. Add user_id with 50,000 active users and the bound becomes 250 million. Every active series costs memory from the moment it is first scraped — head chunk, index postings, symbol table, WAL entries — whether or not anyone queries it, so "we only look at it occasionally" is not a defence.

The rule: label values must be bounded enumerations you could list on one slide — endpoints, status classes, regions, instance names. Anything minted per request or per user (ids, emails, raw URL paths with ids embedded, query strings, churning container ids) belongs in logs or traces, which are indexed by those ids and priced per byte rather than per series. If a histogram must link a bucket to one concrete request, that is what exemplars are for.

Finding the offender is two queries. prometheus_tsdb_head_series over the last day shows when series jumped; topk(10, count by (__name__, job) ({__name__=~".+"})) shows what and whose. The /tsdb-status page lists the label names with the most values. Stopping the growth without a code change happens at the scrape: a metric_relabel_configs rule that drops the metric or the label, followed by a reload. Memory recovers only when the stale series are garbage-collected at the next head truncation, so expect the plateau to hold for an hour or two after the source is fixed.

The guardrails that make the next mistake fail locally are per-job sample_limit, label_limit, label_name_length_limit and label_value_length_limit: a target that exceeds them fails its own scrape (up == 0 for that target) instead of taking fleet-wide alerting down with it. Pair them with an alert on the growth rate of head series and on scrape_samples_post_metric_relabeling per job, and with a review rule that every new label is an enumeration with an owner.

PromQL you must be able to write on a whiteboard

Interviewers ask for three queries and listen to the labels as much as to the functions.

Error ratio at the edge:

sum(rate(http_requests_total{job="api",code=~"5.."}[5m]))
  / sum(rate(http_requests_total{job="api"}[5m]))

Both sides are aggregated with sum so the label sets match. A bare rate(...{code=~"5.."}) divided by rate(...) would try to match code="500" against code="200" and return nothing. For a ratio per route, aggregate both sides by (route).

p99 latency from a histogram:

histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{job="api"}[5m])))

The by (le) is not optional. Without it the buckets collapse into one series with no le label, the function silently ignores that series and returns nothing, and an empty result never satisfies > 1 — an alert that can never fire and that promtool check rules accepts. Add labels to the clause (by (le, route)) for a quantile per route; never drop le.

Capacity, expressed as a symptom rather than a cause: count(up{job="api"} == 1) < 2 pages on lost redundancy instead of on any single restart, and predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 4*3600) < 0 pages only when the disk fills inside the on-call response window.

Two habits complete the set. Recording rules (job:http_requests:rate5m) precompute anything a dashboard or alert evaluates repeatedly, which keeps query latency flat as the fleet grows. And absent(up{job="api"}) catches the failure where a job disappears from service discovery entirely — every other expression then returns nothing, which looks exactly like "no errors" on a dashboard.

Golden signals and what deserves to page

The four golden signals are latency, traffic, errors and saturation. The first three describe what users feel — RED (rate, errors, duration) for a request-driven service — and saturation describes what is about to break — USE (utilization, saturation, errors) for a resource such as a thread pool, a disk or a queue. A dashboard missing one of them cannot say whether the service is healthy, and a service that reports only CPU and memory is reporting causes with no symptoms.

The alerting rule follows directly: page on symptoms that are user-visible and need a human now; route causes to tickets and dashboards. The error ratio at the edge, latency against the SLO threshold, or the SLO burn rate are symptoms. Disk at 80%, a single pod restart, one replica down, GC time — causes with redundancy or hours of runway behind them — become tickets or panels; the exception is saturation whose predicted time to exhaustion is shorter than the response window. Every page also carries an owner, a runbook link and a for: clause sized to ride out flaps, and any page that fires without someone acting on it is deleted or demoted, because a pager that cries wolf trains on-call to ignore the one that matters.

Thresholds come from the SLO, not from taste. A 99.9% availability SLO has an error budget of 0.1%; an error ratio of 14.4 × 0.001 = 0.0144 sustained for an hour spends 2% of a 30-day budget, which is the standard fast-burn page. The multi-window scheme lives in the SLO node; the point here is that a threshold you cannot derive is a threshold nobody will defend at 03:00 — and "alert on p50" or "alert on CPU > 80%" are the two answers interviewers reject most often.

Running it at scale: HA, sharding and long-term storage

A single Prometheus comfortably holds a few million active series on a large machine; beyond that, and for availability, the shape changes. High availability is two identical servers scraping the same targets, with Alertmanager — itself a gossip cluster — deduplicating the alerts both send. There is no leader election and no shared database; both simply run. Capacity comes from sharding targets by a hash of the address across scrape shards so each holds a bounded head, and alerting rules are evaluated on the shards, never only behind a global query layer, because that layer must be allowed to fail without silencing pages. Long-term retention moves two-hour blocks to object storage through a sidecar or remote write (Thanos, Cortex and Mimir are the usual names), with a query layer that fans out, deduplicates HA pairs and serves recording-rule results to dashboards. The arithmetic to have ready: 20 M series at 15 s is 1.33 M samples/s; at roughly 1.5–2 bytes per sample compressed that is 170–230 GB/day; and a few KB of head memory per active series is what decides the shard count, not the retention period.

Myths and facts

Myth: Labels are query-time filters, so adding one is free until someone queries it.

Fact: Each distinct label set is materialised as its own series at scrape time, held in the head block and index whether or not it is ever queried; series count is the product of label cardinalities.

Myth: rate() on a gauge tells me how fast it is changing.

Fact: rate() assumes a monotonic counter and treats every decrease as a reset, inventing increases exactly when the gauge falls. Use deriv(), delta() or the raw level for gauges.

Myth: histogram_quantile returns the exact p99.

Fact: It interpolates linearly inside the bucket where the rank lands; the true value is only known to within the bucket edges, and without sum by (le) it returns nothing at all.

Myth: Longer retention needs more memory.

Fact: Retention governs blocks on disk. Memory is the number of active series in the head block (the last two to three hours), so cardinality, not retention, is what OOM-kills Prometheus.

Myth: Paging on up == 0 for every instance is the safe default.

Fact: One replica of a replicated service is a cause absorbed by redundancy; it pages on every rolling restart. Page on the symptom (error ratio, latency, burn rate) or on lost capacity, and ticket the instance.

Myth: Summaries are better than histograms because their quantiles are exact.

Fact: Exact per instance and impossible to aggregate across instances; histograms lose bucket precision but aggregate correctly with sum by (le), which is what a fleet needs.

How pros do it

  • Keep every label value a bounded enumeration you could list; put ids, emails and raw paths in logs, traces or exemplars, never in labels.
  • Use rate() ranges of at least four scrape intervals ([5m] by default), and put anything a dashboard or alert evaluates repeatedly into a recording rule.
  • Choose histogram bucket edges at your SLO thresholds and always aggregate with sum by (le) before histogram_quantile; write latency SLIs as a fraction-under-threshold so they need no interpolation.
  • Page only on user-visible symptoms tied to the SLO, with a for: clause, an owner and a runbook; route causes to tickets; delete any page nobody acts on.
  • Put sample_limit and label limits on every scrape job so a cardinality mistake fails one target instead of the fleet, and alert on head-series growth.
  • Run scrapers as HA pairs deduplicated in Alertmanager, evaluate alert rules on the scrapers, and name metrics with base units and suffixes (_seconds, _bytes, _total).

Questions people ask

How do you decide what should page?

State the rule, then apply it: page on user-visible symptoms that need a human now — error ratio and latency at the edge, SLO burn rate — and ticket causes that have runway behind them, such as disk at 80% or one replica down. Add that every page has an owner, a runbook and a for: clause, and that a page nobody acts on is deleted. If they push for a number, derive it from the SLO: 14.4 × (1 − SLO) over an hour is the fast-burn page.

How do I find which metric is exploding cardinality?

Two queries: prometheus_tsdb_head_series over the last day for when, and topk(10, count by (name, job) ({name=~".+"})) for what and whose; the /tsdb-status page lists the label names with the most values. Stop it at the scrape with metric_relabel_configs while the owning team fixes the source, and say that memory only recovers at the next head truncation, an hour or two later.

Histogram or summary?

Histogram, almost always — say it, then why: the buckets are counters, so they rate() and sum across instances with by (le), and a fraction-under-threshold comes out exact. A summary computes quantiles inside each client, and two p99s cannot be averaged into a fleet p99. The cost is a series per bucket and precision bounded by bucket edges, so put edges at your SLO thresholds.

How much memory does Prometheus need?

A few KB per active series plus query headroom — roughly 2–4 GB per million series for the head — so a 64 GB machine is comfortable to about ten million series. Then say the thing most people get backwards: retention barely matters for memory; cardinality is what OOM-kills Prometheus.

What is the difference between rate, irate and increase?

rate is the average per-second increase over the whole range; increase is rate × the range length, the total; irate uses only the last two samples. Then the operational line: irate is for zoomed-in graphs and never for alerts, because it amplifies momentary spikes and dropouts.

Why does my rate() graph have gaps when the target is up?

The range holds fewer than two samples at some evaluation points — a range of one or two scrape intervals plus a late scrape. Widen it to at least four intervals ([5m] on a 15–30 s scrape); the smoothing is the point. Add that an empty evaluation also resets an alert's for: timer, so an undersized range silently disables alerting.

Why does histogram_quantile return nothing, or NaN?

Empty means the input lost its le label — usually a sum() without by (le) — so every sample was silently ignored; NaN means the buckets it found are all zero over the range, or there is no +Inf bucket. Aggregate with sum by (le), and say that promtool check rules passes this bug, so test rules with synthetic samples.

Is for: 5m enough to stop an alert flapping?

It stops one-evaluation blips, not a condition that oscillates around the threshold. Use a range long enough to smooth the signal, a threshold derived from the SLO, and for burn-rate alerts a short window paired with a long one so the alert resets when the burn stops.

Further reading

Drills · 9

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

http_requests_total carries the labels pod (200 values), endpoint (5) and code (5), so about 5,000 series. A developer wants to add a user_id label (50,000 active users) "so we can see per-customer error rates". What happens if they do, and where does that detail belong?

  1. It is fine as long as the scrape interval is lengthened, since fewer scrapes means fewer series. The interval changes samples per series, not the number of series; cardinality is the count of distinct label sets, and memory scales with that count.
  2. Series count is bounded by the product of label cardinalities — up to 5,000 × 50,000 ≈ 250 million series — and every active series costs a few KB of memory plus index entries, so Prometheus runs out of memory and scrapes start failing. Per-customer detail belongs in logs or traces indexed by the id (or in exemplars); metric labels stay bounded enumerations. Each distinct label set is a separate time series that exists from the moment it is scraped; multiplying by an unbounded identifier multiplies memory, index size and scrape time.
  3. This is exactly what labels are for — add email too so support can search by customer. Unbounded identifiers (user, email, request id, raw path) are the canonical cardinality bombs; they belong in logs and traces, which are indexed by id and priced per byte, not per series.
  4. Nothing dramatic — labels are query-time filters, so the cost is only paid when someone actually queries by user_id. A label set is materialised as its own series at scrape time, stored in the head block and indexed, whether or not anyone ever queries it.
In short

Each unique label set is its own time series, so a user_id label multiplies memory until Prometheus dies; per-user detail belongs in logs or traces.

Why

A time series in Prometheus is one metric name plus one unique combination of label values. Every active series holds a head chunk, an entry in the in-memory index and the symbol tables, and is written to the WAL — a few kilobytes each. Adding a label whose values are user ids turns 5,000 series into up to 250 million, so memory grows by four orders of magnitude, scrapes slow down, and the process is OOM-killed; on restart it replays the WAL and dies again. The rule is that label values must be bounded enumerations you could list (endpoints, codes, regions). Per-request or per-user detail is what logs and traces are for; an exemplar can link a histogram bucket to one trace id without creating a series per user.

The common mistake

Treating labels as free query-time filters. Every distinct label set is a series that costs memory from the first scrape, whether or not anyone ever queries it.

Read the docs

2 Answer out loud

A team asks you to review their alerting: 40 alerts, all paging, mostly on CPU, disk and pod restarts. What are the four golden signals, which of their alerts should page and which should not, and what one rule would you apply to every future alert? Three to six sentences.

In short

A strong answer names latency, traffic, errors and saturation, pages only on user-facing symptoms, and gives every page an owner and a runbook.

What a strong answer does
  • golden signals: Names all four, distinguishes what users feel (latency, errors — RED) from what is about to break (saturation — USE), and ties them to the SLO.
  • paging philosophy: Page on symptoms that need a human now (error ratio, latency at the edge, ideally burn-rate with a for:); causes go to tickets/dashboards except saturation with a short predicted time-to-exhaustion; every page has an owner and runbook; pages nobody acts on are deleted; gives a rough before/after count.
  • communication: Signals → which of their alerts page and why → the rule; decisive, concrete, ends with a recommendation.
Why

Interviewers listen for the symptom/cause split, the four signals stated as what users experience rather than as machine resources, and the discipline that every page has an owner, a runbook, and a reason a human is needed now. The staff-level tells are tying thresholds to the SLO (burn rate) and treating "delete pages nobody acts on" as part of the design.

The common mistake

Naming CPU, memory, disk and network as the golden signals, or saying everything should page 'so nothing is missed'. Those are resources and causes; the signals are latency, traffic, errors and saturation, and a pager that cries wolf gets ignored.

Read the docs

3 Pick the strongest answer

A team proposes four alerts for a customer-facing API with a 99.9% availability SLO over 30 days. Which one is worth waking a human at 03:00 for, and why not the others?

  1. up{job="api"} == 0 — an instance of the API is down. One replica of a replicated service is a cause absorbed by redundancy; users feel nothing. Page on remaining capacity or on the symptom, ticket the dead instance.
  2. histogram_quantile(0.5, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))) > 0.3 — median latency has doubled. The median hides the tail users actually hit; a p50 shift is a capacity or regression signal for a dashboard. Latency pages use p99 or a good-fast-requests ratio tied to the SLO.
  3. sum(rate(http_requests_total{code=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) > 0.0144 with for: 2m — the error ratio at the edge at a 14.4× burn rate, which exhausts the whole 30-day budget in about two days. A user-visible symptom, quantified against the SLO, that will cost real budget within hours is exactly what a page is for.
  4. node_filesystem_avail_bytes / node_filesystem_size_bytes < 0.2 — the disk will eventually fill and break the service. Disk at 80% is a cause with hours or days of runway; it belongs in a ticket. Page when the symptom appears, or when predict_linear says it fills within the on-call response window.
In short

Page only on the edge error ratio above 14.4 times the error budget; the disk, one dead replica and median latency belong in tickets or dashboards.

Why

The paging rule from the SRE book: page on symptoms that are user-visible and need a human now; route causes to tickets and dashboards. The error ratio at the edge is a symptom; its threshold is derived from the SLO — 14.4 × (1 − 99.9%) = 0.0144 — so it fires when the budget is burning fast enough that waiting until morning is not an option. Disk usage and a single down replica are causes with redundancy or time behind them, and median latency is the wrong statistic for anything users feel. Every page also needs an owner and a runbook; a page nobody acts on is noise that trains on-call to ignore the pager.

Read the docs

4 Find what's broken

You are asked to review this rule file after a bad week: promtool check rules passes, but during an incident p99 latency sat at 3 s for 20 minutes and no latency alert fired; ApiQueueGrowing opens tickets while the queue is draining; and on-call was paged four times during a routine rolling deploy. Which lines are wrong, and how do you fix them?

groups:
  - name: api.rules
    rules:
      - alert: ApiHighErrorRatio
        expr: |
          sum(rate(http_requests_total{job="api",code=~"5.."}[5m]))
            / sum(rate(http_requests_total{job="api"}[5m])) > 0.0144
        for: 2m
        labels:
          severity: page
        annotations:
          runbook_url: https://runbooks.example.com/api-error-ratio
      - alert: ApiHighLatencyP99
        expr: histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket{job="api"}[5m]))) > 1
        for: 5m
        labels:
          severity: page
      - alert: ApiQueueGrowing
        expr: rate(api_queue_depth[5m]) > 100
        for: 10m
        labels:
          severity: ticket
      - alert: ApiInstanceDown
        expr: up{job="api"} == 0
        labels:
          severity: page
      - alert: NodeRootDiskLow
        expr: node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"} < 0.2
        for: 30m
        labels:
          severity: ticket
In short

Three fixes: add by (le) to the histogram_quantile, do not use rate() on a gauge, and stop paging on a single up == 0 with no for clause.

What's broken
  • Line 14: sum(rate(..._bucket[5m])) without by (le) collapses all buckets into one series with no le label, so histogram_quantile silently ignores the input and returns an empty result, which never satisfies > 1.
  • Line 19: rate() on a gauge: api_queue_depth goes down as well as up, and rate() treats every decrease as a counter reset, so a draining queue produces a large positive 'rate'.
  • Line 26: Paging on a single instance of a replicated service with no for: — every rolling restart briefly yields up == 0 and pages a human for something redundancy absorbs.
Why

Three separate mechanisms. histogram_quantile needs the le label to know the bucket boundaries; aggregating without by (le) throws that away, and the function silently returns an empty result rather than erroring — which is why promtool is happy and the alert is dead. rate() is defined for counters: it assumes any decrease is a reset and adds the post-reset value, so applying it to a gauge invents increases exactly when the value falls. And up == 0 for one replica is a cause, not a symptom; without for: it fires on every restart. The suspicious-looking lines are fine: 0.0144 (line 7) is 14.4 × the 0.1% error budget of a 99.9% SLO, for: 2m (line 8) is right for a fast-burn page, and the disk ratio (line 28) divides two series with identical label sets and is correctly a ticket.

Read the docs

5 Scenario: what do you do next?

10:40. The production Prometheus (single replica, 64 GB memory limit) has been OOM-killed three times since 10:15; each restart replays the WAL for ~6 minutes, during which nothing alerts. prometheus_tsdb_head_series was a steady 4.2 M yesterday. The search service deployed at 10:05. Prometheus is up right now.

Step 1. You have a few minutes before it dies again. What do you look at first?

  1. Restart with --storage.tsdb.retention.time=7d to shrink the database. Retention governs blocks on disk; the head block holds the active series of the last ~2–3 hours regardless of retention. It does nothing for memory.
  2. Raise the memory limit to 128 GB and move on. An unbounded label grows without bound; doubling memory buys minutes to hours and hides which metric is responsible. It may be a stopgap later, not a first move.
  3. prometheus_tsdb_head_series over the last 24 h, then topk(10, count by (__name__, job) ({__name__=~".+"})) — series growth per metric and job says whether the 10:05 deploy introduced a high-cardinality label and which metric carries it. Evidence first, and it is cheap: two queries name the metric and the job in seconds, which decides whether the fix is a rollback, a relabel, or something unrelated to the deploy.
  4. Roll back the search deploy immediately — it correlates in time. Plausible, but you do not yet know the deploy is the cause (a new scrape target or a relabel change also fits); the query takes ten seconds and tells you exactly what to roll back.

Step 2. search_request_duration_seconds_bucket went from 12 k to 9.8 M series; the new label is query (the raw search string) on a histogram with 12 buckets. Head series total is 14 M and climbing. What now?

  1. Stop the growth at the scrape: add a metric_relabel_configs rule on the search job that drops search_request_duration_seconds_.* (action: drop on __name__), reload Prometheus, and ask the search team to roll back or hotfix the label. Memory only falls when the stale series are garbage-collected at the next head truncation, so raise the limit as a bridge if needed. Reversible, minutes to apply, and it removes the source of growth; losing search latency metrics for an hour is a smaller outage than losing all alerting.
  2. Increase the search job's scrape_interval to 5 m to reduce load. Series count is unaffected by interval; memory is per active series, not per sample rate.
  3. Delete the series with the admin API (/api/v1/admin/tsdb/delete_series) for that metric. Deletion tombstones data in blocks, but the scrape recreates every series 15 s later; it does nothing to the source, and the admin API is disabled by default.
  4. Leave it — Prometheus is up now; the search team can fix it in their next sprint. Every new distinct query string adds 12 series; it will OOM again within the hour, and each restart is six blind minutes.

Step 3. Prometheus is stable at 4.5 M series. The postmortem asks for the systemic fix. Which do you propose?

  1. Write a wiki page reminding developers not to add high-cardinality labels. A reminder is not a mechanism; the next team will not have read it.
  2. Double Prometheus memory permanently and run two replicas. HA replicas ingest the same series and die together; memory cannot bound an unbounded label.
  3. Switch the latency metric to a summary so buckets stop multiplying. The multiplier is the query label, not the 12 buckets; summaries still emit per-label-set series and cannot be aggregated across instances, so this trades a 12× factor for losing aggregability.
  4. Per-job limits in the scrape config (sample_limit, label_limit, label_value_length_limit) so a target that explodes fails its own scrape instead of taking Prometheus down; an alert on the growth rate of prometheus_tsdb_head_series and on per-job scrape_samples_post_metric_relabeling; and a metrics-naming rule enforced in review that label values must be bounded enumerations. Verify by shipping a deliberately bad label in staging and watching that scrape fail while Prometheus stays healthy. Contains the blast radius mechanically, detects the next one early, and states how to prove it works — mechanisms with verification, not intentions.
In short

Find the exploding metric with the head-series graph and a count-by query, drop it at the scrape with metric_relabel_configs, then add per-job sample limits.

Why

Cardinality incidents have a fixed shape: the head-series gauge shows when, count by (__name__, job) shows what, and the mitigation lives in the scrape pipeline (metric_relabel_configs) because that is the only place the growth can be stopped without a code change. Memory recovers only when the stale series are dropped at head truncation, so a temporary limit increase can be a legitimate bridge once the source is stopped. The durable fix moves failure to the offender: sample_limit makes a cardinality bomb fail one scrape instead of the whole monitoring system, and a growth alert catches the next one at 10:06 instead of 10:15.

Read the docs

6 Design round

Design a metrics ingestion and query service for a fleet of 10,000 hosts, each exposing about 2,000 time series, scraped every 15 seconds. Requirements: 30-day retention; any query over a 1-hour range answers within 2 s at p99; alerting keeps working if any single machine in the metrics system dies. Give the numbers first (samples/s, storage per day and for 30 days, memory, machine count) with justification, then the design, its failure modes, and how you would verify it.

  • Prometheus-compatible: targets expose /metrics and PromQL must keep working for existing dashboards and rules.
  • Budget: at most ~20 machines of 64 GB RAM, 16 cores, 4 TB NVMe for the whole system.
  • Any team may add labels at any time; the design must survive a cardinality mistake without losing fleet-wide alerting.
In short

A strong answer computes 1.33 million samples per second and 60 to 80 GB of memory, shards scrapes into HA pairs, and evaluates alerts on the shards.

A strong answer covers
  • States the arithmetic: 20 M active series; 20 M / 15 s ≈ 1.33 M samples/s; ≈ 115 G samples/day; at 1.5–2 bytes/sample compressed ≈ 170–230 GB/day and ≈ 5–7 TB for 30 days.
  • Sizes memory from active series (a few KB per head series → 60–80 GB for 20 M) and concludes one Prometheus cannot hold it; shards scrape targets by hash (e.g. 8 shards × 2.5 M series, ≈ 10 GB head each).
  • Runs each shard as an HA pair of identical scrapers with query-time deduplication, and evaluates alerting rules on the shards (not on the global query layer) so losing any one machine blinds nothing.
  • Separates hot from long-term: local TSDB for recent data, object storage or remote write (Thanos/Cortex/Mimir-style) for 30 days; a query layer fanning out to shards, with recording rules and result caching to hold the 2 s p99 for 1-hour ranges.
  • Cardinality guardrails: per-scrape sample_limit and label limits so a bad target fails its own scrape, an alert on head-series growth per shard, and an owner for label review.
  • Verification plan and tradeoffs: synthetic targets at 1.3 M samples/s in staging, kill one shard member and confirm alerts still fire, measure query p99; names HA doubling ingest cost and object storage adding latency for old ranges.
What a strong answer does
  • estimation and sizing: Samples/s, bytes/day, 30-day total, head memory from active series, shard count and machine count each derived and rounded with justification.
  • design quality: Sharded scrapers in HA pairs, alerting on shards, long-term store, query layer with recording rules/caching, per-target limits, failure modes named.
  • communication: Requirements restated, numbers, design, failure modes, verification, explicit tradeoffs and a decision.
Why

The exercise rewards deriving each number from the one before it — series → samples/s → bytes/day → memory → shards → machines — and then placing alerting where a single failure cannot silence it. Candidates who name Thanos or Cortex without the arithmetic, or who put alert evaluation behind the global query layer, miss what interviewers are actually scoring: that memory scales with active series, that sharding plus HA pairs is the unit of both capacity and availability, and that cardinality mistakes must fail locally.

Read the docs

7 Quick recall

You need latency quantiles that aggregate correctly across many instances. Histogram or summary?

In short

Histogram: bucket counts add up across instances, and quantiles from summaries do not.

Accepted

histogram · histograms · a histogram

Why

Histogram: its buckets are counters, so they can be rate()d and summed across instances with sum by (le), and a quantile is estimated at query time. A summary computes quantiles inside each client, and two p99s cannot be averaged into a fleet p99. The price is a series per bucket and precision bounded by bucket edges, so put edges at your SLO thresholds.

Read the docs

8 Pick the strongest answer

A team brings you a puzzle: their job is scraped every 30 s, a dashboard panel on rate(http_requests_total[1m]) shows intermittent gaps, and an alert on the same expression with for: 10m never fired during a known 25-minute outage. What is going on, and what do you tell them to change?

  1. Shorten the range to [30s] so it matches the scrape interval and stops averaging. A 30 s range holds at most one sample, so the rate is always empty; rate() is always an average over its window, and that is the point.
  2. rate() needs at least two samples inside its range. A 1 m window over a 30 s scrape holds exactly two, so any single failed or late scrape leaves one and the expression returns nothing — a gap on the graph, and an empty evaluation that resets the alert's for: timer so it never reaches 10 minutes. Use a range of at least 4× the scrape interval ([2m] minimum; [5m] is the usual default). Two samples is the minimum for a rate and leaves no tolerance; four scrape intervals survive one missed scrape, and a continuously non-empty result is what for: requires.
  3. rate() always looks back to the previous sample regardless of the range, so the gaps must be scrape failures — fix the target, not the query. rate() only considers samples whose timestamps fall inside the range vector; nothing outside [1m] is used, so the range is exactly what decides whether a rate exists.
  4. Switch the alert to irate(), which is more precise and immune to gaps. irate() uses only the last two samples in the range, so it is even more sensitive to a missing sample and to momentary spikes; it is for high-resolution graphs, never for alerting.
In short

A 1-minute range holds only two samples at a 30-second scrape, so one missed scrape empties rate(); use a range of at least 4 times the scrape interval, like 5m.

Why

rate(v[r]) finds the samples inside the window r, computes the per-second increase between the first and last (correcting for counter resets), and extrapolates to the window edges. With one sample there is no increase to compute, so the series is absent from the result. Alerts with for: must see the condition true on every consecutive evaluation; an evaluation with no result drops the alert from pending back to inactive, so a flapping empty result guarantees the alert never fires. The rule of thumb — range ≥ 4× scrape interval — buys tolerance for a lost scrape and a smoother, more honest average.

Read the docs

9 Read the output

A developer runs the p99 query — histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{job="api"}[5m]))) — over these buckets and asks you two things: what number comes back, and can they quote it to the millisecond in the SLO report?

# Prometheus UI, Table view. Query:
sum by (le) (rate(http_request_duration_seconds_bucket{job="api"}[5m]))

Element            Value
{le="0.1"}         600
{le="0.25"}        840
{le="0.5"}         940
{le="1"}           985
{le="2.5"}         998
{le="+Inf"}        1000
  1. Exactly 2.5 s — the first bucket whose cumulative count exceeds 99% of the total is le="2.5". The function interpolates inside the bucket rather than returning its edge; the upper edge is returned only when the rank lands exactly on it (or for the +Inf bucket, where it returns the lower edge).
  2. It cannot be computed from rates — quantiles need the raw bucket counters. A quantile depends only on the shape of the distribution; per-bucket rates preserve the proportions, remove counter resets, and are the documented way to compute it.
  3. 1.0 s — 98.5% of requests were under 1 s, which is close enough to 99%. 985 < 990, so the 99th percentile lies above 1 s; the function interpolates into the next bucket rather than rounding down.
  4. ≈ 1.58 s. The rank is 0.99 × 1000 = 990 requests/s, which falls in the (1, 2.5] bucket (cumulative 985 → 998); linear interpolation places it 5/13 of the way up: 1 + (5/13) × 1.5 ≈ 1.58 s. The true p99 is only known to be somewhere in (1, 2.5] — the bucket edges are the real precision. histogram_quantile assumes observations are spread uniformly inside a bucket and interpolates; the estimate can be off by up to a bucket width.
In short

About 1.58 seconds: the 99th percentile falls in the 1 to 2.5 second bucket and is interpolated, so the true value is only known to be inside that bucket.

Why

Histogram buckets are cumulative: le="1" counts every observation ≤ 1 s. histogram_quantile(φ, b) finds the bucket where the cumulative count first reaches φ × total and interpolates linearly between the bucket's lower and upper bounds, assuming a uniform spread inside it. Here 990 of 1000 lands between 985 (≤ 1 s) and 998 (≤ 2.5 s), 5/13 of the way, so ≈ 1.58 s. Two consequences interviewers probe: precision is bounded by bucket edges (choose buckets around your SLO threshold), and the sum by (le) is mandatory — aggregating without le collapses the buckets and the function silently returns nothing.

Read the docs

Next lesson Release engineering: canary, blue/green, progressive delivery, flags, rollback first, and deploy hygiene
Drill · Prometheus
0:00

Loading…