The hidden cost of high-cardinality labels: how unique label values slow down and inflate your time series database

Why every unique label combination becomes its own time series, what that does to Prometheus memory, ingestion and queries, how to find the labels responsible and how to fix them without losing the detail you need.

Obseria TeamObseria
Summary
  • High cardinality means a metric has a very large number of unique label combinations, and in a time series database every combination is a separate series with its own index entries and in-memory chunks.
  • Labels such as user IDs, request IDs, raw URL paths, error messages and pod names multiply series counts, which drives up memory, ingestion CPU, query latency and, with usage-based billing, cost.
  • You can find the culprits with the Prometheus TSDB status page, count and topk queries and scrape_series_added, and fix them with metric relabeling, route templates, bucketing, limits and by moving per-request detail to traces, logs and exemplars.

High cardinality is one of the most common reasons a metrics system that ran happily for months suddenly needs twice the memory, answers dashboard queries in seconds instead of milliseconds, or produces a bill nobody expected. The cause is rarely a dramatic change. Usually someone added one innocent-looking label, such as user_id, path or pod, and the number of time series quietly multiplied.

This article explains what cardinality actually is, why it hurts time series databases like Prometheus in particular, which labels are the usual suspects, how to find them in your own setup and how to fix them. It ends with a table of risky labels and better alternatives and a cardinality audit checklist you can copy.

What cardinality means for metrics

In metrics, cardinality is the number of unique time series a metric produces. A time series is identified by the metric name plus its complete set of labels. Change any label value and you get a new series, with its own storage and its own index entries.

The important property is that cardinality grows multiplicatively, not additively. The worst case for one metric is the product of the number of distinct values of every label.

A worked example (illustrative numbers)

Take a request counter http_requests_total with these labels. The numbers are an example, not a measurement:

  • method: 5 values (GET, POST, PUT, DELETE, PATCH)
  • status: 10 values actually seen
  • route: 50 route templates
  • instance: 20 pods

Upper bound: 5 × 10 × 50 × 20 = 50,000 series. In practice many combinations never occur, so the real number is lower, but it is manageable either way. Now someone adds user_id with 10,000 active users. The theoretical upper bound becomes 50,000 × 10,000 = 500 million series. Even if only a small fraction of those combinations ever appears, you have turned one metric into the largest consumer of your entire metrics backend. If the pods are replaced on every deployment, the instance values change too, and the counting starts again.

Why high cardinality hurts a time series database

Time series databases are optimised for many samples per series, not for many series. Prometheus is a good example because its internals are well documented.

  • Memory in the head block. Recent data lives in the in-memory head block. Every active series has an entry there with its labels and at least one open chunk of compressed samples. Memory therefore scales with the number of active series much more than with the number of samples. The metric prometheus_tsdb_head_series shows this number directly.
  • Inverted index. Each label name/value pair points to the list of series that carry it. More unique values mean more postings, a larger index in memory and on disk, and more work for every selector.
  • Ingestion CPU. Creating a new series is far more expensive than appending a sample to an existing one: labels must be hashed, stored and indexed. A steady stream of new series costs CPU on every scrape.
  • Compaction. The head block is periodically written into persistent blocks and blocks are compacted together. Millions of short-lived series make these blocks and their indexes larger and compaction slower.
  • Query latency. A PromQL query such as sum by (route) (rate(http_requests_total[5m])) has to load and process every matching series. If the selector matches hundreds of thousands of series, dashboards and alert rules slow down or hit query limits.

Series churn: the cardinality you do not see in a snapshot

Churn is the rate at which series appear and disappear. In Kubernetes, every rollout produces new pod names, container IDs and sometimes new ReplicaSet hashes. Each change ends one set of series and starts another. At any moment the number of active series may look fine, but the head block, the index and the blocks covering the last hours still contain all the series that existed in that window. Frequent deployments plus pod-level labels on high-volume metrics is one of the most common sources of unexpected memory growth.

Typical culprits: labels that explode cardinality

Almost every cardinality incident comes from a label whose set of values is unbounded or grows with traffic rather than with the size of your system:

  • User, customer, session or tenant IDs on request metrics.
  • Request, trace or correlation IDs: a new value per request, which effectively means one series per event.
  • Full URLs and raw paths such as /orders/839201/items/17 instead of /orders/{id}/items/{item}, plus query strings.
  • Timestamps or dates in label values, for example a build time or a batch date.
  • Error messages and exception text that contain IDs, file paths or values.
  • Pod names, container IDs and IP addresses on metrics where the per-pod view is not needed.
  • Unbounded values from user input: search terms, user agents, referrers, free-text fields, or HTTP methods taken straight from the request without normalisation.

The table summarises the risk and a better place for that information.

LabelCardinality riskBetter alternative
user_id, customer_idVery high, grows with usersSpan or log attribute; aggregate per plan or tier as a metric label
request_id, trace_idExtreme, one value per requestTraces; link from metrics via exemplars
path / url (raw)High, every ID creates a valueRoute template such as /orders/{id}
error_messageHigh, messages contain variable dataError class or code as label, full message in logs
timestamp, dateUnbounded, new value constantlyUse the sample timestamp; put build info in an info metric
pod, container_idMedium to high, churns on every deployAggregate to deployment or service; keep pod level only for resource metrics
user_agent, search_termUnbounded user inputBucket into a fixed set (browser family, "other")
response_size, duration as labelHigh, numeric values as stringsHistogram buckets instead of a label

How to find Prometheus cardinality problems

The TSDB status page and API

The Prometheus web UI has a TSDB status page under Status (/tsdb-status). It shows head block statistics and top lists by series count per metric name, number of values per label name, memory used per label name and series count per label/value pair. The same data is available from the HTTP API:

# Top 20 entries per statistic (default is 10)
curl -s 'http://prometheus:9090/api/v1/status/tsdb?limit=20' | jq '.data.seriesCountByMetricName'

# Other fields in .data:
#   headStats, labelValueCountByLabelName,
#   memoryInBytesByLabelName, seriesCountByLabelValuePair

Start with labelValueCountByLabelName: a label with tens of thousands of values is almost always a bug.

PromQL queries

# Total active series in the head block
prometheus_tsdb_head_series

# Top 10 metric names by series count (expensive, run sparingly)
topk(10, count by (__name__) ({__name__=~".+"}))

# How many distinct values does one label have on one metric?
count(count by (route) (http_requests_total))

# Which targets add the most new series (churn)?
topk(10, sum by (job, instance) (sum_over_time(scrape_series_added[1h])))

# Samples per scrape, before and after metric relabeling
topk(10, scrape_samples_scraped)
topk(10, scrape_samples_post_metric_relabeling)

scrape_series_added is a synthetic metric Prometheus generates for every target. It reports the approximate number of new series in each scrape, which makes it the best signal for churn. A target that keeps adding series long after start-up is exposing a label with constantly changing values.

How to reduce high cardinality metrics

Fix it at the source

The cleanest fix is in the instrumentation. Use route templates from your web framework instead of the raw path, record error classes instead of messages, and do not attach user or request IDs to metrics at all. Numeric values such as duration or size belong in histograms, not in labels.

Drop and rewrite with metric_relabel_configs

When you cannot change the application quickly, rewrite at scrape time. metric_relabel_configs runs after the scrape and before storage:

scrape_configs:
  - job_name: shop-api
    sample_limit: 50000          # fail the scrape if more samples arrive
    label_limit: 30              # max labels per sample
    label_value_length_limit: 200
    metric_relabel_configs:
      # Remove labels that should never be on metrics
      - action: labeldrop
        regex: request_id|user_id|session_id
      # Normalise raw paths with numeric IDs to a route template
      - source_labels: [path]
        regex: /orders/[0-9]+
        target_label: path
        replacement: /orders/{id}
      # Drop a whole debug metric family
      - source_labels: [__name__]
        regex: debug_.*
        action: drop

Be careful with labeldrop: if two series differ only in the dropped label, they collide after relabeling and Prometheus rejects the duplicates. Dropping a label is safest when the metric is aggregated anyway, or when you aggregate first in a pipeline.

Use limits as a safety net

sample_limit, label_limit, label_name_length_limit and label_value_length_limit are evaluated after metric relabeling. If a target exceeds them, the entire scrape is treated as failed. That sounds harsh, but it turns a silent memory explosion into a visible scrape failure you can alert on (up == 0). Set the limits with headroom above normal values.

Bucket, aggregate and downsample

  • Bucketing: map unbounded values to a small fixed set, for example user agents to browser family, HTTP status to class (2xx, 4xx, 5xx) where detail is not needed, and anything unknown to other.
  • Aggregation in the pipeline: a telemetry pipeline can sum away the pod dimension for high-volume metrics before they reach storage, while keeping service and route.
  • Recording rules and downsampling: precompute the aggregates your dashboards use and keep raw high-resolution data for a shorter period.

Metrics versus traces and events for high-cardinality data

High-cardinality data is not bad. Questions like "which customer saw the slow checkout?" are exactly what you want to answer during an incident. The problem is storing that detail in the wrong signal.

  • Metrics are cheap per sample and fast to aggregate because the set of series is small and stable. They answer "how much, how often, how fast" over time.
  • Traces and logs are stored per event. Attributes like user.id, request ID or full URL cost the same whether there are ten distinct values or ten million, because nothing is indexed per combination as a separate series.
  • Exemplars bridge the two: a histogram bucket stores a sample trace ID, so you can jump from a latency spike on a dashboard to a concrete trace without adding the trace ID as a label. In Prometheus, exemplar storage is enabled with the exemplar-storage feature flag.

A practical rule: if a label value identifies a single request, user or event, it belongs in a span or log line. If it identifies a part of your system with a bounded number of values, it can be a metric label.

The cost angle in usage-based billing

In self-hosted Prometheus, high cardinality costs RAM, CPU and disk. In a managed backend it costs money directly. Many vendors bill metrics per active series, per custom metric or per ingested data point, so a single label added to one hot metric can change the monthly invoice more than a new service does. Because the growth is multiplicative, the effect is often only noticed when the bill arrives.

The defensive pattern is the same in both cases: control cardinality before storage, not after. Our article on reducing observability costs with a pipeline-first approach covers filtering, sampling and aggregation in more depth, and the cost calculator helps you estimate how volume changes affect your spend.

Cardinality audit checklist

Cardinality audit checklist

  1. Record the current prometheus_tsdb_head_series and its trend over the last 30 days.
  2. Open /tsdb-status and list the top 20 metric names by series count.
  3. List the top 20 label names by number of values; flag every label with more than a few hundred values.
  4. For each flagged label, decide: drop, normalise, bucket or move to traces/logs.
  5. Check scrape_series_added per target for continuous churn after start-up.
  6. Verify that HTTP metrics use route templates, never raw paths or query strings.
  7. Confirm that no metric carries user, session, request or trace IDs.
  8. Review pod- and container-level labels on high-volume application metrics.
  9. Add metric_relabel_configs for anything you cannot fix in code this sprint.
  10. Set sample_limit and label_limit per job and alert on failed scrapes.
  11. Enable exemplars so high-cardinality detail stays reachable through traces.
  12. Add a cardinality review to the checklist for new instrumentation in code review.

How Obseria helps with high cardinality

Obseria is an OpenTelemetry-native observability platform with EU data residency. Metrics monitoring ingests Prometheus and OpenTelemetry metrics, the Prometheus integration works with your existing exporters and scrape configs, and per-request detail stays in traces and logs where it does not multiply series.

  • Obseria Pipeline filters, drops labels, aggregates and routes telemetry before it is stored.
  • APM traces and logs carry high-cardinality attributes such as user or request IDs and are linked to metrics.
  • Usage-based pricing per signal with unlimited users makes the effect of cardinality changes visible.

You can audit your own metrics against this checklist with a free 14-day Obseria trial.

Share

Observability that delivers answers.

Start for free with OpenTelemetry, no credit card required.