📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

A developer added the user id as a tag on a request metric. A week later Prometheus memory has tripled, dashboards time out, and the managed Prometheus bill has jumped. How do you confirm cardinality is the cause, find the offending metric and label, stop the bleeding, and fix it so it doesn't happen again?

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.

Senior Debugging Advanced cardinality cost-optimisation metrics observability opentelemetry-collector prometheus

🎯 Key points

  • Series = product of label value counts; one user id label multiplies by active users
  • Confirm with prometheus_tsdb_head_series and topk(10, count by (__name__)({__name__=~".+"}))
  • Find the label: count(count by (user_id) (metric)) and the /tsdb-status page
  • Mitigate without a deploy: Collector metricstransform aggregate_labels (re-aggregates) or drop the metric
  • Deleting a label without re-aggregating creates colliding series and rejected samples
  • Code fix: remove the tag; per-user questions go to traces and logs, not metrics
  • OpenTelemetry .NET caps tag combinations per metric (2,000 by default, configurable via CardinalityLimit); alert on otel.metric.overflow
  • Guardrails: attribute allow-lists, series budget alert, PR review; user ids are personal information (APP 11)

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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.id to http.server.request.duration through 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 a metricstransform rule in the OpenTelemetry Collector that re-aggregated the metric on route, method and status code only, which drops user.id without 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.overflow series 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."


Diagnosis steps

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

Mitigations, fastest first

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.

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can diagnose a cardinality explosion methodically, mitigate quickly without a risky deploy, and put guardrails in place.

Green flags

  • Proves it's series count, not traffic, with concrete queries
  • Mitigates at the Collector or relabel layer first
  • Explains histogram multiplication of series
  • Moves per-user data to traces or logs and mentions the privacy angle

Red flags

  • Shortens retention or scales Prometheus up as the fix
  • Rolls back blindly without knowing which change caused it
  • Thinks a label with thousands of values is fine because the metric is 'only one metric'

📚 Learn in depth

1. Why cardinality multiplies

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.

2. What breaks, layer by layer

.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.

3. Finding the culprit

# 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.

4. Removing a label correctly

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:

  • Prometheus labeldrop at scrape produces duplicate series and the scrape fails or samples are rejected.
  • A Collector 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.

5. Where per-user detail belongs

  • Traces: put enduser.id (or a pseudonymous id) on the span; query it in Application Insights or Jaeger. Sampling bounds cost.
  • Logs: structured property for support lookups, with retention set by data class.
  • Exemplars: attach a trace id to a histogram sample, so a slow bucket links to a real trace without a user label.

6. Guardrails

  • Collector allow-list of attributes for metrics (metricstransform or transform with keep rules) as the default.
  • Series budget per service: alert when count by (service_name) exceeds, for example, 20,000.
  • A test that asserts the tag keys of each custom instrument (MetricCollector<T>).
  • PR template line: 'new metric tags: values bounded? list them'.

Try it yourself

  1. Add a GUID tag through IHttpMetricsTagsFeature, run k6 for 5 minutes, and watch prometheus_tsdb_head_series.
  2. Find it with topk and /tsdb-status.
  3. Fix it with a metricstransform aggregate_labels rule and confirm totals still match the request rate.
  4. Lower the SDK CardinalityLimit to 50 on a view and look for otel_metric_overflow in Prometheus.
  5. Write a MetricCollector<double> test that fails if any measurement carries a tag outside an allow-list.

💻 Code

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]

⚠ Common mistakes

  • Mistake: Shortening retention to cut the bill. Why it is wrong: cost and memory are driven by active series, not history. Instead: remove the label and re-aggregate.
  • Mistake: Dropping the label with 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.
  • Mistake: Scaling Prometheus up and moving on. Why it is wrong: the next unbounded label repeats the problem at a larger bill. Instead: fix the label and add a series budget alert.
  • Mistake: Rolling back the whole release blindly. Why it is wrong: it may revert unrelated fixes and doesn't prove the cause. Instead: find the metric and label with topk and count by, then mitigate precisely.
  • Mistake: Ignoring the SDK overflow series. Why it is wrong: once the 2,000-point default limit is hit, real data is merged into an overflow bucket and dashboards lie. Instead: alert when otel.metric.overflow appears.
  • Mistake: Putting user ids, emails or tenant names in metric labels for support. Why it is wrong: unbounded, and personal information in a store not classified for it (APP 11). Instead: use span attributes or logs with pseudonymous ids and proper retention.
  • Mistake: Treating it as a one-off. Why it is wrong: without guardrails someone adds the next one. Instead: attribute allow-lists in the Collector, PR checklist, and tests on tag keys.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the managed Prometheus or Application Insights bill. Why: Checks they understand how each platform turns series into cost.
    How to answer

    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.

  2. When: Candidate says tags must be bounded and tested. Why: Checks they can write metrics correctly in the first place.
    How to answer

    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.

  3. When: Candidate mentions telemetry cost more broadly. Why: Checks they can control log volume and cost as well as metrics.
    How to answer

    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.

🛠 Real-world problems: how you handle them

User id label on the request histogram blew up Prometheus
Situation
[25] .NET services on AKS at [company], Prometheus with Grafana for dashboards and alerts, about [50,000] daily active users; a support-driven change added the user id to request metrics.
Signals
Prometheus pod OOM-killed twice in a day; Grafana panels timing out; `prometheus_tsdb_head_series` from [400k] to [9 million] the day of a deploy; managed ingestion cost alert from Azure Cost Management.
Investigation
Charted `prometheus_tsdb_head_series` against the deploy timeline; `topk(10, count by (__name__) ...)` pointed at `http_server_request_duration_seconds_bucket`; `/tsdb-status` showed `user_id` as the top label by value count; `git log` on the shared middleware package found the `IHttpMetricsTagsFeature` enrichment.
Resolution
Within minutes, added a `metricstransform` `aggregate_labels` rule in the Collector to drop `user_id` and re-aggregate; Prometheus recovered after the next head compaction. Then shipped a package update removing the tag, moved the user id to a pseudonymous span attribute, and wrote the support team a KQL query over traces.
Prevention
Collector attribute allow-list for metrics; alert when series per service exceed 20,000 or `otel_metric_overflow` appears, paging the platform on-call with a runbook; SDK views with `TagKeys` in the shared telemetry package; PR checklist and a tag-key test.

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.

↩ Usually asked after

More in Metrics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me