TExcelTAD

Labels & Cardinality

Cardinality is the number of distinct series a metric produces: the product of the number of values of each of its labels, times the number of targets. It is the single most important cost driver in Prometheus (and in every hosted metrics service, which bills by active series). One careless label can multiply it by thousands.

Counting series

http_requests_total with labels route (6 values), method (4), code (8), scraped from 10 pods:

text
6 × 4 × 8 × 10 = 1,920 series (at most; only combinations that actually occur exist)

Add le for a histogram with 12 buckets and each latency metric is × 14 (12 buckets plus _sum and _count). Add user_id with 50,000 users and it's tens of millions. The model below makes those numbers concrete, using only combinations that really occur, the way Prometheus does:

python · try it yourself
import random

random.seed(7)
routes = ["/{code}", "/links", "/healthz", "/readyz", "/metrics"]
codes = {"/{code}": ["302", "404", "500"], "/links": ["201", "400", "409", "500"],
         "/healthz": ["200"], "/readyz": ["200", "503"], "/metrics": ["200"]}
pods = [f"linkly-{i}" for i in range(10)]

def series(requests, labels):
    return len({tuple(r[k] for k in labels) for r in requests})

requests = []
for _ in range(20000):
    route = random.choice(routes)
    requests.append({
        "pod": random.choice(pods),
        "route": route,
        "code": random.choice(codes[route]),
        "path": "/" + "".join(random.choice("abcdefghjkmnpqrstuvwxyz23456789") for _ in range(6)) if route == "/{code}" else route,
        "user": f"u{random.randrange(5000)}",
    })

for labels in (["pod", "route", "code"],
               ["pod", "route", "code", "user"],
               ["pod", "path", "code"]):
    n = series(requests, labels)
    print(f"{'+'.join(labels):22} {n:6} series   x14 as a histogram = {n * 14:7}")
pod+route+code            110 series   x14 as a histogram =    1540
pod+route+code+user     19547 series   x14 as a histogram =  273658
pod+path+code            4110 series   x14 as a histogram =   57540

With 20,000 requests the user label already produces nearly one series per request and the raw path one per short code visited, and both keep growing with traffic, while the good set stays at about a hundred forever. Every series costs memory in the head block (a few KB including the index), so a few million series means tens of GB of RAM.

Where cardinality explodes

Source Fix
IDs in labels: user, order, request, trace, short code put them in logs or traces; use exemplars to link a metric to a trace
raw paths, query strings route templates (/{code})
error messages as labels a small reason enum (timeout, conn_refused, other)
too many histogram buckets × many labels fewer buckets (8–12), fewer labels on histograms, or native histograms
Kubernetes pod names on high-churn workloads each rollout creates new pod values: aggregate them away in recording rules; drop in relabeling if unused
exporters with huge defaults (kube-state-metrics, cAdvisor) metric_relabel_configs to drop what no dashboard uses

Churn is the related problem: series that exist briefly and are replaced (new pod names on every deploy, per-job IDs). Each new series has a setup cost, and old ones stay in the head block until the next compaction.

Finding the culprits

promtool tsdb analyze reads a TSDB and prints the label pairs and names with the most series. The session backfills a small TSDB in which somebody added a path label, then analyzes it:

bash · try it yourself
python3 - > data.om <<'PY'
import random
random.seed(3)
start = 1767225600
print("# TYPE http_requests_total counter")
paths = ["/" + "".join(random.choice("abcdefghjkmnp23456789") for _ in range(6)) for _ in range(300)]
for pod in ("linkly-0", "linkly-1", "linkly-2"):
    for code in ("302", "404"):
        for t in range(0, 300, 60):
            print(f'http_requests_total{{pod="{pod}",route="/{{code}}",code="{code}"}} {t} {start + t}')
    for p in paths[:100] if pod == "linkly-0" else paths[100:]:
        for t in range(0, 300, 60):
            print(f'linkly_redirects_by_path_total{{pod="{pod}",path="{p}"}} {t} {start + t}')
print("# EOF")
PY
promtool tsdb create-blocks-from openmetrics data.om data >/dev/null
promtool tsdb analyze --limit=4 data | sed -n '/^Label names with highest cumulative/,$p'
Label names with highest cumulative label value length:
2100 path
49 __name__
24 pod
7 route

Highest cardinality labels:
300 path
3 pod
2 __name__
2 code

Highest cardinality metric names:
500 linkly_redirects_by_path_total
6 http_requests_total

path has 300 values and is responsible for almost every series; linkly_redirects_by_path_total is the metric to delete. On a live server, the same information is on Status → TSDB Status in the UI and at /api/v1/status/tsdb. In Grafana Cloud or Mimir, the cardinality management dashboards do the same at scale.

Dropping a label or metric at scrape time

If the metric comes from code you don't control, drop it before it is stored with metric_relabel_configs (they run after the scrape, on every sample):

yaml
scrape_configs:
  - job_name: linkly
    static_configs:
      - targets: ["linkly:8080"]
    metric_relabel_configs:
      - source_labels: [__name__]
        regex: linkly_redirects_by_path_total
        action: drop
      - regex: user_id              # remove one label from every series
        action: labeldrop

Dropping a label only works if the remaining labels still identify each series uniquely; otherwise two series collide and samples are rejected as duplicates. Fix the instrumentation when you can. Scrape Configuration & Relabeling covers the relabeling actions.

Prometheus also has guard rails per scrape job: sample_limit (fail the scrape if a target exposes more than N samples), label_limit, label_value_length_limit. A failed scrape is visible (up == 0) instead of silently filling memory.

Test yourself

A histogram with 10 buckets has labels route (5 values) and code (4 values) on 6 pods. At most how many series?

  1. 120
  2. 1,440
  3. 1,200
  4. 240

Where should a per-request ID go instead of a metric label?

  1. Into the metric name
  2. Into logs and traces (optionally linked from metrics with exemplars)
  3. Into # HELP
  4. Into a gauge value

Which setting makes a scrape fail when a target suddenly exposes far too many samples?

  1. scrape_timeout
  2. sample_limit
  3. honor_labels
  4. retention.size