InsightsDevOps
Prometheus cardinality: finding the labels that blow up memory, and capping them
How to see which metrics and labels create the most time series, drop or rewrite them at scrape time, and set per-job limits so one team's new label cannot take down the shared Prometheus.
Published November 28, 20266 min read
Prometheus does not run out of memory because of traffic. It runs out because of series. Every unique combination of metric name and label values is a separate time series, held in memory while it is active. A service that adds a user_id or path label to a request counter turns one series into hundreds of thousands, and the first sign is usually a Prometheus that restarts in a loop or a bill that doubles.
This article covers how to find the series that cost the most, how to remove them at scrape time, and how to set limits so the next mistake fails one job instead of the whole server.
What cardinality means here
The number of series for a metric is roughly the product of the distinct values of each label:
http_requests_total{service, method, code, path}
20 services × 5 methods × 8 codes × 1,000 paths = 800,000 seriesA histogram multiplies this again, because each bucket is its own series, plus _sum and _count. A latency histogram with 12 buckets and an unbounded path label is the classic way to reach millions.
Labels that grow without bound are the problem: user, session, request and trace IDs, full URLs with IDs in them, email addresses, container IDs in short-lived jobs. Labels with a small fixed set of values (method, code, region) are fine.
Churn is the other half. A pod that restarts gets a new pod label, so every series it exposed ends and a new one starts. Total series over a day can be many times the number active at any moment, which matters for index size and query cost even when memory looks fine.
Find the expensive series
Start with the TSDB status page in the Prometheus UI, or the same data from the API:
curl -s 'http://prometheus:9090/api/v1/status/tsdb?limit=20' \
| jq '.data | {
head: .headStats.numSeries,
byMetric: .seriesCountByMetricName,
byLabel: .labelValueCountByLabelName
}'The HTTP API reference describes the response. Three lists matter:
| Field | What it answers |
|---|---|
seriesCountByMetricName | Which metric names have the most series |
labelValueCountByLabelName | Which label names have the most distinct values |
memoryInBytesByLabelName | Which label names take the most memory, estimated from the length of their values |
limit defaults to 10 and goes up to 10,000. Read the first two together: a metric with 400,000 series and a label with 400,000 distinct values is almost always the same problem.
To see the problem per job, query the server itself. These two use the series Prometheus records about every scrape:
# What each target exposes
topk(10, max by (job) (scrape_samples_scraped))
# What is kept after metric_relabel_configs
topk(10, max by (job) (scrape_samples_post_metric_relabeling))scrape_samples_post_metric_relabeling is defined in the Prometheus docs as the number of samples remaining after metric relabeling. Comparing the two shows how much your relabeling already removes, and tells you which job to look at first.
To find the metric inside a job:
topk(10, count by (__name__) ({job="checkout"}))This query touches every series in the job, so run it against a job, never against {__name__=~".+"} on a large server.
For churn and for history, promtool tsdb analyze <data-dir> reads a block on disk and reports the highest-cardinality metric names and label pairs. Run it against a copy of the data directory, not the live one.
Remove series at scrape time
The cheapest series is the one never stored. metric_relabel_configs runs on each scraped sample before it is written, and can drop whole metrics or single labels.
scrape_configs:
- job_name: checkout
kubernetes_sd_configs:
- role: pod
metric_relabel_configs:
# Drop a metric nobody queries
- source_labels: [__name__]
regex: checkout_debug_.*
action: drop
# Drop a label that is unbounded
- regex: request_id
action: labeldropTwo details cause most of the surprises:
- Dropping a label can merge series. If two series differ only by
request_id, removing the label leaves two samples with identical labels in one scrape. Prometheus rejects the duplicates, and you get errors instead of fewer series. Uselabeldroponly on labels that are not needed to tell series apart, or fix the application. - Relabeling hides the source of the problem. The application still exposes, and the target still serializes, everything you dropped. That costs CPU and network on both sides. It is a mitigation, not a fix.
When you control the code, fix it there. Replace raw paths with the route template (/orders/{id}, not /orders/8841). Put per-user detail in logs or traces, which are built for high cardinality.
Cap each job with scrape limits
Relabeling answers a problem you already know about. Limits cover the one you do not. Each scrape config accepts limits that are counted after metric relabeling; all default to 0, meaning no limit. They are described in the configuration reference:
| Setting | Caps |
|---|---|
sample_limit | Samples accepted per scrape |
label_limit | Number of labels on any sample |
label_name_length_limit | Bytes in any label name |
label_value_length_limit | Bytes in any label value |
target_limit | Targets per scrape config (marked experimental) |
body_size_limit | Uncompressed response size (marked experimental) |
scrape_configs:
- job_name: checkout
sample_limit: 20000
label_limit: 30
label_value_length_limit: 200The behavior to understand is what happens at the limit: the entire scrape is treated as failed. That means up goes to 0 for that target and none of its samples from that scrape are used. A limit protects the server by sacrificing the offending job, which is why it needs to be paired with an alert:
- alert: ScrapeFailing
expr: up == 0
for: 10m
labels:
severity: ticket
annotations:
summary: "{{ $labels.job }}/{{ $labels.instance }} is failing its scrapes, possibly over a scrape limit"Set sample_limit from what the job exposes today. Take the maximum of scrape_samples_post_metric_relabeling over a few weeks and leave headroom, such as double. A limit that is too tight turns a normal deploy into an outage of the metrics for that service. A limit that is too loose protects nothing.
If you run the Prometheus Operator, the same limits are available on ServiceMonitor and PodMonitor as fields such as sampleLimit, next to metricRelabelings. Check the field names in the CRD for your operator version.
Who owns the limit
On a shared Prometheus, the platform team sets the defaults and each team owns the metrics inside them. A workable split:
- Every job gets a
sample_limitandlabel_value_length_limitin a shared template, so a new service is protected from its first deploy. - Teams that need more raise their own limit in a pull request, with the current
scrape_samples_post_metric_relabelingnumber in the description. - A recording rule or dashboard shows series per job and per team, so growth is visible before the limit is hit.
max by (job) (scrape_samples_post_metric_relabeling) > 0.8 * 20000In practice you generate this rule from the same file that holds the limits, so the two cannot drift apart.
What goes wrong
- Limits without alerts. The job fails quietly and dashboards go blank. Alert on
up == 0and on approaching the limit. - Relabeling that creates duplicates. The scrape reports duplicate-sample errors. Check the target's page in the UI after any
labeldrop. - Fixing symptoms in the TSDB. Deleting series with the admin API frees nothing until compaction, and the series return on the next scrape. Fix the source.
- Histograms. Bucket counts multiply every label. Before adding a label to a histogram, multiply it out. Native histograms store a distribution in one series per label set, and the config has
native_histogram_bucket_limitto cap their size, but they need support in both client library and server, so test before migrating. - Looking only at the head. Churn from short-lived pods inflates the index even when active series look reasonable. Check
promtool tsdb analyzeafter a busy week.
A short routine
- Open the TSDB status page and note the top metric and label.
- Compare
scrape_samples_scrapedwithscrape_samples_post_metric_relabelingper job. - Fix the biggest offender in the application; drop it at scrape time while that is in review.
- Add
sample_limitandlabel_value_length_limitto every job, with an alert on failing scrapes and on 80% of the limit. - Repeat monthly, or when the head series count moves more than expected after a release.