> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Diagnosing High Cardinality in Metric Design

> Hands on demo showing how a single unbounded label explodes Prometheus series, how to measure it, and how to fix it via scrape time metric relabeling.

In this hands‑on lesson you’ll see how a single unbounded label can explode the number of Prometheus time series, how to measure that effect, and how to fix it using metric relabeling at scrape time. We'll:

* Deploy two versions of a shopping cart API (low- and high-cardinality).
* Generate traffic against both.
* Inspect the scraped metrics and compare time series counts.
* Apply Prometheus metric relabeling via a ServiceMonitor to drop the problematic label.
* Verify the reduction in stored series in Grafana Explore.

***

## Overview

Cardinality multiplies across label dimensions. For example:

* `method`: 5 values
* `endpoint`: 50 values
* `status`: 10 values
* `user_id`: 1,000,000 values

Multiply those and you get billions of distinct time series. A single high-cardinality label (like `user_id`) can overwhelm your storage and RAM.

| Label | Example cardinality |
| - | - |
| `method` | 5 |
| `endpoint` | 50 |
| `status` | 10 |
| `user_id` | 1,000,000 |
| Combined (approx.) | billions of series |

***

## 1) Deploy the low-cardinality application and generate traffic

Apply the ServiceMonitor and other manifests for the low-cardinality app, and confirm the pod starts:

```bash theme={null}
kubectl apply -f low-cardinality-app/k8s/servicemonitor.yaml
kubectl get ns
# NAME                 STATUS   AGE
# default              Active   37m
kubectl get po -w
# NAME                                   READY   STATUS    RESTARTS   AGE
# cart-api-low-7fb455599c-xmtv9          0/1     Running   0          18s
# cart-api-low-7fb455599c-xmtv9          1/1     Running   0          24s
```

Start the traffic generator for the low-cardinality API in the background:

```bash theme={null}
./low-cardinality-app/scripts/generate-traffic.sh low &
# [1] 32569
# Starting traffic generation for cart-api-low...
# Target: http://localhost:30801
# Simulating 1000 unique users
```

After \~45 seconds, stop traffic generation and capture the metrics endpoint:

```bash theme={null}
pkill -f "generate-traffic.sh"
curl http://localhost:30801/metrics > ~/low-cardinality-metrics.txt
# 100  6417  100  6417    0     0  2113k      0 --:--:-- --:--:-- --:--:-- 3133k
```

Count histogram bucket lines for the `cart_order_duration_seconds` metric:

```bash theme={null}
grep "cart_order_duration_seconds_bucket" ~/low-cardinality-metrics.txt | wc -l
# 28
```

This low-cardinality deployment exposes route templates (e.g., `/cart/user/{user_id}`) rather than emitting a distinct `user_id` value per request, so the number of series is bounded.

***

## 2) Inspect a sample of the low-cardinality metrics

Below is a short excerpt from the scraped metrics (kept as raw text to avoid MDX parsing):

```text theme={null}
# HELP cart_order_duration_seconds Duration of cart order requests in seconds
# TYPE cart_order_duration_seconds histogram
cart_order_duration_seconds_bucket{endpoint="/cart/user/{user_id}",le="0.005",method="POST",status="200"} 0.0
cart_order_duration_seconds_bucket{endpoint="/cart/user/{user_id}",le="0.01",method="POST",status="200"} 0.0
cart_order_duration_seconds_bucket{endpoint="/cart/user/{user_id}",le="0.025",method="POST",status="200"} 3.0
cart_order_duration_seconds_bucket{endpoint="/cart/user/{user_id}",le="0.05",method="POST",status="200"} 12.0
...
```

Key points:

* The `endpoint` label uses a route template (`/cart/user/{user_id}`), not the concrete `user_id`.
* Labels present: `endpoint`, `le`, `method`, `status` — none are unbounded per-user labels.

***

## 3) Deploy the high-cardinality application and generate traffic

Apply the high-cardinality manifests and verify the pod:

```bash theme={null}
kubectl apply -f high-cardinality-app/k8s/deployment.yaml
kubectl apply -f high-cardinality-app/k8s/service.yaml
kubectl apply -f high-cardinality-app/k8s/servicemonitor.yaml

kubectl get po -w
# cart-api-high-75cb49fbfcf-6vl74  1/1  Running ...
# cart-api-low-7fb455599c-xmtvg    1/1  Running ...
```

Start the high-cardinality traffic generator:

```bash theme={null}
./high-cardinality-app/scripts/generate-traffic.sh high &
# Starting traffic generation for cart-api-high...
# Target: http://localhost:30802
# Simulating 1000 unique users
```

After \~45 seconds, stop the generator and capture metrics:

```bash theme={null}
pkill -f "generate-traffic.sh"
curl http://localhost:30802/metrics > ~/high-cardinality-metrics.txt
# 100  358k  100  358k    0     0   750k      0 --:--:-- --:--:-- --:--:--  751k
```

Count bucket lines:

```bash theme={null}
grep "cart_order_duration_seconds_bucket" ~/high-cardinality-metrics.txt | wc -l
# 2114
```

Compare: low-cardinality had 28 lines vs high-cardinality with 2,114 lines — roughly a 100× increase caused by exporting a per-user label.

***

## 4) Inspect the high-cardinality metric lines

A sample of the high-cardinality output shows a concrete `user_id` label being exported:

```text theme={null}
cart_order_duration_seconds_bucket{endpoint="/cart/user/{user_id}",le="0.005",method="POST",status="200",user_id="user_0787"} 0.0
cart_order_duration_seconds_bucket{endpoint="/cart/user/{user_id}",le="0.01",method="POST",status="200",user_id="user_0787"} 0.0
cart_order_duration_seconds_bucket{endpoint="/cart/user/{user_id}",le="0.025",method="POST",status="200",user_id="user_0787"} 0.0
cart_order_duration_seconds_bucket{endpoint="/cart/user/{user_id}",le="0.05",method="POST",status="200",user_id="user_0787"} 0.0
...
```

That concrete `user_id` label is the unbounded dimension responsible for multiplying the number of distinct time series.

***

## 5) Why this is a problem

* Each unique combination of label values is stored as a separate time series.
* An effectively unbounded label (user IDs, IPs, UUIDs, pod names) multiplies cardinality and RAM consumption.
* Rule of thumb: each series consumes on the order of kilobytes. Millions or billions of series means terabytes of RAM.

Best practices:

| Problem | Recommended action |
| - | - |
| Endpoint labels containing raw IDs | Use route templates like `/cart/user/{user_id}` instead of raw IDs |
| Unbounded labels (`user_id`, IPs, UUIDs) | Avoid exporting them as metrics; use logs or a dedicated store |
| Sudden series growth | Monitor and alert on series-count increases |
| Need per-request diagnostic data | Use logs/traces or a separate high-cardinality store |

If you cannot change the application (legacy or third-party), use Prometheus metric relabeling at scrape time to drop or rewrite problematic labels so high-cardinality data is never stored.

***

## 6) Use metric relabeling to drop the high-cardinality label

Prometheus supports `metric_relabel_configs` and the Prometheus Operator's ServiceMonitor CRD exposes `metricRelabelings` under each `endpoints` entry. Apply relabeling so the `user_id` label is removed during scrape and never written to the TSDB.

Here is the ServiceMonitor snippet that includes the `metricRelabelings` section (the original manifest showed this as commented lines). Keep `metricRelabelings` under the `endpoints` stanza:

```yaml theme={null}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: cart-api-high
  namespace: monitoring
  labels:
    app: cart-api-high
    release: prometheus-stack
spec:
  selector:
    matchLabels:
      app: cart-api-high
  namespaceSelector:
    matchNames:
      - default
  endpoints:
    - port: http
      path: /metrics
      interval: 15s
      scrapeTimeout: 10s
## NOTE: Uncomment the following lines to enable dropping the user_id label at scrape time.
# metricRelabelings:
# - action: labeldrop
#   regex: user_id
```

Uncomment those lines in `high-cardinality-app/k8s/servicemonitor.yaml`, then reapply:

```bash theme={null}
kubectl apply -f high-cardinality-app/k8s/servicemonitor.yaml
# servicemonitor.monitoring.coreos.com/cart-api-high configured
```

Regenerate traffic and allow Prometheus to scrape the target. The relabeling will drop `user_id` before Prometheus stores the samples.

***

## 7) Verify the effect in Grafana Explore

Log in to Grafana (example credentials: `admin` / `admin`), open Explore, and run:

```promql theme={null}
count(cart_order_duration_seconds_bucket{job="cart-api-high"})
```

You should observe the series count drop from roughly 2,000 to 28 — matching the low-cardinality deployment. This confirms that relabeling removed the `user_id` dimension at scrape time, reducing stored series while preserving aggregated metrics.

![A screenshot of a web page prompting to update your password with fields for new and confirm password and a Submit button. A browser password-save popup overlays the page, showing the username "admin" and a masked password.](https://mintcdn.com/kodekloud-c4ac6d9a/qM9vA-hQoWNCxcKa/images/Grafana-Prometheus-for-Metrics-Driven-Observability/Cardinality/Demo-Diagnosing-High-Cardinality-in-Metric-Design/update-password-confirm-save-popup.jpg?fit=max\&auto=format\&n=qM9vA-hQoWNCxcKa\&q=85\&s=0233ae0a4a759bebabfddfc5f5562a49)

Example Grafana Explore query and expected result:

```promql theme={null}
count(cart_order_duration_seconds_bucket{job="cart-api-high"})
# → 28
```

***

## 8) Final takeaway

* Prometheus scrapes whatever metrics an application exposes.
* Metric relabeling (via `metric_relabel_configs` or `metricRelabelings` in a ServiceMonitor) runs at scrape time and can drop or modify labels before samples are written to the TSDB.
* Dropping unbounded labels (for example `user_id`) prevents cardinality explosions and dramatically reduces Prometheus storage and RAM usage — without modifying the application.

Do not rely on metrics to hold high-cardinality, per-entity data. Use logs, traces, or a dedicated datastore for per-request diagnostic data. Reserve metrics for aggregated and bounded observability signals.

***

## Links and references

* Prometheus metric relabeling and `metric_relabel_configs`: [https://prometheus.io/docs/prometheus/latest/configuration/configuration/#metric\_relabel\_configs](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#metric_relabel_configs)
* Prometheus Operator ServiceMonitor API: [https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/api.md#servicemonitor](https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/api.md#servicemonitor)
* Grafana Explore documentation: [https://grafana.com/docs/grafana/latest/explore/](https://grafana.com/docs/grafana/latest/explore/)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/grafana-prometheus-for-metrics-driven-observability/module/90070254-6cda-4097-b5a2-5c7c271512ee/lesson/41a7742c-fe4a-474b-8427-b2706ea88d88)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.