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

OpenTelemetry Semantic Conventions and Cardinality Quarantine Standard

Enforces deterministic attribute bounds, strict baggage allowlisting, and automated redaction of dynamic high-cardinality values across OpenTelemetry distributed tracing pipelines. Prevents backend APM ingest denial-of-service, memory exhaustion, and runaway indexing costs by quarantining unbounded parameters at instrumentation boundaries.

Prohibited Anti-Pattern: Unbounded Runtime Baggage and Direct Ingestion of High-Cardinality Variables into Span Attributes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Semantic Conventions and Cardinality Quarantine Standard - Enforces deterministic attribute bounds, strict baggage allowlisting, and automated redaction of dynamic high-cardinality values across OpenTelemetry distributed tracing pipelines. Prevents backend APM ingest denial-of-service, memory exhaustion, and runaway indexing costs by quarantining unbounded parameters at instrumentation boundaries.
globs: src/**/*.ts, src/**/*.js, telemetry/**/*.ts, instrumentation/**/*.ts, collector/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-cardinality-quarantine-guardrail"
---

# OpenTelemetry Semantic Conventions and Cardinality Quarantine Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Runtime Baggage and Direct Ingestion of High-Cardinality Variables into Span Attributes

## System Constraints
You are a Principal Observability and Infrastructure Architect enforcing OpenTelemetry Semantic Conventions Context Cardinality Quarantine. You mandate deterministic limits on trace attributes and context propagation. Reject all code that sets unparameterized routes, raw URLs with UUIDs/emails, unbounded baggage propagation, or missing SpanLimits in NodeTracerProvider initialization.

## Strict Guidelines
- Engineers MUST ALWAYS configure deterministic SpanLimits (attributeCountLimit, attributeValueLengthLimit) during TracerProvider registration.
- Engineers MUST ALWAYS enforce strict parameterized route patterns (e.g., http.route = '/users/:id') rather than injecting raw URLs with UUIDs or query strings into span attributes.
- Engineers MUST NOT propagate arbitrary client headers, raw JWT claims, or variable user payloads directly into W3C Baggage context.
- Code SHOULD implement an explicit CardinalityQuarantineSpanProcessor to truncate, redact, or drop attributes exceeding safe cardinality thresholds before exporter dispatch.
- Services MUST quarantine baggage entries exceeding 128 bytes per key or 2048 bytes in aggregate, rejecting un-whitelisted baggage keys at service entrypoints.
- Components NEVER store PII, session tokens, or unhashed internal identifiers in standard OpenTelemetry semantic convention tags.

## Bad vs Good Implementations
### Span Limits and Cardinality Quarantine Implementation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The provider lacks deterministic SpanLimits, allowing unbounded attribute counts and lengths. The span directly attaches high-cardinality identifiers (UUID in raw URL, email, full payload), and unvetted authorization tokens are inserted into distributed Baggage, risking downstream memory bloat and tracing backend index explosion.
```typescript
import { trace, propagation } from '@opentelemetry/api';
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { SimpleSpanProcessor, ConsoleSpanExporter } from '@opentelemetry/sdk-trace-base';

// ANTI-PATTERN: No SpanLimits configured; vulnerable to memory exhaustion and payload DOS
const provider = new NodeTracerProvider();
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
provider.register();

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

export function handleRequest(req: any) {
  // ANTI-PATTERN: Direct injection of unbounded high-cardinality URI and raw parameters
  const span = tracer.startSpan('http_request');
  span.setAttribute('http.url', req.originalUrl); // e.g., /api/v1/users/550e8400-e29b-41d4-a716-446655440000?search=confidential
  span.setAttribute('user.email', req.user.email);
  span.setAttribute('raw.payload', JSON.stringify(req.body));

  // ANTI-PATTERN: Unbounded Baggage propagation
  const baggage = propagation.createBaggage({
    jwt: req.headers['authorization'] ?? '',
    requestId: req.headers['x-request-id'] ?? ''
  });
  propagation.setBaggage(propagation.extract(trace.setSpan(propagation.context.active(), span), req.headers), baggage);

  span.end();
}
```

#### Production Standard (Correct)
> **Standard**: Configures strict SpanLimits on the NodeTracerProvider to bound payload volume. Implements an explicit CardinalityQuarantineProcessor, utilizes parameterized semantic convention attributes ('http.route') instead of dynamic raw URLs, and strictly allowlists and truncates context baggage entries.
```typescript
import { trace, propagation, Context, Span } from '@opentelemetry/api';
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { BatchSpanProcessor, ConsoleSpanExporter, SpanProcessor, ReadableSpan } from '@opentelemetry/sdk-trace-base';
import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
import { Resource } from '@opentelemetry/resources';

// Safe baggage allowlist
const ALLOWED_BAGGAGE_KEYS = new Set(['tenant.id', 'client.version', 'region']);
const MAX_BAGGAGE_VAL_LEN = 64;

class CardinalityQuarantineProcessor implements SpanProcessor {
  forceFlush(): Promise<void> { return Promise.resolve(); }
  shutdown(): Promise<void> { return Promise.resolve(); }
  onStart(span: Span, _parentContext: Context): void {
    // Mutate or safeguard at start if required
  }
  onEnd(span: ReadableSpan): void {
    // Quarantine / Scrub attributes post-execution before exporter serialization
    const attrs = span.attributes;
    if (attrs['http.url']) {
      delete (attrs as Record<string, unknown>)['http.url'];
    }
  }
}

// PRODUCTION FIX: Hard deterministic limits set on span count and attribute size
const provider = new NodeTracerProvider({
  resource: new Resource({ [SEMRESATTRS_SERVICE_NAME]: 'user-service' }),
  spanLimits: {
    attributeCountLimit: 64,
    attributeValueLengthLimit: 256,
    eventCountLimit: 32
  }
});

provider.addSpanProcessor(new CardinalityQuarantineProcessor());
provider.addSpanProcessor(new BatchSpanProcessor(new ConsoleSpanExporter()));
provider.register();

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

export function handleRequest(req: any) {
  const span = tracer.startSpan('http_request', {
    attributes: {
      // Conform to OTel Semantic Conventions using parameterized route
      'http.method': req.method,
      'http.route': '/api/v1/users/:id',
      'http.status_code': 200
    }
  });

  // PRODUCTION FIX: Sanitized and allowlist-quarantined Baggage propagation
  const safeEntries: Record<string, { value: string }> = {};
  for (const [key, val] of Object.entries(req.headers)) {
    if (ALLOWED_BAGGAGE_KEYS.has(key) && typeof val === 'string') {
      safeEntries[key] = { value: val.slice(0, MAX_BAGGAGE_VAL_LEN) };
    }
  }
  const baggage = propagation.createBaggage(safeEntries);
  propagation.setBaggage(trace.setSpan(propagation.context.active(), span), baggage);

  span.end();
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry Semantic Conventions and Cardinality Quarantine Standard

OpenTelemetry Semantic Conventions and Cardinality Quarantine Standard defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic attribute bounds, strict baggage allowlisting, and automated redaction of dynamic high-cardinality values across OpenTelemetry distributed tracing pipelines. Prevents backend APM ingest denial-of-service, memory exhaustion, and runaway indexing costs by quarantining unbounded parameters at instrumentation boundaries. 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 Baggage and Direct Ingestion of High-Cardinality Variables into Span Attributes 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 Baggage and Direct Ingestion of High-Cardinality Variables into Span AttributesCritical
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 configure deterministic SpanLimits (attributeCountLimit, attributeValueLengthLimit) during TracerProvider registration.

Engineers MUST ALWAYS configure deterministic SpanLimits (attributeCountLimit, attributeValueLengthLimit) during TracerProvider registration.

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 ALWAYS enforce strict parameterized route patterns (e.g., http.route = '/users/

Engineers MUST ALWAYS enforce strict parameterized route patterns (e.g., http.route = '/users/:id') rather than injecting raw URLs with UUIDs or query strings into 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

Engineers MUST NOT propagate arbitrary client headers, raw JWT claims, or variable user payloads directly into W3C Baggage context.

Engineers MUST NOT propagate arbitrary client headers, raw JWT claims, or variable user payloads directly into W3C Baggage context.

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 SHOULD implement an explicit CardinalityQuarantineSpanProcessor to truncate, redact, or drop attributes exceeding safe cardinality thresholds before exporter dispatch.

Code SHOULD implement an explicit CardinalityQuarantineSpanProcessor to truncate, redact, or drop attributes exceeding safe cardinality thresholds before exporter dispatch.

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 quarantine baggage entries exceeding 128 bytes per key or 2048 bytes in aggregate, rejecting un-whitelisted baggage keys at service entrypoints.

Services MUST quarantine baggage entries exceeding 128 bytes per key or 2048 bytes in aggregate, rejecting un-whitelisted baggage keys at service entrypoints.

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 store PII, session tokens, or unhashed internal identifiers in standard OpenTelemetry semantic convention tags.

Components NEVER store PII, session tokens, or unhashed internal identifiers in standard OpenTelemetry semantic convention tags.

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 Semantic Conventions and Cardinality Quarantine Standard critical for AI coding assistants?

Enforces deterministic attribute bounds, strict baggage allowlisting, and automated redaction of dynamic high-cardinality values across OpenTelemetry distributed tracing pipelines. Prevents backend APM ingest denial-of-service, memory exhaustion, and runaway indexing costs by quarantining unbounded parameters at instrumentation boundaries. 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 Baggage and Direct Ingestion of High-Cardinality Variables into Span Attributes) 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