Covers diagnosing a metric cardinality explosion (series counts, top metrics and labels with PromQL, workspace ingestion metrics), immediate mitigation (Collector or relabel drop, SDK views and cardinality limits), the code fix, where per-user data belongs instead, and guardrails.
Cardinality is the number of unique label combinations; each is a separate time series. A user_id label multiplies a metric's series by the number of active users, and on a histogram that is again multiplied by every bucket, so 20 routes × 5 status codes × 17 buckets × 50,000 users is 85 million series.
I confirm it with prometheus_tsdb_head_series (or the Azure Monitor workspace's active series and ingestion metrics), find the metric with topk(10, count by (__name__) ({__name__=~".+"})), and the label with count(count by (user_id) (...)). I stop the bleeding without a deploy by dropping the label in the OpenTelemetry Collector or with Prometheus labeldrop, then remove the tag in code and move per-user questions to traces and logs.
The trade-off: per-user detail is real value, but metrics are the wrong place for unbounded data.
"The first thing I'd do is prove it's cardinality, not traffic. Prometheus exposes
prometheus_tsdb_head_series; if that went from a few hundred thousand to several million on the day of a deploy while request rate is flat, it's a series explosion. On managed Prometheus I'd look at the Azure Monitor workspace's active time series and samples ingested per minute. Then I find the culprit:topk(10, count by (__name__) ({__name__=~".+"}))gives the metrics with the most series, and for the top one I count distinct values per label. A label with 48,000 values on a request histogram is the answer.For example, at [company] a developer added
user.idtohttp.server.request.durationthrough an enrichment callback so support could see slow users. Because it's a histogram, every user got [17] bucket series per route and status code. Prometheus head series went from [400k] to [9 million], memory tripled, Grafana timed out, and ingestion cost was up [x]%. I stopped the bleeding in minutes with ametricstransformrule in the OpenTelemetry Collector that re-aggregated the metric on route, method and status code only, which dropsuser.idwithout leaving colliding series, and needed no application deploy. Then we removed the tag in code, and gave support what they actually needed: a KQL query over traces filtered by a pseudonymous user attribute, which is sampled and access-controlled.Afterwards I added guardrails: a series budget alert per service, an alert when the SDK's
otel.metric.overflowseries appears, an allow-list of metric attributes in the Collector, and a PR checklist line for any new tag. I'd also point out the privacy angle: user ids in a metrics store are personal information under the Privacy Act and APP 11, in a system nobody classified for it.The mistake I see is fixing the bill by shortening retention. The problem is series count; retention only hides it."
| Step | Tool / query | What it tells you |
|---|---|---|
| 1. Is it series, not samples? | prometheus_tsdb_head_series, workspace active series metric |
Series jumped on a date; traffic didn't |
| 2. Which metric? | topk(10, count by (__name__) ({__name__=~".+"})) |
The metric with millions of series |
| 3. Which label? | count(count by (user_id) (http_server_request_duration_seconds_bucket)), /tsdb-status |
Distinct values per label |
| 4. Which change? | Git history of the metrics/enrichment code, deploy timeline | The PR and service |
| 5. Impact? | Prometheus memory, query latency, Cost Management | Cost and blast radius |
| Fix | Speed | Needs deploy? | Notes |
|---|---|---|---|
Collector filter processor drops the whole metric |
Minutes | Collector config only | Safe stop-gap; you lose that metric until the fix |
Collector metricstransform aggregate_labels |
Minutes | Collector config only | Keeps the metric, sums away the bad label |
SDK view with TagKeys allow-list and CardinalityLimit |
Hours | App deploy | Re-aggregates in process; defence in depth |
| Remove the tag from code | Hours to days | App deploy | The real fix |
A plain labeldrop at scrape or delete_key in the Collector is not enough on its own: series that differed only by user_id collide, and samples are rejected or overwritten.
After the Collector rule, head series dropped from [9 million] back to [420,000] once the old series went stale and the head block compacted, Prometheus memory went from [48] GB to [15] GB, and Grafana panels loaded in under 2 seconds again. Alerts based on the request histogram kept working throughout because the re-aggregated totals were unchanged.
Checks that the candidate can diagnose a cardinality explosion methodically, mitigate quickly without a risky deploy, and put guardrails in place.
Green flags
Red flags
A metric's series count is the product of the number of values of each label, summed over what actually occurs:
series ≈ routes × methods × status codes × (buckets + 2) × instances × NEW_LABEL
≈ 20 × 2 × 5 × 17 × 6 = 20,400
× 50,000 users ≈ 1 billion (theoretical)
In practice only combinations that occur become series, but even 1% of that is millions. Histograms make it far worse than counters because every bucket is its own series.
.NET process OpenTelemetry SDK keeps one MetricPoint per tag set (memory grows);
default limit 2,000 per metric, extra points go to an overflow series
Collector larger batches, more memory, export queue backs up
Prometheus head block holds every active series in RAM -> OOM, slow compaction
Managed service billed per sample ingested; workspace active-series quota may throttle
Grafana queries fan out over millions of series -> timeouts
The SDK's cardinality limit protects the process, but the overflow series (otel.metric.overflow = true) means your real per-route data is now mixed into one bucket: dashboards quietly become wrong. Seeing the overflow attribute in the back end is itself a diagnostic.
# Total series over time (self-hosted)
prometheus_tsdb_head_series
# Metrics with most series
topk(10, count by (__name__) ({__name__=~".+"}))
# Distinct values of a suspect label on one metric
count(count by (user_id) (http_server_request_duration_seconds_bucket))
# Which service sends it
count by (service_name) (http_server_request_duration_seconds_bucket{user_id!=""})
Prometheus's TSDB status page (/tsdb-status) lists the highest-cardinality metric names and label names directly. In Azure, the Azure Monitor workspace exposes active time series and events-per-minute metrics you can chart and alert on.
Dropping a label is not just deleting a key. Two points that differed only by user_id now have identical labels. If you simply delete the key:
labeldrop at scrape produces duplicate series and the scrape fails or samples are rejected.transform delete_key sends duplicate points that the back end may reject or overwrite.You must re-aggregate: in the SDK with a view that allow-lists tag keys (the SDK aggregates correctly before export), or in the Collector with the metricstransform processor's aggregate_labels action, which keeps the listed labels and sums the rest. If you need a stop-gap in minutes, dropping the whole metric with the filter processor is safe and simple; the built-in RED data is back once the code fix ships.
enduser.id (or a pseudonymous id) on the span; query it in Application Insights or Jaeger. Sampling bounds cost.metricstransform or transform with keep rules) as the default.count by (service_name) exceeds, for example, 20,000.MetricCollector<T>).IHttpMetricsTagsFeature, run k6 for 5 minutes, and watch prometheus_tsdb_head_series.topk and /tsdb-status.metricstransform aggregate_labels rule and confirm totals still match the request rate.CardinalityLimit to 50 on a view and look for otel_metric_overflow in Prometheus.MetricCollector<double> test that fails if any measurement carries a tag outside an allow-list.How the bad tag got in, the code fix, an SDK guardrail, and a Collector mitigation.
// BEFORE: enrichment middleware added user id to the built-in request duration histogram
app.Use(async (context, next) =>
{
var tags = context.Features.Get<IHttpMetricsTagsFeature>();
tags?.Tags.Add(new("user.id", context.User.FindFirst("sub")?.Value)); // unbounded + personal information
await next(context);
});
// AFTER: bounded business tag on the metric, user id only on the trace span
app.Use(async (context, next) =>
{
var plan = context.User.FindFirst("plan")?.Value ?? "anonymous"; // 4 values: anonymous, free, pro, enterprise
context.Features.Get<IHttpMetricsTagsFeature>()?.Tags.Add(new("customer.plan", plan));
System.Diagnostics.Activity.Current?.SetTag("enduser.pseudo_id", context.User.FindFirst("pseudo_id")?.Value);
await next(context);
});
// Guardrail in the SDK: allow-list tag keys and cap cardinality (re-aggregates in process)
builder.Services.AddOpenTelemetry().WithMetrics(m => m
.AddAspNetCoreInstrumentation()
.AddView("http.server.request.duration", new ExplicitBucketHistogramConfiguration
{
TagKeys = ["http.route", "http.request.method", "http.response.status_code", "error.type", "customer.plan"],
CardinalityLimit = 1000
})
.AddOtlpExporter());
# OpenTelemetry Collector: mitigate in minutes without an app deploy.
# aggregate_labels keeps the listed labels and sums the rest, so no duplicate points.
processors:
metricstransform/drop-user-id:
transforms:
- include: http.server.request.duration
action: update
operations:
- action: aggregate_labels
label_set: [http.route, http.request.method, http.response.status_code, error.type]
aggregation_type: sum
service:
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, metricstransform/drop-user-id, batch]
exporters: [prometheusremotewrite]
labeldrop or delete_key alone. Why it is wrong: series that differed only by that label collide, causing rejected samples or wrong values. Instead: re-aggregate with an SDK view or metricstransform aggregate_labels, or drop the whole metric temporarily.topk and count by, then mitigate precisely.otel.metric.overflow appears.Cardinality problems are rarely one bad developer; they're a missing guardrail. The durable fix is a pipeline that refuses unbounded labels by default: an allow-list of attributes per metric in the Collector or in SDK views, a series budget per service with an alert, and review of new tags like any other API change. The other senior point is putting per-entity questions in the right signal: traces and logs are built for high-cardinality fields and can be sampled; metrics are built for low-cardinality aggregates.
| Where per-user data goes | When it fits | Cost | When not to |
|---|---|---|---|
| Metric label | Never for unbounded ids; fine for tiers (free, pro, enterprise) | Series × values | Any id, email or free text |
| Span attribute | Investigating one user's requests | Per span ingested, can be sampled | Aggregate rates and SLOs |
| Structured log property | Audits, support lookups | Per GB | High-volume per-request logging |
| Exemplars on histograms | Jump from a slow bucket to a trace | Small | Back ends without exemplar support |
Prometheus pulls: it scrapes a /metrics endpoint on each target every 15 to 60 seconds and stores each metric-plus-label combination as a time series, queried with PromQL; Grafana draws the dashboards. Azure Monitor is push: the Azure Monitor OpenTelemetry exporter or an agent sends metrics to Application Insights (queried with KQL) or to Azure Monitor managed Prometheus, which keeps PromQL but removes the servers you would otherwise run, and pairs with Azure Managed Grafana.
In all of them cardinality is the cost driver: self-hosted Prometheus pays in memory and disk per active series, managed Prometheus bills per sample ingested, and Log Analytics bills per GB.
On AKS I'd usually pick managed Prometheus plus Grafana for metrics and Application Insights for traces and logs; the trade-off is that you then run two query languages.
I put a feature's metrics in one singleton class that takes IMeterFactory, creates a Meter named after the component (Shop.Orders) and creates the instruments once: a Counter<long> for events such as orders placed, a Histogram<double> in seconds for durations, and an ObservableGauge<T> for current state. Names follow OpenTelemetry semantic conventions (shop.orders.placed, unit {order}), and tags are bounded (channel, outcome), never customer or order ids.
OpenTelemetry picks them up when I register the meter name with AddMeter inside WithMetrics, and the exporter (OTLP to a Collector, the Azure Monitor distro, or Prometheus) is a separate decision. I test with MetricCollector<T> from Microsoft.Extensions.Diagnostics.Testing, which captures measurements from a meter created by the same factory.
The trade-off: every tag value and histogram bucket is a time series you pay for, so I add metrics for questions someone will actually ask.
First measure, don't guess: in Log Analytics run union * | summarize sum(_BilledSize) by itemType, then break traces down by category and message template (OriginalFormat). One or two sources usually dominate: a Debug level left on, EF Core SQL command logging, HTTP body logging, health probes, or two pipelines sending the same data.
Latency rises because logging runs on the request thread: synchronous sinks, a full console queue, or formatting large payloads.
Fix in order: levels per category (configuration, no deploy), remove duplicates and noise, sample traces while keeping metrics complete, then workspace controls: daily cap as a safety net, cheaper table plans, retention, and a cost anomaly alert. The trade-off: every gigabyte you cut must not be the one you need at 3 a.m.
How to tell it (STAR)
**S:** At [company] our Prometheus started getting OOM-killed and Grafana timed out a week after a shared middleware change. **T:** I owned the observability platform and needed to restore dashboards and stop the cost growth. **A:** I showed head series jumped from [400k] to [9 million] on the deploy day, found the request duration histogram and the user id label with topk and the TSDB status page, and traced it to an enrichment middleware. I re-aggregated the metric in the Collector without the label to recover in minutes, then removed the tag in code and gave support a trace-based query instead, plus allow-lists and a series budget alert. **R:** Series dropped back to about [420k], Prometheus memory fell from [48] to [15] GB, and we've had no cardinality incident since.
Last updated 23 Nov 2026.