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

OpenTelemetry W3C Baggage Context Propagation and Cardinality Bounding Standard

Enforces strict entry counts, byte-size quotas, and allowlisted schema definitions on W3C Baggage context propagation across distributed trace boundaries. Prevents propagation of unbounded user input, ephemeral session IDs, and oversized payloads that trigger HTTP 431 (Request Header Fields Too Large) outages or cause metric cardinality explosions in downstream telemetry backends.

Prohibited Anti-Pattern: Unbounded Baggage Injection and Indiscriminate Metric Dimension Propagation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Context Propagation and Cardinality Bounding Standard - Enforces strict entry counts, byte-size quotas, and allowlisted schema definitions on W3C Baggage context propagation across distributed trace boundaries. Prevents propagation of unbounded user input, ephemeral session IDs, and oversized payloads that trigger HTTP 431 (Request Header Fields Too Large) outages or cause metric cardinality explosions in downstream telemetry backends.
globs: **/instrumentation/**/*.{ts,js,py,go,java}, **/telemetry/**/*.{ts,js,py,go,java}, **/middleware/**/*.{ts,js,py,go,java}, **/tracing/**/*.{ts,js,py,go,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-w3c-baggage-cardinality-bounding-standard"
---

# OpenTelemetry W3C Baggage Context Propagation and Cardinality Bounding Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Baggage Injection and Indiscriminate Metric Dimension Propagation

## System Constraints
You are a Principal Software Architect enforcing the OpenTelemetry W3C Baggage Context Propagation Cardinality Bounding Standard. Baggage is designed for lightweight, operational metadata (e.g., tenant tier, region, client release channel) across service boundaries—it is NOT an RPC payload bus or arbitrary cache. Mandate strict allowlisting of baggage keys, enforce maximum byte-size and entry limits (W3C RFC allows 8192 bytes total, but internal service-to-service bounds MUST be restricted to <= 1024 bytes total, <= 16 keys, <= 128 bytes per value), and strictly prohibit promoting raw baggage items into downstream metric dimensions without cardinality mapping.

## Strict Guidelines
- Engineers MUST ALWAYS validate baggage keys against an explicit runtime allowlist (enum/schema) before injection or downstream extraction.
- Engineers MUST NOT propagate high-cardinality dynamic identifiers (e.g., UUIDs, email addresses, order IDs, authorization tokens, raw timestamps) via W3C baggage.
- Services MUST enforce total baggage size constraints (<= 1024 total bytes, <= 16 entries, <= 128 bytes per value) and discard or truncate over-limit entries with a logged telemetry drop warning.
- Components NEVER promote incoming baggage entries directly to metric dimensions or log index keys without cardinality sanitization (e.g., bucket mapping or low-cardinality categorical classification).
- Code SHOULD sanitize and strip unapproved W3C baggage headers at ingress perimeter API gateways to prevent external injection attacks.

## Bad vs Good Implementations
### Unbounded Dynamic Baggage Injection vs Schema-Bounded Baggage Context Management

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Arbitrary request parameters, raw JSON bodies, and high-cardinality IDs are injected into Baggage. This violates W3C header size limits (causing HTTP 431 errors on downstream reverse proxies), leaks sensitive authorization tokens to third-party microservices, and risks telemetry database indexing crashes if translated to metrics.
```typescript
import { propagation, context } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

// ANTI-PATTERN: Injects unbounded raw request data into W3C baggage without bounds or allowlist
export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  let currentBaggage = propagation.getBaggage(context.active()) || propagation.createBaggage();

  // DANGEROUS: Injects high-cardinality UUID and unbounded arbitrary user agent header
  currentBaggage = currentBaggage
    .setEntry('user_id', { value: req.headers['x-user-id'] as string }) // High-cardinality ID
    .setEntry('request_payload', { value: JSON.stringify(req.body) }) // Exceeds byte budget; risks HTTP 431
    .setEntry('session_token', { value: req.headers['authorization'] as string }); // PII/Secret leak

  const newContext = propagation.setBaggage(context.active(), currentBaggage);
  context.with(newContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements an allowlist-only policy (`ALLOWED_BAGGAGE_KEYS`), strictly checks key counts (max 8) and value lengths (max 64 bytes), enforces an aggregate byte boundary (1024 bytes), and sanitizes values into categorical invariants to prevent downstream header inflation and metric cardinality explosions.
```typescript
import { propagation, context, Baggage, BaggageEntry } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

// Explicit low-cardinality allowlist for distributed context
const ALLOWED_BAGGAGE_KEYS = new Set(['tenant_tier', 'region', 'traffic_source'] as const);
type AllowedKey = 'tenant_tier' | 'region' | 'traffic_source';

const MAX_TOTAL_BYTES = 1024;
const MAX_KEY_COUNT = 8;
const MAX_VALUE_LENGTH = 64;

export function setBoundedBaggage(
  currentBaggage: Baggage,
  key: AllowedKey,
  value: string
): Baggage {
  if (!ALLOWED_BAGGAGE_KEYS.has(key)) {
    return currentBaggage;
  }

  const sanitizedValue = value.trim().slice(0, MAX_VALUE_LENGTH);
  const currentEntries = currentBaggage.getAllEntries();

  if (currentEntries.length >= MAX_KEY_COUNT && !currentBaggage.getEntry(key)) {
    return currentBaggage; // Drop entry if count limit is exceeded
  }

  // Calculate projected byte length to prevent header buffer overflow
  const projectedSize = currentEntries.reduce((total, [k, entry]) => {
    return total + k.length + entry.value.length;
  }, key.length + sanitizedValue.length);

  if (projectedSize > MAX_TOTAL_BYTES) {
    return currentBaggage; // Discard to preserve HTTP header budgets
  }

  return currentBaggage.setEntry(key, { value: sanitizedValue });
}

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  let currentBaggage = propagation.getBaggage(context.active()) || propagation.createBaggage();

  const rawTier = (req.headers['x-tenant-tier'] as string) || 'free';
  const safeTier = ['free', 'pro', 'enterprise'].includes(rawTier) ? rawTier : 'unknown';

  currentBaggage = setBoundedBaggage(currentBaggage, 'tenant_tier', safeTier);
  currentBaggage = setBoundedBaggage(currentBaggage, 'region', process.env.NODE_REGION || 'unknown');

  const newContext = propagation.setBaggage(context.active(), currentBaggage);
  context.with(newContext, () => {
    next();
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry W3C Baggage Context Propagation and Cardinality Bounding Standard

OpenTelemetry W3C Baggage Context Propagation and Cardinality Bounding Standard defines an industrial-grade behavioral standard for devops engineering. Enforces strict entry counts, byte-size quotas, and allowlisted schema definitions on W3C Baggage context propagation across distributed trace boundaries. Prevents propagation of unbounded user input, ephemeral session IDs, and oversized payloads that trigger HTTP 431 (Request Header Fields Too Large) outages or cause metric cardinality explosions in downstream telemetry backends. 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 Baggage Injection and Indiscriminate Metric Dimension Propagation 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 Baggage Injection and Indiscriminate Metric Dimension PropagationCritical
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 validate baggage keys against an explicit runtime allowlist (enum/schema) before injection or downstream extraction.

Engineers MUST ALWAYS validate baggage keys against an explicit runtime allowlist (enum/schema) before injection or downstream extraction.

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 propagate high-cardinality dynamic identifiers (e.g., UUIDs, email addresses, order IDs, authorization tokens, raw timestamps) via W3C baggage.

Engineers MUST NOT propagate high-cardinality dynamic identifiers (e.g., UUIDs, email addresses, order IDs, authorization tokens, raw timestamps) via W3C baggage.

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

Services MUST enforce total baggage size constraints (<= 1024 total bytes, <= 16 entries, <= 128 bytes per value) and discard or truncate over-limit entries with a logged telemetry drop warning.

Services MUST enforce total baggage size constraints (<= 1024 total bytes, <= 16 entries, <= 128 bytes per value) and discard or truncate over-limit entries with a logged telemetry drop warning.

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

Components NEVER promote incoming baggage entries directly to metric dimensions or log index keys without cardinality sanitization (e.g., bucket mapping or low-cardinality categorical classification).

Components NEVER promote incoming baggage entries directly to metric dimensions or log index keys without cardinality sanitization (e.g., bucket mapping or low-cardinality categorical classification).

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

Code SHOULD sanitize and strip unapproved W3C baggage headers at ingress perimeter API gateways to prevent external injection attacks.

Code SHOULD sanitize and strip unapproved W3C baggage headers at ingress perimeter API gateways to prevent external injection attacks.

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 W3C Baggage Context Propagation and Cardinality Bounding Standard critical for AI coding assistants?

Enforces strict entry counts, byte-size quotas, and allowlisted schema definitions on W3C Baggage context propagation across distributed trace boundaries. Prevents propagation of unbounded user input, ephemeral session IDs, and oversized payloads that trigger HTTP 431 (Request Header Fields Too Large) outages or cause metric cardinality explosions in downstream telemetry backends. 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 Baggage Injection and Indiscriminate Metric Dimension Propagation) 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