Zeeshan Adil
Book a call
← All writing
Cover of Why High Cardinality Exhausts Prometheus: Series, Head Memory and Churn

Why High Cardinality Exhausts Prometheus: Series, Head Memory and Churn

by Zeeshan Adil·in KubernetesUpdated 20 min read
Listen to this articleWhy High Cardinality Exhausts Prometheus: Series, Head Memory and Churn 22 min · read by an AI voice
0:00 / 22:12

How high-cardinality labels and churn affect Prometheus memory, WAL replay and queries, with ways to measure series and reduce unnecessary ingestion.

THE SHORT VERSION

  • Prometheus documents roughly one to two bytes per sample as a disk-sizing average; distinct series also add head memory, index, WAL and replay costs.
  • Cardinality is the series count. Unbounded labels and changing Pod names grow it; classic histogram buckets multiply it even when the bucket set is fixed.
  • The head retains recent series beyond their last sample. On a churning fleet, overlapping generations can make head cardinality much larger than the live count.
  • Measure with prometheus_tsdb_head_series and TSDB stats, then reduce unneeded series while preserving unique label sets and the detail your operators need.

A new label can look harmless in a metrics review. A few deploys later, Prometheus is using much more memory, restarting takes longer, and a dashboard query is dragging. Sample volume matters, but a label can also multiply the number of distinct time series Prometheus must track. That series count affects head memory, replay, and queries, especially when old label values keep being replaced by new ones.

"High cardinality" is the name for that, and it is usually explained as a rule: don't put user IDs in labels. That rule is correct and it is not enough. Once you understand how the storage engine actually holds a series, you can predict which labels will hurt, how much, and when, and you can design metrics for a fleet that churns thousands of Pods a day without guessing.

So this starts at the bottom.

Reading path: This assumes you have seen a metric with labels; it explains what a time series is before discussing storage. Read in order to understand the cost. If you are investigating a running server, start with measuring cardinality, then controlling it. Check the tradeoffs before removing a label you use for diagnosis.

Part 1: What Prometheus stores

Prometheus pulls. On a schedule, usually every 15 to 60 seconds, it fetches a text page from each target. The page is a list of lines like:

Code
http_requests_total{method="GET", status="200", engine="chrome"} 18342

Three parts. A metric name. A set of label name and value pairs. A number. Prometheus stamps the number with the scrape time and stores it.

Cardinality is the count of distinct series. The arithmetic is multiplication: a metric with a method label of 4 values, a status label of 5 values and an engine label of 7 values can have up to 140 series. Add a label with a thousand values and it is 140,000. Add one whose values never repeat, like a request ID, and it is unbounded.

That is the model most explanations stop at. The reason it matters is in the next part.

For one metric, four possible method values, five status values and seven engine values can produce up to 140 series. The maximum occurs only if every combination appears.

Part 2: How the storage engine holds a series

Prometheus's storage is its own time series database, usually just called the TSDB. It has two halves: a recent, in-memory half called the head, and a set of immutable blocks on disk for everything older. A sample's life goes head first, then block, then deletion by retention.

The head block

When a sample arrives for a series, Prometheus finds that series' in-memory record and appends the sample to its current chunk. A chunk is a small compressed buffer of consecutive samples for one series. Prometheus uses a delta-of-delta and XOR encoding, the design usually referred to as Gorilla compression, and the storage documentation uses an average of one to two bytes per sample as a rough disk-sizing estimate. That average is not a guarantee for every workload, and it is not the total in-memory cost.

Each series also has an in-memory record that holds its label set, references to its chunks, and the current open chunk. When a chunk fills, roughly 120 samples by default in current implementations (an implementation detail, not a documented guarantee), it is written to disk and memory-mapped, and only a reference stays in RAM. So the per-series memory is not mainly samples. It is the labels, the index entries, the chunk references and the bookkeeping. That cost is paid once per series regardless of how many samples it has. Series are expensive. That is the second half.

The write-ahead log

The head lives in memory, so a crash would lose it. To prevent that, every new series and every batch of samples is also appended to a write-ahead log on disk, in segments of 128 MiB by default. The log has record types for series, which carry the full label set, and for samples, which carry a series reference and values.

On restart, Prometheus replays the log to rebuild the head. Every series record must be read and every series re-created in memory before the server can serve queries. Series churn can make restart replay expensive because Prometheus must reconstruct series and their samples. Replay time also depends on WAL volume, disk performance, and the server's configuration; it is not determined by series count alone.

Compaction to blocks

The head keeps a window of recent data, two hours by default. When the head spans one and a half times that, three hours, the oldest two hours are written out as a persistent block and the head is truncated. At that truncation, series that have no chunks left in the head are garbage collected from its index, and the write-ahead log is truncated and checkpointed to match.

A block on disk is a directory: the chunk files, a meta.json describing its time range, a tombstones file for deletions, and an index. The index is what makes queries possible and what makes cardinality expensive at rest. It holds a symbol table of every distinct string in every label pair, a series section listing every series with its labels and chunk references, and postings lists, which for every label pair record which series carry it.

Blocks are periodically compacted together into larger blocks covering longer ranges, and retention deletes whole blocks once they age out.

Part 3: Where cardinality actually costs you

Now put the two halves together. Samples compress well on disk, but a series also needs memory and index bookkeeping, and both series and samples contribute to the WAL. Five places are especially worth watching.

Head memory. Every series alive in the head window has an in-memory record, plus its entry in the head's own index and postings. Double the series, roughly double that memory. This is the number behind most Prometheus out-of-memory restarts.

The retention tail. The head does not immediately forget a series when its target disappears. Recent chunks remain until head truncation and garbage collection, so several generations of short-lived targets can coexist in head memory. The timing depends on sample and block boundaries and the Prometheus version; the two-to-three-hour head window is a model, not a per-series expiry timer.

Restart time. Write-ahead log replay walks every series record. An instance with five million series in its window can take many minutes to come back, during which alerts are blind.

Query cost. A query like rate(http_requests_total[5m]) has to find every matching series through the postings lists, then decode chunks for each. A thousand series is fast. A million is not, and a dashboard with ten such panels multiplies it. Queries that look innocent are expensive because of the series behind them, not the math.

Money, on managed platforms. Managed services price this in different units. Grafana Cloud bills on active series. Google Managed Prometheus and Amazon Managed Prometheus price on samples ingested, which series count still drives, because every series is sampled on every scrape interval. Check each provider's current pricing page for the unit and the rate. Either way, cardinality becomes a line item.

Part 4: Which labels explode

With the mechanism in hand, the dangerous labels are predictable. Any label whose values are unbounded or short-lived multiplies series by churn:

LabelWhy it explodesWhere it belongs instead
Pod name on an autoscaling fleetUnique forever, replaced constantlyLogs, with the Pod name in the line
Request or trace IDUnique per requestTraces or logs
User or customer IDUnboundedLogs, or an aggregate metric
Raw URL pathIncludes IDs and query stringsRoute template label
Client IPEffectively unboundedLogs
Histogram le bucketsMultiplies every other label by bucket countFewer buckets, or native histograms

The histogram row deserves a sentence. A classic histogram exposes one series per bucket through the le label, plus _sum and _count series. Twelve buckets on a metric that already carries engine, status and pod give twelve times that label product for the bucket series alone. Histograms are the most common way a reasonable label set becomes an unreasonable series count.

The same metric at four scales

One request-duration histogram, twelve buckets, on a service with seven engines and five status values. The numbers are illustrative arithmetic (label counts multiplied together, as in Part 1), not measurements. Watch what each added label does:

Labels on the metricSeriesChange
engine, status35baseline
+ le (12 buckets)420x12
+ pod, 40 stable replicas16,800x40
+ pod, autoscaling fleet, ~3,600 Pods per generation1,512,000x3,600
+ three generations inside the head window~4,500,000x3 again

Nothing in that table is a mistake anyone makes deliberately. Each step is one reasonable-sounding decision: measure latency properly, keep per-Pod detail, scale the fleet, and the last row is not a decision at all, it is the storage engine holding what you already created. Four and a half million series from one metric is far past what a typical single Prometheus server handles comfortably (the exact limit depends on its memory and your query load), The table shows why the per-Pod dimension is costly. To get an engine-level view safely, aggregate before ingestion or keep the source series and aggregate at query time; simply deleting the label can collapse distinct series into the same identity.

Part 5: Measuring it before it measures you

Prometheus tells you exactly where cardinality lives, if you ask.

The head series count is a metric, prometheus_tsdb_head_series, and its trend over a day is the single most useful graph for capacity. A sawtooth can reflect head truncation. A sustained rise deserves investigation, but it is not by itself proof of a leak: a growing fleet or new label values can produce the same shape.

The TSDB stats endpoint at /api/v1/status/tsdb breaks it down: series count by metric name, value count by label name, memory by label name, and series count by label pair, with a limit parameter that defaults to ten entries each and goes up to ten thousand. In practice, the label-value-count-by-label-name list usually identifies the culprit in one look. A label with forty thousand values is the problem, whatever it is called.

These queries provide a starting point. Run the broad scans cautiously on a busy server.

Code
# 1. How many series exist right now, and is the trend flat?
prometheus_tsdb_head_series

# 2. Which metrics own those series? Usually one or two dominate.
#    (This is expensive on a large server; the TSDB stats endpoint gives
#    the same answer more cheaply.)
topk(10, count by (__name__)({__name__!=""}))

# 3. Churn: distinct values a label took over the window, versus now.
count(count by (pod) (count_over_time(up[6h])))
count(count by (pod) (up))

# 4. Which targets are expensive to scrape?
topk(10, scrape_samples_scraped)

Query 3 is the one that surprises people. On a static deployment the two numbers match. On an autoscaling fleet the first can be much larger than the second. It describes distinct Pod values observed over six hours, not an exact multiplier for the current head window; check the labels and time range before using it for sizing.

Query 2 is where to start if the head series count is already too high, because cardinality is almost never spread evenly. One metric with an unfortunate label usually accounts for most of it, and the TSDB stats endpoint will name the label.

Part 6: Controlling it

There are four levers, and they act at different points in the pipeline.

Design labels around the question people ask. For every label on a high-churn workload, write down who queries by it and what would be lost without it. Our fleet needed engine-level views most often, while per-Pod details were less useful for routine dashboards. That doesn't mean a label can always be removed: it may be needed to distinguish sources correctly even when nobody filters on it.

Drop at scrape time with relabeling. metric_relabel_configs runs after the scrape and before storage. An action of labeldrop on a regex of label names removes the label before the series is ever created; an action of drop on a metric name discards whole metrics. Because it happens before ingestion, the series never touch the head, the log, or the index. This is the cheapest possible fix and the least reversible, since the data was never stored.

Code
metric_relabel_configs:
  # Example: omit a metric that no consumer needs.
  - source_labels: [__name__]
    regex: 'example_debug_metric'
    action: drop

This rule removes the whole named metric before ingestion. For labeldrop, check both the scraped output and labels added by service discovery: removing pod or instance can make distinct sources share a label set. Prometheus warns that relabeled series must remain uniquely identified. Metric relabeling also does not apply to automatically generated series such as up. Test the effective configuration and compare ingested series before rolling it out widely.

Guard with limits. Prometheus offers per-scrape limits: sample_limit on samples per scrape, label_limit on labels per sample, and length limits on label names and values. They default to zero, meaning off. Exceeding a limit fails the entire scrape, so alert on failures and use limits as a guardrail. These are not a complete cardinality cap: a target can emit a modest number of new label values on every scrape and still create substantial churn.

Use recording rules for query cost. A recording rule can sum a metric by engine into a lower-cardinality series for dashboards and alerts. It does not reduce local ingestion, because the raw series must remain available to the rule. If long-term storage needs only the aggregate, one design is to evaluate the rule in a collecting Prometheus and use write relabeling to omit raw series from remote storage. To reduce the collector's own ingestion, aggregate upstream or change the instrumentation instead.

Part 7: A worked example from an autoscaling fleet

The fleet is a headless browser platform on Kubernetes: workers that scale on queue depth from a few dozen nodes to around 600, on Spot capacity, so Pods are replaced constantly by scale events, preemptions and deploys.

The visible symptom was a dashboard showing the same metric three times. A self-hosted Prometheus had scraped one Service address, which collapsed all Pods behind a single series per metric. Moving to a managed Prometheus that scrapes each Pod individually meant every restart started a new series carrying the new Pod name. Panels that plotted raw series drew every generation still inside the head window. Thirty-one series in a six-hour window where the correct number was seven, one per subscription.

The arithmetic from Part 3 says why. At peak, roughly 3,600 worker Pods. Say each exposes fifty series that carry the pod label; that is 180,000 series per generation. Three scale cycles inside the two-to-three-hour head window is three generations, so around 540,000 series in memory for a fleet whose steady-state count is a fraction of that. The fifty series per Pod and the resulting totals are illustrative, not measured; the shape is what the head-series graph showed. The measured facts are the fleet's range (to around 600 nodes), the seven engines, and the 31 series that should have been 7.

The fix followed the levers in order:

  1. Ask the question. Who queries by Pod? Nobody. Who queries by engine and subscription? Everyone.
  2. Patch the dashboards. Aggregating the appropriate gauges by subscription and applying rate() to counters before aggregating reduced the displayed series from 31 to 7. The right aggregation depends on what a metric represents.
  3. Reduce unnecessary source series. Removing a label only works when the remaining labels still identify each series uniquely; otherwise aggregate before ingestion or retain a source identifier.
  4. Keep the detail where it is useful. Logs can carry a Pod name for individual investigations, subject to their own volume and retention costs.
LabelWho asks about itDistinct valuesKept on metrics?
engineOn-call, dashboards, alerts7Yes
subscriptionAutoscaling, backlog panels7Yes
statusError-rate alerts5Yes
podNobody, in practiceThousands per dayNo
nodeOccasionallyHundreds per dayNo, use events

Part 8: What you give up, and when that matters

Dropping a label loses the ability to see one outlier along that dimension in the metrics. With pod gone, a single degraded worker shows up as a slightly worse engine-level percentile and nothing more.

On a Spot fleet where a worker lives minutes to hours, that does not matter: the bad Pod is replaced before anyone could act on it, and the bad-node case surfaces through node events and restart counters, which are kept at low cardinality. On a stateful service with a dozen long-lived Pods, it matters a great deal, because one degraded replica can sit there for days. There, pod has a name in the "who asks" column and belongs on the metrics.

The mixed-fleet answer is to keep pod on a small set of high-signal metrics, restarts, out-of-memory kills, readiness, and drop it from everything else. This selective approach needs careful configuration and testing: preserve unique series identities and check that the retained metrics answer the incident questions you care about.

What to take from this

Prometheus costs depend on both samples and series. High cardinality adds head memory and index work; churn leaves multiple recent generations to track and replay. Start with the head-series metric and TSDB stats, then decide which dimensions you need and where aggregation can happen safely. Logs and traces can retain individual identifiers, but they have their own storage and query costs.

Continue learning

For a production example of observability at fleet scale, see Running a 600-Node GKE Spot Fleet. To go deeper into Prometheus itself, follow the compaction and retention lifecycle, then look at relabeling, recording rules, and remote write. Each affects a different part of the cost.

Sources and further reading

Everything in Parts 2 and 3 comes from these, and they are the right order to read them in.

FAQ

Is the pod label always wrong? No. It is wrong on high-churn, short-lived workloads where nobody queries by it, and right on long-lived stateful Pods where one replica can be the problem for days.

Why does memory not drop when I scale the fleet down? Recent series are not removed from the head immediately when a Pod disappears. Truncation and garbage collection happen later, and the timing depends on the sample and block boundaries. Watch the head-series trend over time before concluding there is a leak.

Do sample limits reduce cardinality? They can limit the samples accepted in an individual scrape by failing that scrape, but they do not cap all series churn over time. Treat failures as an alert and fix the source of excess series.

Does a bigger Prometheus fix this? It postpones it. The cost is per series and churn keeps generating series. Fix the multipliers first, then size the server for the count that remains.

KEEP GOING

Get the next deep dive by email

New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.

You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.

Written by Zeeshan Adil

I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.