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

OpenTelemetry v1.28 Dynamic Attribute Cardinality Guardrail & Schema Validation

Enforces compile-time metric attribute typing and runtime cardinality shedding on OpenTelemetry metric streams. Prevents downstream TSDB (Prometheus, M3DB, Cortex, VictoriaMetrics) memory exhaustion and OOM cascades caused by unbounded dynamic dimensions such as UUIDs, email addresses, or unparameterized URLs.

Prohibited Anti-Pattern: Injecting Dynamic High-Cardinality Identifiers Directly into OpenTelemetry Metric Dimensions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry v1.28 Dynamic Attribute Cardinality Guardrail & Schema Validation - Enforces compile-time metric attribute typing and runtime cardinality shedding on OpenTelemetry metric streams. Prevents downstream TSDB (Prometheus, M3DB, Cortex, VictoriaMetrics) memory exhaustion and OOM cascades caused by unbounded dynamic dimensions such as UUIDs, email addresses, or unparameterized URLs.
globs: src/**/*.{ts,tsx,js,mjs}, packages/**/*.{ts,js}, instrumentation/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-high-cardinality-dynamic-attribute-guardrail"
---

# OpenTelemetry v1.28 Dynamic Attribute Cardinality Guardrail & Schema Validation

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Injecting Dynamic High-Cardinality Identifiers Directly into OpenTelemetry Metric Dimensions

## System Constraints
You are a Principal Software Architect enforcing production-grade observability standards under OpenTelemetry JS SDK v1.28. You must strictly prevent metric cardinality explosion. Unbounded dynamic data (UUIDs, IP addresses, session tokens, email addresses, raw query params, and un-parameterized HTTP paths) must NEVER be applied to metric labels or attributes. Enforce strict compile-time TypeScript schemas for all metric attributes. Mandate SDK-level runtime View configurations using attributeNameFilter to shed non-whitelisted labels before TSDB ingestion. Dynamic context must be delegated to Tracing Spans, Log Records, or Trace Exemplars.

## Strict Guidelines
- Engineers MUST ALWAYS define metric attributes using sealed TypeScript interfaces, string literal unions, or strict enums instead of accepting generic Record<string, any>.
- Engineers MUST NOT attach runtime-generated dynamic IDs (UUIDs, user IDs, transaction hashes, IP addresses, full raw request URLs) as metric attributes.
- Engineers MUST normalize parameterized HTTP routes (e.g., '/users/:id' rather than '/users/a58c14...') before passing them to HTTP metric instruments.
- Code MUST route unbounded diagnostic attributes into Active Tracing Spans or Trace Exemplars where cardinality is bounded by trace storage, not inverted TSDB index tables.
- Services MUST configure OpenTelemetry View aggregations in MeterProvider initialization using an explicit attributeNameFilter to programmatically drop unauthorized metric labels at runtime.
- Components NEVER accept raw user input or unvetted third-party webhook payloads into metric increment, gauge record, or histogram measurement calls.

## Bad vs Good Implementations
### Metric Instrumentation Cardinality Control & View Filtering

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Attaching unique, unbounded runtime values (UUIDs, transaction IDs, raw URLs) directly to metric counters generates new time-series entries on every request, exploding TSDB index cardinality and risking total cluster collapse.
```typescript
import { metrics } from '@opentelemetry/api';

const meter = metrics.getMeter('billing-service');
const checkoutCounter = meter.createCounter('checkout_operations_total');

export function handleCheckout(req: any, res: any) {
  // CRITICAL ANTI-PATTERN: Direct injection of unbounded high-cardinality attributes
  // This causes millions of unique time-series in the TSDB, leading to memory exhaustion and crash loops.
  checkoutCounter.add(1, {
    'user.id': req.params.userId,               // Unbounded UUID
    'transaction.id': req.body.transactionId,   // Unique per request
    'http.target': req.originalUrl,              // Dynamic query params & un-parameterized IDs
    'customer.email': req.body.customerEmail     // PII and high cardinality
  });

  res.status(200).send({ status: 'completed' });
}
```

#### Production Standard (Correct)
> **Standard**: Enforces type-safe attribute definitions, normalizes routing paths, delegates high-cardinality parameters strictly to tracing spans, and enforces an SDK-level View filter to shed extraneous metric labels at the collection boundary.
```typescript
import { metrics, trace } from '@opentelemetry/api';
import { MeterProvider, View } from '@opentelemetry/sdk-metrics';

// 1. Compile-time bounded metric attribute schema contract
export type CheckoutStatus = 'success' | 'failure';
export type PaymentProvider = 'stripe' | 'adyen' | 'internal';

export interface BoundedCheckoutMetricAttributes {
  'checkout.status': CheckoutStatus;
  'payment.provider': PaymentProvider;
  'http.route': string;
}

const ALLOWED_METRIC_ATTRIBUTES: ReadonlySet<string> = new Set([
  'checkout.status',
  'payment.provider',
  'http.route'
]);

// 2. Runtime View Filter registered on SDK initialization to drop unapproved dynamic keys
export const meterProvider = new MeterProvider({
  views: [
    new View({
      instrumentName: 'checkout_operations_total',
      attributeNameFilter: (attributeName: string) => ALLOWED_METRIC_ATTRIBUTES.has(attributeName)
    })
  ]
});

const meter = meterProvider.getMeter('billing-service', '1.28.0');
const checkoutCounter = meter.createCounter<BoundedCheckoutMetricAttributes>('checkout_operations_total', {
  description: 'Total completed checkout operations',
  unit: '{operation}'
});

export function handleCheckout(req: any, res: any) {
  const activeSpan = trace.getActiveSpan();
  
  // High-cardinality IDs and contextual metadata belong in distributed trace spans
  if (activeSpan) {
    activeSpan.setAttribute('user.id', req.params.userId);
    activeSpan.setAttribute('transaction.id', req.body.transactionId);
  }

  // TSDB metrics strictly bounded to low-cardinality dimensions
  const boundedAttributes: BoundedCheckoutMetricAttributes = {
    'checkout.status': 'success',
    'payment.provider': req.body.provider === 'stripe' ? 'stripe' : 'adyen',
    'http.route': req.route?.path ?? '/api/v1/checkout/:userId' // Normalized route template
  };

  checkoutCounter.add(1, boundedAttributes);
  res.status(200).send({ status: 'completed' });
}
```

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 v1.28 Dynamic Attribute Cardinality Guardrail & Schema Validation

OpenTelemetry v1.28 Dynamic Attribute Cardinality Guardrail & Schema Validation defines an industrial-grade behavioral standard for devops engineering. Enforces compile-time metric attribute typing and runtime cardinality shedding on OpenTelemetry metric streams. Prevents downstream TSDB (Prometheus, M3DB, Cortex, VictoriaMetrics) memory exhaustion and OOM cascades caused by unbounded dynamic dimensions such as UUIDs, email addresses, or unparameterized URLs. 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: Injecting Dynamic High-Cardinality Identifiers Directly into OpenTelemetry Metric Dimensions 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 DriftInjecting Dynamic High-Cardinality Identifiers Directly into OpenTelemetry Metric DimensionsCritical
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 define metric attributes using sealed TypeScript interfaces, string literal unions, or strict enums instead of accepting generic Record<string, any>.

Engineers MUST ALWAYS define metric attributes using sealed TypeScript interfaces, string literal unions, or strict enums instead of accepting generic Record<string, any>.

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 NOT attach runtime-generated dynamic IDs (UUIDs, user IDs, transaction hashes, IP addresses, full raw request URLs) as metric attributes.

Engineers MUST NOT attach runtime-generated dynamic IDs (UUIDs, user IDs, transaction hashes, IP addresses, full raw request URLs) as metric attributes.

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

Engineers MUST normalize parameterized HTTP routes (e.g., '/users/

Engineers MUST normalize parameterized HTTP routes (e.g., '/users/:id' rather than '/users/a58c14...') before passing them to HTTP metric instruments.

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 route unbounded diagnostic attributes into Active Tracing Spans or Trace Exemplars where cardinality is bounded by trace storage, not inverted TSDB index tables.

Code MUST route unbounded diagnostic attributes into Active Tracing Spans or Trace Exemplars where cardinality is bounded by trace storage, not inverted TSDB index tables.

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

Services MUST configure OpenTelemetry View aggregations in MeterProvider initialization using an explicit attributeNameFilter to programmatically drop unauthorized metric labels at runtime.

Services MUST configure OpenTelemetry View aggregations in MeterProvider initialization using an explicit attributeNameFilter to programmatically drop unauthorized metric labels at runtime.

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

Components NEVER accept raw user input or unvetted third-party webhook payloads into metric increment, gauge record, or histogram measurement calls.

Components NEVER accept raw user input or unvetted third-party webhook payloads into metric increment, gauge record, or histogram measurement calls.

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 v1.28 Dynamic Attribute Cardinality Guardrail & Schema Validation critical for AI coding assistants?

Enforces compile-time metric attribute typing and runtime cardinality shedding on OpenTelemetry metric streams. Prevents downstream TSDB (Prometheus, M3DB, Cortex, VictoriaMetrics) memory exhaustion and OOM cascades caused by unbounded dynamic dimensions such as UUIDs, email addresses, or unparameterized URLs. 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 (Injecting Dynamic High-Cardinality Identifiers Directly into OpenTelemetry Metric Dimensions) 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