This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: opentelemetry-prometheus-exemplar-cardinality-guardrail

OpenTelemetry Prometheus Exemplar Cardinality & Memory Bounds

Enforces bounded exemplar reservoirs and deterministic trace-metric correlation on latency spikes while eliminating Prometheus TSDB label explosion and OTel Collector OOM eviction under burst traffic. Prevents injecting high-cardinality trace identifiers into dimensional metric labels and mandates strict memory-limiter pipelining.

Prohibited Anti-Pattern: Unbounded Metric Cardinality and Unconstrained Exemplar Reservoirs Triggering Collector Eviction Crashes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Prometheus Exemplar Cardinality & Memory Bounds - Enforces bounded exemplar reservoirs and deterministic trace-metric correlation on latency spikes while eliminating Prometheus TSDB label explosion and OTel Collector OOM eviction under burst traffic. Prevents injecting high-cardinality trace identifiers into dimensional metric labels and mandates strict memory-limiter pipelining.
globs: src/telemetry/**/*.{ts,js,go}, otel-collector-config*.{yaml,yml}, prometheus*.{yaml,yml}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-prometheus-exemplar-cardinality-guardrail"
---

# OpenTelemetry Prometheus Exemplar Cardinality & Memory Bounds

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Metric Cardinality and Unconstrained Exemplar Reservoirs Triggering Collector Eviction Crashes

## System Constraints
You are a Principal Software Architect enforcing production-grade OpenTelemetry metrics and Prometheus exemplar invariants. You must prevent memory exhaustion and TSDB degradation by mandating bounded exemplar reservoir sampling, preventing TraceID promotion to dimensional metric attributes, and enforcing OTel Collector memory limiter safeguards.

## Strict Guidelines
- Engineers MUST ALWAYS attach TraceID and SpanID via OpenTelemetry Exemplars rather than dimensional metric attributes (labels) to keep time-series cardinality strictly bounded.
- Engineers MUST configure Prometheus Histograms with explicit bucket distributions and fixed-size Exemplar Reservoirs (e.g., AlignedHistogramBucketExemplarReservoir) to prevent unconstrained heap expansion during burst traffic.
- OTel Collector configurations MUST place the `memory_limiter` processor as the very first processor in every pipeline with explicit check_interval, limit_percentage, and spike_limit_percentage.
- Code MUST NEVER bind dynamic, unbounded request identifiers (such as UUIDs, user IDs, raw URLs, or authorization tokens) into Prometheus metric label keys or values.
- Collector pipelines MUST use the `batch` processor with strictly bounded `send_batch_max_size` and `timeout` values directly downstream of the `memory_limiter`.
- Exemplar filters MUST use sample-based or trace-sampled filters (e.g., `TraceBasedExemplarFilter`) rather than unrestricted in-memory accumulators to ensure zero CPU/memory regression during upstream denial-of-service events.

## Bad vs Good Implementations
### TypeScript OpenTelemetry Metric Instrument with Proper Exemplar Context vs. Dimensional Leakage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Injecting `trace_id` and raw dynamic URIs directly into the metric attribute map creates a new time series for every single request, rapidly exhausting Prometheus TSDB index memory and crashing the OpenTelemetry Collector.
```typescript
import { metrics, trace, context } from '@opentelemetry/api';

const meter = metrics.getMeter('billing-service');
const latencyHistogram = meter.createHistogram('http_request_duration_seconds');

export function recordRequestLatency(durationSec: number, reqPath: string): void {
  const activeSpan = trace.getSpan(context.active());
  const spanContext = activeSpan?.spanContext();

  // ANTI-PATTERN: Promoting trace_id and raw unbounded paths into metric attributes.
  // This causes infinite Prometheus time-series generation (cardinality explosion)
  // and collector OOM eviction crashes under sustained burst traffic.
  latencyHistogram.record(durationSec, {
    'http.route': reqPath, // e.g. /users/123e4567-e89b-12d3-a456-426614174000
    'trace_id': spanContext ? spanContext.traceId : 'none',
    'span_id': spanContext ? spanContext.spanId : 'none'
  });
}
```

#### Production Standard (Correct)
> **Standard**: Attributes are strictly constrained to low-cardinality bounded sets (parameterized routes). Exemplar data (TraceID/SpanID) is passed implicitly via the OpenTelemetry Context, allowing Prometheus to bind latency spikes to traces without creating new metric time-series.
```typescript
import { metrics, context } from '@opentelemetry/api';

const meter = metrics.getMeter('billing-service');
const latencyHistogram = meter.createHistogram('http_request_duration_seconds', {
  description: 'HTTP request duration in seconds',
  unit: 's',
});

export function recordRequestLatency(durationSec: number, parameterizedRoute: string, statusCode: number): void {
  // INVARIANT: Attributes are strictly static, bounded dimensions.
  // Trace correlation is handled out-of-band via context passing to Exemplar Reservoirs.
  const staticAttributes = {
    'http.route': parameterizedRoute, // e.g., '/users/:id'
    'http.status_code': statusCode
  };

  // OpenTelemetry SDK automatically extracts TraceID & SpanID from active context
  // into the Prometheus exemplar reservoir without adding series cardinality.
  latencyHistogram.record(durationSec, staticAttributes, context.active());
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry Prometheus Exemplar Cardinality & Memory Bounds

OpenTelemetry Prometheus Exemplar Cardinality & Memory Bounds defines an industrial-grade behavioral standard for devops engineering. Enforces bounded exemplar reservoirs and deterministic trace-metric correlation on latency spikes while eliminating Prometheus TSDB label explosion and OTel Collector OOM eviction under burst traffic. Prevents injecting high-cardinality trace identifiers into dimensional metric labels and mandates strict memory-limiter pipelining. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbounded Metric Cardinality and Unconstrained Exemplar Reservoirs Triggering Collector Eviction Crashes Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbounded Metric Cardinality and Unconstrained Exemplar Reservoirs Triggering Collector Eviction CrashesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS attach TraceID and SpanID via OpenTelemetry Exemplars rather than dimensional metric attributes (labels) to keep time-series cardinality strictly bounded.

Engineers MUST ALWAYS attach TraceID and SpanID via OpenTelemetry Exemplars rather than dimensional metric attributes (labels) to keep time-series cardinality strictly bounded.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST configure Prometheus Histograms with explicit bucket distributions and fixed-size Exemplar Reservoirs (e.g., AlignedHistogramBucketExemplarReservoir) to prevent unconstrained heap expansion during burst traffic.

Engineers MUST configure Prometheus Histograms with explicit bucket distributions and fixed-size Exemplar Reservoirs (e.g., AlignedHistogramBucketExemplarReservoir) to prevent unconstrained heap expansion during burst traffic.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

OTel Collector configurations MUST place the `memory_limiter` processor as the very first processor in every pipeline with explicit check_interval, limit_percentage, and spike_limit_percentage.

OTel Collector configurations MUST place the `memory_limiter` processor as the very first processor in every pipeline with explicit check_interval, limit_percentage, and spike_limit_percentage.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code MUST NEVER bind dynamic, unbounded request identifiers (such as UUIDs, user IDs, raw URLs, or authorization tokens) into Prometheus metric label keys or values.

Code MUST NEVER bind dynamic, unbounded request identifiers (such as UUIDs, user IDs, raw URLs, or authorization tokens) into Prometheus metric label keys or values.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Collector pipelines MUST use the `batch` processor with strictly bounded `send_batch_max_size` and `timeout` values directly downstream of the `memory_limiter`.

Collector pipelines MUST use the `batch` processor with strictly bounded `send_batch_max_size` and `timeout` values directly downstream of the `memory_limiter`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Exemplar filters MUST use sample-based or trace-sampled filters (e.g., `TraceBasedExemplarFilter`) rather than unrestricted in-memory accumulators to ensure zero CPU/memory regression during upstream denial-of-service events.

Exemplar filters MUST use sample-based or trace-sampled filters (e.g., `TraceBasedExemplarFilter`) rather than unrestricted in-memory accumulators to ensure zero CPU/memory regression during upstream denial-of-service events.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is OpenTelemetry Prometheus Exemplar Cardinality & Memory Bounds critical for AI coding assistants?

Enforces bounded exemplar reservoirs and deterministic trace-metric correlation on latency spikes while eliminating Prometheus TSDB label explosion and OTel Collector OOM eviction under burst traffic. Prevents injecting high-cardinality trace identifiers into dimensional metric labels and mandates strict memory-limiter pipelining. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbounded Metric Cardinality and Unconstrained Exemplar Reservoirs Triggering Collector Eviction Crashes) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

OpenTelemetry