This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: otel-w3c-baggage-sanitization-exemplar-binding

Deterministic W3C Baggage Sanitization and Metric Exemplar Binding Standard

Enforces strict allowlisting, size caps, and redaction on incoming/outgoing W3C Baggage headers while preventing metric cardinality explosion. Ensures high-cardinality contextual attributes propagated via Baggage are bound strictly to Metric Exemplars rather than converted into metric dimensions.

Prohibited Anti-Pattern: Unbounded Baggage Header Propagation and Ingress Baggage-to-Metric Dimension Leakage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic W3C Baggage Sanitization and Metric Exemplar Binding Standard - Enforces strict allowlisting, size caps, and redaction on incoming/outgoing W3C Baggage headers while preventing metric cardinality explosion. Ensures high-cardinality contextual attributes propagated via Baggage are bound strictly to Metric Exemplars rather than converted into metric dimensions.
globs: src/telemetry/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/instrumentation/**/*.{ts,js}, src/infrastructure/observability/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-w3c-baggage-sanitization-exemplar-binding"
---

# Deterministic W3C Baggage Sanitization and Metric Exemplar Binding Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Baggage Header Propagation and Ingress Baggage-to-Metric Dimension Leakage

## System Constraints
You are a Principal Observability and Systems Architect enforcing OpenTelemetry W3C Baggage sanitization and Exemplar binding standards. You must ensure all distributed trace baggage is immutably validated, strictly allowlisted, and size-constrained across process boundaries. You must prohibit mapping high-cardinality baggage entries directly into metric dimensions, mandating metric exemplars instead.

## Strict Guidelines
- Services MUST validate and filter all inbound and outbound W3C Baggage against an explicit, immutable key allowlist with hard byte limits (maximum 8 entries, 128 bytes per key, 256 bytes per value).
- Engineers MUST NOT convert dynamic or high-cardinality Baggage entries directly into metric attributes or dimension labels, which causes metric store cardinality explosion.
- High-cardinality Baggage values (e.g., tenant_id, request_id, customer_tier) MUST be linked to metrics exclusively via OpenTelemetry Exemplars attached to histogram and counter observations.
- Baggage mutations MUST produce a new immutable Context instance using `propagation.setBaggage`; mutating context in-place or leaking unsanitized carrier objects across asynchronous scopes is strictly prohibited.
- Interceptors MUST purge sensitive telemetry data (PII, bearer tokens, passwords, raw query parameters) from Baggage before outbound HTTP/gRPC carrier injection.
- Downstream RPC clients MUST enforce fail-safe stripping: if incoming baggage exceeds the maximum payload size (4096 bytes total), non-essential keys MUST be dropped deterministically to prevent HTTP 431 (Request Header Fields Too Large) failures.

## Bad vs Good Implementations
### Baggage Ingress Sanitization and Exemplar Binding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepts unvalidated, unbounded W3C Baggage headers and iterates through all entries, injecting dynamic baggage values directly into metric labels. This causes catastrophic metric store cardinality explosion (e.g., in Prometheus or M3DB) and leaves the service vulnerable to HTTP 431 header-bloat amplification.
```typescript
import { propagation, context, metrics } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

const meter = metrics.getMeter('order-service');
const requestCounter = meter.createCounter('http_requests_total');

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  // ANTI-PATTERN: Blindly accepting all inbound baggage headers without validation
  const activeContext = propagation.extract(context.active(), req.headers);
  const currentBaggage = propagation.getBaggage(activeContext);

  // ANTI-PATTERN: Leaking arbitrary baggage keys directly into metric dimensions (Cardinality Explosion)
  const metricLabels: Record<string, string> = { path: req.path };
  if (currentBaggage) {
    for (const [key, entry] of currentBaggage.getAllEntries()) {
      metricLabels[key] = entry.value; // Arbitrary cardinality injected into metrics
    }
  }

  requestCounter.add(1, metricLabels);
  context.with(activeContext, () => next());
}
```

#### Production Standard (Correct)
> **Standard**: Validates inbound baggage against an explicit allowlist and length limits, discards unapproved headers to prevent header bloat, and attaches dynamic contextual data via OpenTelemetry Exemplars (the 3rd argument to counter.add with contextual binding) rather than expanding the metric label set.
```typescript
import { propagation, context, metrics, Baggage, BaggageEntry } from '@opentelemetry/api';
import { Request, Response, NextFunction } from 'express';

const meter = metrics.getMeter('order-service');
const requestCounter = meter.createCounter('http_requests_total');

const ALLOWED_BAGGAGE_KEYS = new Set(['tenant_id', 'environment', 'customer_tier']);
const MAX_KEY_LENGTH = 64;
const MAX_VALUE_LENGTH = 256;

function sanitizeBaggage(inboundBaggage: Baggage | undefined): Baggage {
  let sanitized = propagation.createBaggage();
  if (!inboundBaggage) return sanitized;

  for (const [key, entry] of inboundBaggage.getAllEntries()) {
    if (
      ALLOWED_BAGGAGE_KEYS.has(key) &&
      key.length <= MAX_KEY_LENGTH &&
      entry.value.length <= MAX_VALUE_LENGTH
    ) {
      sanitized = sanitized.setEntry(key, { value: entry.value });
    }
  }
  return sanitized;
}

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  const extractedContext = propagation.extract(context.active(), req.headers);
  const inboundBaggage = propagation.getBaggage(extractedContext);
  const sanitizedBaggage = sanitizeBaggage(inboundBaggage);

  // Bind sanitized baggage to an immutable context
  const sanitizedContext = propagation.setBaggage(extractedContext, sanitizedBaggage);

  // PRODUCTION INVARIANT: Metric attributes remain static/bounded;
  // dynamic contextual baggage is attached to the exemplar context only.
  context.with(sanitizedContext, () => {
    requestCounter.add(1, { route: req.route?.path ?? 'unknown' }, sanitizedContext);
    next();
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Deterministic W3C Baggage Sanitization and Metric Exemplar Binding Standard

Deterministic W3C Baggage Sanitization and Metric Exemplar Binding Standard defines an industrial-grade behavioral standard for devops engineering. Enforces strict allowlisting, size caps, and redaction on incoming/outgoing W3C Baggage headers while preventing metric cardinality explosion. Ensures high-cardinality contextual attributes propagated via Baggage are bound strictly to Metric Exemplars rather than converted into metric dimensions. 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 Header Propagation and Ingress Baggage-to-Metric Dimension Leakage 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 Header Propagation and Ingress Baggage-to-Metric Dimension LeakageCritical
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

Services MUST validate and filter all inbound and outbound W3C Baggage against an explicit, immutable key allowlist with hard byte limits (maximum 8 entries, 128 bytes per key, 256 bytes per value).

Services MUST validate and filter all inbound and outbound W3C Baggage against an explicit, immutable key allowlist with hard byte limits (maximum 8 entries, 128 bytes per key, 256 bytes per value).

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 convert dynamic or high-cardinality Baggage entries directly into metric attributes or dimension labels, which causes metric store cardinality explosion.

Engineers MUST NOT convert dynamic or high-cardinality Baggage entries directly into metric attributes or dimension labels, which causes metric store cardinality explosion.

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

High-cardinality Baggage values (e.g., tenant_id, request_id, customer_tier) MUST be linked to metrics exclusively via OpenTelemetry Exemplars attached to histogram and counter observations.

High-cardinality Baggage values (e.g., tenant_id, request_id, customer_tier) MUST be linked to metrics exclusively via OpenTelemetry Exemplars attached to histogram and counter observations.

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

Baggage mutations MUST produce a new immutable Context instance using `propagation.setBaggage`

Baggage mutations MUST produce a new immutable Context instance using `propagation.setBaggage`; mutating context in-place or leaking unsanitized carrier objects across asynchronous scopes is strictly prohibited.

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

Interceptors MUST purge sensitive telemetry data (PII, bearer tokens, passwords, raw query parameters) from Baggage before outbound HTTP/gRPC carrier injection.

Interceptors MUST purge sensitive telemetry data (PII, bearer tokens, passwords, raw query parameters) from Baggage before outbound HTTP/gRPC carrier injection.

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

Downstream RPC clients MUST enforce fail-safe stripping

Downstream RPC clients MUST enforce fail-safe stripping: if incoming baggage exceeds the maximum payload size (4096 bytes total), non-essential keys MUST be dropped deterministically to prevent HTTP 431 (Request Header Fields Too Large) failures.

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 Deterministic W3C Baggage Sanitization and Metric Exemplar Binding Standard critical for AI coding assistants?

Enforces strict allowlisting, size caps, and redaction on incoming/outgoing W3C Baggage headers while preventing metric cardinality explosion. Ensures high-cardinality contextual attributes propagated via Baggage are bound strictly to Metric Exemplars rather than converted into metric dimensions. 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 Header Propagation and Ingress Baggage-to-Metric Dimension Leakage) 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

Deterministic