Skip to main content

Mitigating Cardinality Explosion in Prometheus

How unbounded labels like customer_id or pod_ip multiply TSDB series counts, plus relabelling rules, Cortex/Mimir limits, and remote-write sharding to contain it.

KBY Technologies10 min read
Mitigating Cardinality Explosion in Prometheus

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.

A single misconfigured label, such as customer_id, request_uuid or an unbounded pod_ip, can take a healthy instance from 2 million active series to 40 million in under an hour. This is cardinality explosion: the exponential growth of unique time series caused by high-dimensionality label combinations, and it remains the single most common cause of Prometheus OOM kills in production observability stacks. Unlike a slow memory leak, cardinality explosion is combinatorial. It doesn’t degrade gracefully; it degrades catastrophically, usually during an incident when you can least afford it.

What follows covers the TSDB internals that make cardinality explosion possible, the detection tooling required to catch it before it pages you, and the sharding and relabelling architecture needed to contain it in a large deployment. If you are running Prometheus beyond a single-team, single-cluster footprint, this is not optional reading.

#How one extra label multiplies the series count

Prometheus’s storage engine indexes every unique combination of metric name and label set as a distinct time series. A metric like http_requests_total{method="GET", status="200", path="/api/v1/users"} is cheap in isolation. The problem is combinatorial: if path has 500 unique values, status has 10, and you add a well-intentioned user_id label with 100,000 distinct values, you have just generated 500,000,000 potential series from a single metric family. This is the mechanism behind virtually every cardinality explosion incident: a label that seemed reasonable in a design review turns out to be unbounded in production.

Each active series consumes memory in the head block, roughly 1-3 KB per series depending on chunk encoding and label byte size. At 10 million active series, you are looking at 10-30 GB of resident memory before you have even accounted for query working sets. Prometheus was architecturally designed as a single-node, pull-based system with a bounded cardinality assumption baked into its TSDB storage model; it does not fail safely when that assumption breaks.

#What happens inside the TSDB

#
Where the head block’s memory goes

The TSDB head block is an in-memory, mutable structure holding the last two hours of samples for every active series. Every new label combination triggers a new series entry in the head’s inverted index, a map from label name/value pairs to series references. This index is O(1) for lookups but grows linearly with unique series count, and linearly with churn rate (series created and immediately orphaned). High churn is often worse than high steady-state cardinality because it forces constant WAL (write-ahead log) writes and index mutation without any compensating query value.

#
The Maths of Label Combinatorics

Cardinality is multiplicative across label dimensions, not additive. For a metric with labels L1, L2, ... Ln with cardinalities c1, c2, ... cn, worst-case series count approaches c1 × c2 × ... × cn. In practice, real-world correlation reduces this (not every combination is observed), but any label sourced from a high-entropy field (UUIDs, IP addresses, raw error messages, unbounded customer identifiers) collapses that correlation assumption and cardinality explosion follows almost immediately after deployment.

cardinality explosion

#
Downstream Propagation via Remote Write

In federated architectures using Thanos, Cortex, or Mimir, cardinality explosion doesn’t stay local. Remote write forwards every active series to the long-term storage tier, meaning an uncontrolled label on a single scrape target can degrade shared multi-tenant infrastructure. This is precisely why cardinality governance needs to sit as an architectural pattern enforced at ingestion, not as a reactive cleanup task performed after a query-path outage.

#Finding the label and containing it

#
Step 1: Count series and measure churn

Before applying mitigation, find out how far the damage reaches. Use the TSDB status endpoint and targeted PromQL to identify the offending metric families:

1# Top 10 metric names by series count
2topk(10, count by (__name__)({__name__=~".+"}))
3
4# Count distinct customer_id values for one metric (repeat for each suspect label)
5count(count by (customer_id) (http_requests_total)) 
6
7# Check churn rate over a rolling window
8sum(rate(prometheus_tsdb_head_series_created_total[5m]))

Cross-reference against /api/v1/status/tsdb, which returns seriesCountByMetricName and labelValueCountByLabelName directly, and this is the fastest path to isolating the specific label driving cardinality explosion without scanning raw samples.

#
Step 2: Drop and cap series at scrape time

Cardinality should be filtered as close to the source as possible: at scrape time, before it ever enters the head block. Use per-scrape limits and metric_relabel_configs to cap a target and drop offending metric families:

1scrape_configs:
2  - job_name: 'payments-api'
3    static_configs:
4      - targets: ['payments-api:9090']
5    # Fail the whole scrape if the target exposes more samples than this
6    sample_limit: 50000
7    # Fail the scrape if any label value is longer than this
8    label_value_length_limit: 200
9    metric_relabel_configs:
10      # Drop an entire metric family whose labels are unbounded
11      - source_labels: [__name__]
12        regex: 'payments_requests_by_customer_.*'
13        action: drop

A limit turns an unbounded failure into a failed scrape, which shows up as up == 0 for that target and can be alerted on, rather than as a memory spike. Do not use labeldrop, or a hashmod bucket in place of the original label, on a label that distinguishes series, such as customer_id or request_uuid. Relabelling does not aggregate: series that differed only by that label collapse into duplicate series within one scrape, and Prometheus keeps the first sample and rejects later ones with a different value (see prometheus_target_scrapes_sample_duplicate_timestamp_total), so counters are silently wrong rather than summed. Remove or aggregate such labels in the instrumentation itself, and test any relabelling change on one target first. Dropping at scrape time is still significantly cheaper than post-ingestion cleanup, since dropped series never enter the head block or the WAL.

#
Step 3: Cap series per tenant in the shared tier

For clusters that have already outgrown single-node Prometheus, cardinality containment shifts from prevention to isolation. Cortex and Mimir implement per-tenant ingestion limits that cap active series and reject writes exceeding the threshold, preventing one noisy team from starving shared capacity. The fields below are Grafana Mimir’s per-tenant limits; Cortex shares many of these names, but check the reference for the version you run:

Mitigating Cardinality Explosion in Prometheus architecture diagram 2
1limits:
2  max_global_series_per_user: 1500000
3  max_global_series_per_metric: 200000
4  ingestion_rate: 50000
5  ingestion_burst_size: 100000

The max_global_series_per_metric field is the direct structural defence against cardinality explosion at the metric-family level: it caps growth regardless of how many label dimensions a team introduces, converting an unbounded failure into a bounded, alertable rejection.

#How it fails in production

#
OOM kills during WAL replay

A Prometheus pod that OOM-kills mid-cardinality-explosion enters a dangerous restart loop: on boot, it must replay the WAL to reconstruct the head block. If cardinality explosion has already pushed the WAL to several gigabytes, replay time itself can exceed the pod’s liveness probe timeout, causing to kill it again before recovery completes. This creates a crash loop that masks the underlying root cause. Engineers frequently misdiagnose this as a resource-limit problem rather than a cardinality problem.

#
Labels filled from user input

The most severe class of cardinality explosion originates from labels populated directly from user input, such as HTTP headers, raw error strings, or session tokens exposed via instrumentation middleware. These are effectively adversarial from a systems perspective: a single malformed client, bot, or misbehaving retry loop can generate millions of unique series in minutes. Any label sourced from external, non-enumerable input should be treated as untrusted and excluded from metric labels by default.

#
Remote Write Backpressure Cascades

When a downstream Cortex or Mimir cluster rejects samples because a series limit is hit, it answers with an HTTP 4xx status and Prometheus drops that batch rather than retrying it, so the data is lost, not queued. Server errors (5xx) and, depending on your Prometheus version and settings, rate-limit responses (HTTP 429) are retried with backoff; while that happens remote write falls behind the WAL, in-memory queues fill, local memory pressure rises, and samples older than the WAL’s retention (roughly two hours) can be lost. The mitigation designed to protect the shared tier can therefore destabilise the source Prometheus instance. Prometheus has no general drop-on-failure switch, and queue_config does not change how 4xx rejections are handled: it tunes throughput and memory use only (buffer size per shard, shard count, batch size and retry backoff). Those 4xx drops are inherent, so monitor them through prometheus_remote_storage_samples_failed_total on the sender and the receiver’s discarded-samples counter. A typical tuning block looks like this:

1remote_write:
2  - url: "https://mimir.internal/api/v1/push"
3    queue_config:
4      capacity: 10000
5      max_shards: 50
6      max_samples_per_send: 2000
7      min_backoff: 30ms
8      max_backoff: 5s

#What each containment approach costs

Containing cardinality explosion is ultimately a governance problem layered on top of a storage-engine constraint. The following trade-offs should inform whether you invest in relabelling discipline, horizontal sharding, or both:

  • Relabelling at scrape time is the cheapest mitigation (near-zero CPU overhead) but requires organisational buy-in: every team onboarding new instrumentation must follow label conventions, which does not scale past a handful of teams without automated linting.
  • Per-tenant ingestion limits (Cortex/Mimir) scale well operationally but introduce a hard failure mode: writes are rejected rather than degraded, which can cause silent data loss for teams that don’t monitor cortex_discarded_samples_total (Mimir keeps the cortex_ prefix).
  • Recording rules for pre-aggregation reduce query-time cardinality exposure but add write amplification and a maintenance burden, since every new dimension requires a corresponding rule update.
  • Security exposure: unbounded labels sourced from user input (IP addresses, emails, tokens) create a data-leakage risk in addition to a cardinality risk, because metrics endpoints frequently lack the access controls applied to logs, so PII inadvertently ends up in label values scraped by third-party observability vendors.
  • Multi-tenant isolation: shared Prometheus/Mimir clusters without hard per-tenant caps allow a single team’s cardinality explosion to exhaust ingester memory cluster-wide, so tenant-level circuit breakers are not optional at organisational scale.
  • Cost implications: in managed observability platforms billed per active series, an unnoticed cardinality explosion is a direct and immediate cost incident, often before it manifests as a performance incident.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01TSDB storage modelprometheus.io

About this page

Credited to

Dates

Published

Last updated

Corrections

  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details
Reader Interaction

Comments

Add a thoughtful note on Mitigating Cardinality Explosion in Prometheus. Comments are checked for spam and held for moderation before appearing.

Loading comments...

More from KBY that goes with this article.

Discover more

Lexicon Definitions

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Engineering insights, direct to you.

Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.