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

OpenTelemetry Ingress W3C Baggage Attenuation and Cardinality Gate

Enforces strict attenuation, validation, and sanitization of incoming W3C baggage headers at ingress boundaries and API gateways. Prevents metric cardinality explosions and cross-tenant context injection by applying schema allowlists, length bounds, and identity verification before propagating context downstream.

Prohibited Anti-Pattern: Unvalidated W3C Baggage Propagation Allowing High-Cardinality Metrics and Tenant Injection

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Ingress W3C Baggage Attenuation and Cardinality Gate - Enforces strict attenuation, validation, and sanitization of incoming W3C baggage headers at ingress boundaries and API gateways. Prevents metric cardinality explosions and cross-tenant context injection by applying schema allowlists, length bounds, and identity verification before propagating context downstream.
globs: src/middleware/**/*.{ts,js}, src/gateway/**/*.{ts,js}, src/telemetry/**/*.{ts,js}, src/tracing/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-attenuation-gate"
---

# OpenTelemetry Ingress W3C Baggage Attenuation and Cardinality Gate

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unvalidated W3C Baggage Propagation Allowing High-Cardinality Metrics and Tenant Injection

## System Constraints
You are a Principal Observability and Security Engineer enforcing strict W3C Baggage Attenuation at the ingress gateway. Ingress boundaries MUST NOT propagate un-sanitized, client-controlled W3C baggage headers into internal OpenTelemetry contexts, preventing metric dimension explosion, PII contamination, and cross-tenant context spoofing.

## Strict Guidelines
- Gateways MUST ALWAYS filter incoming W3C baggage keys against an explicit, immutable allowlist before downstream context propagation.
- Engineers MUST NOT blindly propagate unparsed or unverified 'baggage' HTTP headers using raw OTel extraction without an attenuation gate.
- Ingress middleware MUST truncate baggage keys and values to deterministic limits (e.g., maximum 32 bytes for keys, 128 bytes for values, maximum 5 entries total).
- Services MUST overwrite tenant-identifying baggage items (such as 'tenant_id' or 'account_id') with cryptographically validated claims from the authenticated session token.
- Telemetry processors NEVER record arbitrary baggage values as metric dimensions without strict finite-enumeration validation.
- Middleware MUST silently drop malformed, non-compliant W3C baggage pairs instead of failing requests, but SHOULD emit an attenuation drop counter metric for auditability.

## Bad vs Good Implementations
### Ingress Baggage Attenuation Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly extracting incoming headers without attenuation trusts raw user baggage, exposing downstream metric processors to cardinality explosions and allowing cross-tenant spoofing.
```typescript
import { Request, Response, NextFunction } from 'express';
import { propagation, context } from '@opentelemetry/api';

export function telemetryMiddleware(req: Request, res: Response, next: NextFunction) {
  // VULNERABLE: Direct propagation allows external callers to inject arbitrary
  // baggage keys, forging tenant contexts or poisoning downstream metric dimensions with UUIDs.
  const extractedContext = propagation.extract(context.active(), req.headers);
  context.with(extractedContext, () => {
    next();
  });
}
```

#### Production Standard (Correct)
> **Standard**: Applies strict allowlist filtering, caps total entries and value lengths to protect metric registries, and forces authoritative tenant context from the verified authentication layer.
```typescript
import { Request, Response, NextFunction } from 'express';
import { propagation, context, baggageEntryMetadataSymbol, BaggageEntry } from '@opentelemetry/api';

const ALLOWED_BAGGAGE_KEYS = new Set(['region', 'client_version', 'trace_tier']);
const MAX_BAGGAGE_ENTRIES = 5;
const MAX_VALUE_LENGTH = 64;

export function telemetryAttenuationMiddleware(req: Request, res: Response, next: NextFunction) {
  // Extract raw incoming context
  const extractedContext = propagation.extract(context.active(), req.headers);
  const incomingBaggage = propagation.getBaggage(extractedContext);

  // Create empty sanitized baggage container
  let sanitizedBaggage = propagation.createBaggage();
  let count = 0;

  if (incomingBaggage) {
    for (const [key, entry] of incomingBaggage.getAllEntries()) {
      if (count >= MAX_BAGGAGE_ENTRIES) break;
      
      // Filter against strict allowlist and bound value length
      if (ALLOWED_BAGGAGE_KEYS.has(key)) {
        const safeValue = entry.value.slice(0, MAX_VALUE_LENGTH);
        sanitizedBaggage = sanitizedBaggage.setEntry(key, { value: safeValue });
        count++;
      }
    }
  }

  // Mutate or assert verified tenant identity from authenticated session only
  const authenticatedTenantId = req.auth?.tenantId;
  if (authenticatedTenantId) {
    sanitizedBaggage = sanitizedBaggage.setEntry('tenant_id', {
      value: authenticatedTenantId
    });
  }

  // Bind sanitized baggage to execution context, clearing untrusted entries
  const attenuatedContext = propagation.setBaggage(extractedContext, sanitizedBaggage);
  context.with(attenuatedContext, () => {
    next();
  });
}
```

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 Ingress W3C Baggage Attenuation and Cardinality Gate

OpenTelemetry Ingress W3C Baggage Attenuation and Cardinality Gate defines an industrial-grade behavioral standard for devops engineering. Enforces strict attenuation, validation, and sanitization of incoming W3C baggage headers at ingress boundaries and API gateways. Prevents metric cardinality explosions and cross-tenant context injection by applying schema allowlists, length bounds, and identity verification before propagating context downstream. 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: Unvalidated W3C Baggage Propagation Allowing High-Cardinality Metrics and Tenant Injection 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 DriftUnvalidated W3C Baggage Propagation Allowing High-Cardinality Metrics and Tenant InjectionCritical
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

Gateways MUST ALWAYS filter incoming W3C baggage keys against an explicit, immutable allowlist before downstream context propagation.

Gateways MUST ALWAYS filter incoming W3C baggage keys against an explicit, immutable allowlist before downstream context propagation.

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 blindly propagate unparsed or unverified 'baggage' HTTP headers using raw OTel extraction without an attenuation gate.

Engineers MUST NOT blindly propagate unparsed or unverified 'baggage' HTTP headers using raw OTel extraction without an attenuation gate.

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

Ingress middleware MUST truncate baggage keys and values to deterministic limits (e.g., maximum 32 bytes for keys, 128 bytes for values, maximum 5 entries total).

Ingress middleware MUST truncate baggage keys and values to deterministic limits (e.g., maximum 32 bytes for keys, 128 bytes for values, maximum 5 entries total).

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 overwrite tenant-identifying baggage items (such as 'tenant_id' or 'account_id') with cryptographically validated claims from the authenticated session token.

Services MUST overwrite tenant-identifying baggage items (such as 'tenant_id' or 'account_id') with cryptographically validated claims from the authenticated session token.

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

Telemetry processors NEVER record arbitrary baggage values as metric dimensions without strict finite-enumeration validation.

Telemetry processors NEVER record arbitrary baggage values as metric dimensions without strict finite-enumeration validation.

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

Middleware MUST silently drop malformed, non-compliant W3C baggage pairs instead of failing requests, but SHOULD emit an attenuation drop counter metric for auditability.

Middleware MUST silently drop malformed, non-compliant W3C baggage pairs instead of failing requests, but SHOULD emit an attenuation drop counter metric for auditability.

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 Ingress W3C Baggage Attenuation and Cardinality Gate critical for AI coding assistants?

Enforces strict attenuation, validation, and sanitization of incoming W3C baggage headers at ingress boundaries and API gateways. Prevents metric cardinality explosions and cross-tenant context injection by applying schema allowlists, length bounds, and identity verification before propagating context downstream. 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 (Unvalidated W3C Baggage Propagation Allowing High-Cardinality Metrics and Tenant Injection) 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