This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: otel-otlp-cardinality-circuit-breaker-standard

OpenTelemetry OTLP High-Cardinality Dynamic Attribute Scrubbing & Circuit Breaker Guardrail

Protects downstream telemetry collector pipelines, ClickHouse/Tempo backends, and in-memory trace buffers from catastrophic OOM crashes by dynamically bounding, hashing, and shedding unindexed dynamic runtime span attributes. Implements runtime span processors with token bucket rate limiters, strict key allowlists, and deterministic truncated SHA-256 hashing for dynamic entity identifiers.

Prohibited Anti-Pattern: Unbounded Runtime Span Attribute Injection Inducing OTLP Collector Memory Exhaustion and Storage Explosion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry OTLP High-Cardinality Dynamic Attribute Scrubbing & Circuit Breaker Guardrail - Protects downstream telemetry collector pipelines, ClickHouse/Tempo backends, and in-memory trace buffers from catastrophic OOM crashes by dynamically bounding, hashing, and shedding unindexed dynamic runtime span attributes. Implements runtime span processors with token bucket rate limiters, strict key allowlists, and deterministic truncated SHA-256 hashing for dynamic entity identifiers.
globs: src/telemetry/**/*.{ts,js}, src/observability/**/*.{ts,js}, src/instrumentation/**/*.{ts,js}, src/tracing/**/*.{ts,js}, src/server/**/*.{ts,js}, src/app/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-otlp-cardinality-circuit-breaker-standard"
---

# OpenTelemetry OTLP High-Cardinality Dynamic Attribute Scrubbing & Circuit Breaker Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Runtime Span Attribute Injection Inducing OTLP Collector Memory Exhaustion and Storage Explosion

## System Constraints
You are a Principal Observability and Infrastructure Architect enforcing industrial-grade OpenTelemetry OTLP high-cardinality safeguards. You must strictly mandate that all span creation and attribute mutation passes through an inline sanitization and circuit-breaking layer. Unbounded runtime keys, raw UUIDs, high-entropy query payloads, and arbitrary user IDs injected directly into span attributes trigger catastrophic memory allocation and index degradation in downstream time-series storage (Prometheus, Mimir, Tempo, ClickHouse). You must reject any direct, unvalidated span attribute insertion, requiring bounded sets, deterministic hash-masking, maximum attribute count caps, and active circuit-breaking drop strategies.

## Strict Guidelines
- Engineers MUST ALWAYS sanitize span attributes through a dedicated SpanProcessor or bounded telemetry wrapper before dispatching to BatchSpanProcessor.
- Engineers MUST NOT inject raw dynamic identifiers (such as session tokens, raw user IDs, query strings, or memory addresses) directly into OTLP span attributes.
- Dynamic entity identifiers (e.g., tenant-specific UUIDs, transaction identifiers) MUST be masked or deterministically hashed using truncated SHA-256 (e.g., 12-char hex) when low-cardinality aggregation is required.
- Services MUST enforce hard caps on span attributes: MAX_ATTRIBUTES_PER_SPAN <= 32, MAX_ATTRIBUTE_KEY_LENGTH <= 64 bytes, and MAX_ATTRIBUTE_VALUE_LENGTH <= 256 bytes.
- The telemetry layer MUST implement an in-memory circuit breaker that sheds non-critical span attributes or drops spans entirely when memory pressure exceeds 85% or attribute ingest rates exceed safe bucket capacities.
- Span attribute keys MUST be constrained to a strictly defined, validated allowlist or hierarchical namespace (e.g., 'app.*', 'db.system', 'http.route').
- Dynamic keys constructed via string concatenation (e.g., `span.setAttribute(`user_${id}`, value)`) are STRICTLY FORBIDDEN.

## Bad vs Good Implementations
### Unbounded Attribute Injection vs. Bounded Cardinality Guardrail Processor

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly sets raw UUIDs, authentication tokens, and arbitrary user-supplied object keys onto spans. This creates millions of unique index entries in downstream telemetry collectors, rapidly exhausts collector heap memory, and triggers OOM crash loops.
```typescript
import { trace } from '@opentelemetry/api';

const tracer = trace.getTracer('checkout-service');

export function processOrder(orderId: string, userToken: string, rawPayload: Record<string, unknown>) {
  return tracer.startActiveSpan('processOrder', (span) => {
    // FATAL: High-cardinality identifiers & arbitrary keys injected directly into trace buffer
    span.setAttribute('order.id', orderId); // High-cardinality UUID
    span.setAttribute('auth.token', userToken); // PII + Infinite Cardinality
    
    // FATAL: Dynamic, unconstrained object key generation causing index explosion in Tempo/ClickHouse
    for (const [key, value] of Object.entries(rawPayload)) {
      span.setAttribute(`payload.${key}`, String(value));
    }
    
    span.end();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements strict cardinality bounding: hashes dynamic UUIDs with truncated SHA-256, strictly limits key space against an allowlist, truncates attribute value length, and drops unindexed/unapproved attributes before they reach the export buffer.
```typescript
import { createHash } from 'node:crypto';
import { trace, Span, SpanKind } from '@opentelemetry/api';

const tracer = trace.getTracer('checkout-service');

const MAX_ATTRIBUTES_PER_SPAN = 32;
const MAX_VALUE_LENGTH = 128;
const ALLOWED_KEYS = new Set(['order.hash', 'service.environment', 'http.status_code', 'checkout.tier']);

class CardinalityGuard {
  private static hashIdentifier(raw: string): string {
    return createHash('sha256').update(raw).digest('hex').substring(0, 12);
  }

  public static safeSetAttribute(span: Span, key: string, value: unknown, currentCount: number): boolean {
    if (currentCount >= MAX_ATTRIBUTES_PER_SPAN || !ALLOWED_KEYS.has(key)) {
      return false; // Circuit-breaker shedding dynamic or excess attributes
    }
    
    const strValue = typeof value === 'string' ? value : JSON.stringify(value);
    const boundedValue = strValue.length > MAX_VALUE_LENGTH 
      ? strValue.substring(0, MAX_VALUE_LENGTH) + '...[TRUNCATED]' 
      : strValue;

    span.setAttribute(key, boundedValue);
    return true;
  }

  public static hashEntityId(id: string): string {
    return this.hashIdentifier(id);
  }
}

export function processOrder(orderId: string, userToken: string, tier: string) {
  return tracer.startActiveSpan('processOrder', { kind: SpanKind.INTERNAL }, (span) => {
    let attrCount = 0;
    
    // Invariant: Bounded cardinality through truncated hashing and key allowlisting
    if (CardinalityGuard.safeSetAttribute(span, 'order.hash', CardinalityGuard.hashEntityId(orderId), attrCount)) {
      attrCount++;
    }
    if (CardinalityGuard.safeSetAttribute(span, 'checkout.tier', tier, attrCount)) {
      attrCount++;
    }
    
    span.end();
  });
}
```

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 OTLP High-Cardinality Dynamic Attribute Scrubbing & Circuit Breaker Guardrail

OpenTelemetry OTLP High-Cardinality Dynamic Attribute Scrubbing & Circuit Breaker Guardrail defines an industrial-grade behavioral standard for devops engineering. Protects downstream telemetry collector pipelines, ClickHouse/Tempo backends, and in-memory trace buffers from catastrophic OOM crashes by dynamically bounding, hashing, and shedding unindexed dynamic runtime span attributes. Implements runtime span processors with token bucket rate limiters, strict key allowlists, and deterministic truncated SHA-256 hashing for dynamic entity identifiers. 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 Runtime Span Attribute Injection Inducing OTLP Collector Memory Exhaustion and Storage Explosion 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 Runtime Span Attribute Injection Inducing OTLP Collector Memory Exhaustion and Storage ExplosionCritical
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 sanitize span attributes through a dedicated SpanProcessor or bounded telemetry wrapper before dispatching to BatchSpanProcessor.

Engineers MUST ALWAYS sanitize span attributes through a dedicated SpanProcessor or bounded telemetry wrapper before dispatching to BatchSpanProcessor.

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 inject raw dynamic identifiers (such as session tokens, raw user IDs, query strings, or memory addresses) directly into OTLP span attributes.

Engineers MUST NOT inject raw dynamic identifiers (such as session tokens, raw user IDs, query strings, or memory addresses) directly into OTLP span 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

Dynamic entity identifiers (e.g., tenant-specific UUIDs, transaction identifiers) MUST be masked or deterministically hashed using truncated SHA-256 (e.g., 12-char hex) when low-cardinality aggregation is required.

Dynamic entity identifiers (e.g., tenant-specific UUIDs, transaction identifiers) MUST be masked or deterministically hashed using truncated SHA-256 (e.g., 12-char hex) when low-cardinality aggregation is required.

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

Services MUST enforce hard caps on span attributes

Services MUST enforce hard caps on span attributes: MAX_ATTRIBUTES_PER_SPAN <= 32, MAX_ATTRIBUTE_KEY_LENGTH <= 64 bytes, and MAX_ATTRIBUTE_VALUE_LENGTH <= 256 bytes.

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

The telemetry layer MUST implement an in-memory circuit breaker that sheds non-critical span attributes or drops spans entirely when memory pressure exceeds 85% or attribute ingest rates exceed safe bucket capacities.

The telemetry layer MUST implement an in-memory circuit breaker that sheds non-critical span attributes or drops spans entirely when memory pressure exceeds 85% or attribute ingest rates exceed safe bucket capacities.

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

Span attribute keys MUST be constrained to a strictly defined, validated allowlist or hierarchical namespace (e.g., 'app.*', 'db.system', 'http.route').

Span attribute keys MUST be constrained to a strictly defined, validated allowlist or hierarchical namespace (e.g., 'app.*', 'db.system', 'http.route').

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

Dynamic keys constructed via string concatenation (e.g., `span.setAttribute(`user_${id}`, value)`) are STRICTLY FORBIDDEN.

Dynamic keys constructed via string concatenation (e.g., `span.setAttribute(`user_${id}`, value)`) are STRICTLY FORBIDDEN.

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 OTLP High-Cardinality Dynamic Attribute Scrubbing & Circuit Breaker Guardrail critical for AI coding assistants?

Protects downstream telemetry collector pipelines, ClickHouse/Tempo backends, and in-memory trace buffers from catastrophic OOM crashes by dynamically bounding, hashing, and shedding unindexed dynamic runtime span attributes. Implements runtime span processors with token bucket rate limiters, strict key allowlists, and deterministic truncated SHA-256 hashing for dynamic entity identifiers. 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 Runtime Span Attribute Injection Inducing OTLP Collector Memory Exhaustion and Storage Explosion) 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