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

OpenTelemetry W3C Baggage Isolation and Metric Cardinality Guardrail

Distributed tracing setups that blindly forward W3C Baggage across perimeter boundaries leak sensitive PII downstream and trigger metric cardinality denial-of-service. This guardrail mandates strict allowlisting for baggage propagation across services, completely decouples baggage from metric dimensions, and enforces bounded cardinality controls at span and metric boundaries.

Prohibited Anti-Pattern: Blind W3C Baggage Propagation and High-Cardinality Dimension Injection into Metrics

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry W3C Baggage Isolation and Metric Cardinality Guardrail - Distributed tracing setups that blindly forward W3C Baggage across perimeter boundaries leak sensitive PII downstream and trigger metric cardinality denial-of-service. This guardrail mandates strict allowlisting for baggage propagation across services, completely decouples baggage from metric dimensions, and enforces bounded cardinality controls at span and metric boundaries.
globs: src/**/*.ts, src/**/*.js, lib/**/*.ts, instrumentation/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-baggage-isolation-cardinality-guardrail"
---

# OpenTelemetry W3C Baggage Isolation and Metric Cardinality Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind W3C Baggage Propagation and High-Cardinality Dimension Injection into Metrics

## System Constraints
You are a Principal Observability and SRE Architect enforcing OpenTelemetry W3C Baggage Isolation and Metric Cardinality Guardrails. You must prevent telemetry cost blowouts, backend TSDB memory exhaustion, and sensitive data leakage via tracing baggage. Strictly enforce allowlists on baggage propagation, prohibit raw baggage keys from becoming metric labels, and mandate bounded cardinality bucketing.

## Strict Guidelines
- Engineers MUST ALWAYS sanitize and filter W3C Baggage using an explicit organizational allowlist before propagating context downstream.
- Engineers MUST NEVER inject dynamic or arbitrary W3C Baggage entries directly into Metric instrument attributes.
- Engineers MUST validate that metric attributes have bounded cardinality (<100 distinct values); high-cardinality identifiers (UUIDs, user IDs, emails, raw paths) MUST only exist as trace span attributes or structured logs.
- Services MUST strip incoming W3C Baggage headers at untrusted edge boundaries unless explicitly verified and prefixed (e.g., `x-org-*`).
- Components MUST NOT bind un-sanitized baggage values to external HTTP client headers going to third-party or untrusted APIs.
- Instrumentation code SHOULD configure OpenTelemetry View attribute filters to drop unexpected dimensions before TSDB export.

## Bad vs Good Implementations
### Sanitizing Outbound Baggage and Safeguarding Metric Cardinality

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly mapping high-cardinality fields (transactionId, userEmail, IP) to metric attributes explodes metric cardinality in systems like Prometheus/Datadog, leading to massive cloud bills or TSDB crash. Passing raw baggage entries without allowlisting exposes PII to all downstream microservices and third parties.
```typescript
import { baggage, metrics, context } from '@opentelemetry/api';

const meter = metrics.getMeter('order-service');
const checkoutCounter = meter.createCounter('checkout_requests_total');

export async function processCheckout(req: { headers: Record<string, string>; userId: string }) {
  // VULNERABILITY 1: Unsanitized baggage reading and blind addition
  const currentBaggage = baggage.getBaggage(context.active());
  const userEmail = currentBaggage?.getEntry('user.email')?.value;
  const transactionId = req.headers['x-transaction-id'];

  // VULNERABILITY 2: Telemetry cardinality explosion & PII leakage into TSDB labels
  checkoutCounter.add(1, {
    'user.email': userEmail || 'unknown', // Unbounded PII
    'transaction.id': transactionId,     // Unbounded UUID -> TSDB OOM
    'client.ip': req.headers['x-forwarded-for'],
  });

  // VULNERABILITY 3: Blindly forwarding all baggage downstream without filtering
  // Outbound HTTP requests automatically forward raw baggage to third-party APIs
}
```

#### Production Standard (Correct)
> **Standard**: High-cardinality attributes (transaction ID, user ID) are attached to Spans rather than Metrics, preserving debuggability without blowing up TSDB time-series cardinality. Inbound baggage is strictly allowlisted against approved business keys, preventing accidental downstream PII leakage.
```typescript
import { baggage, metrics, trace, context } from '@opentelemetry/api';

const meter = metrics.getMeter('order-service');
const tracer = trace.getTracer('order-service');

// Cardinality-bounded metric: only predefined, finite categorical values
const checkoutCounter = meter.createCounter('checkout_requests_total', {
  description: 'Total checkouts partitioned by customer tier and status',
});

const ALLOWED_BAGGAGE_KEYS = new Set(['app.tenant.tier', 'app.experiment.cohort']);
const VALID_TIERS = new Set(['free', 'starter', 'enterprise']);

export async function processCheckout(req: { headers: Record<string, string>; userId: string }) {
  const activeCtx = context.active();
  const currentBaggage = baggage.getBaggage(activeCtx);

  // 1. High-cardinality data belongs strictly on Tracing Spans, NEVER on Metrics
  const span = tracer.startSpan('processCheckout', undefined, activeCtx);
  span.setAttribute('order.transaction_id', req.headers['x-transaction-id'] ?? 'unknown');
  span.setAttribute('user.id', req.userId);

  // 2. Bound metric attributes to finite categorical values
  const rawTier = currentBaggage?.getEntry('app.tenant.tier')?.value ?? 'free';
  const validatedTier = VALID_TIERS.has(rawTier) ? rawTier : 'unknown';

  checkoutCounter.add(1, {
    'tenant.tier': validatedTier,
    'operation.status': 'success',
  });

  // 3. Construct an isolated, sanitized Baggage container for downstream propagation
  let isolatedBaggage = baggage.createBaggage();
  if (currentBaggage) {
    for (const [key, entry] of currentBaggage.getAllEntries()) {
      if (ALLOWED_BAGGAGE_KEYS.has(key)) {
        isolatedBaggage = isolatedBaggage.setEntry(key, entry);
      }
    }
  }

  span.end();
  return baggage.setBaggage(activeCtx, isolatedBaggage);
}
```

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 W3C Baggage Isolation and Metric Cardinality Guardrail

OpenTelemetry W3C Baggage Isolation and Metric Cardinality Guardrail defines an industrial-grade behavioral standard for devops engineering. Distributed tracing setups that blindly forward W3C Baggage across perimeter boundaries leak sensitive PII downstream and trigger metric cardinality denial-of-service. This guardrail mandates strict allowlisting for baggage propagation across services, completely decouples baggage from metric dimensions, and enforces bounded cardinality controls at span and metric 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: Blind W3C Baggage Propagation and High-Cardinality Dimension Injection into Metrics 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 DriftBlind W3C Baggage Propagation and High-Cardinality Dimension Injection into MetricsCritical
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 and filter W3C Baggage using an explicit organizational allowlist before propagating context downstream.

Engineers MUST ALWAYS sanitize and filter W3C Baggage using an explicit organizational allowlist before propagating context downstream.

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 NEVER inject dynamic or arbitrary W3C Baggage entries directly into Metric instrument attributes.

Engineers MUST NEVER inject dynamic or arbitrary W3C Baggage entries directly into Metric instrument 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 validate that metric attributes have bounded cardinality (<100 distinct values)

Engineers MUST validate that metric attributes have bounded cardinality (<100 distinct values); high-cardinality identifiers (UUIDs, user IDs, emails, raw paths) MUST only exist as trace span attributes or structured logs.

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 strip incoming W3C Baggage headers at untrusted edge boundaries unless explicitly verified and prefixed (e.g., `x-org-*`).

Services MUST strip incoming W3C Baggage headers at untrusted edge boundaries unless explicitly verified and prefixed (e.g., `x-org-*`).

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

Components MUST NOT bind un-sanitized baggage values to external HTTP client headers going to third-party or untrusted APIs.

Components MUST NOT bind un-sanitized baggage values to external HTTP client headers going to third-party or untrusted APIs.

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

Instrumentation code SHOULD configure OpenTelemetry View attribute filters to drop unexpected dimensions before TSDB export.

Instrumentation code SHOULD configure OpenTelemetry View attribute filters to drop unexpected dimensions before TSDB export.

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 Isolation and Metric Cardinality Guardrail critical for AI coding assistants?

Distributed tracing setups that blindly forward W3C Baggage across perimeter boundaries leak sensitive PII downstream and trigger metric cardinality denial-of-service. This guardrail mandates strict allowlisting for baggage propagation across services, completely decouples baggage from metric dimensions, and enforces bounded cardinality controls at span and metric 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 (Blind W3C Baggage Propagation and High-Cardinality Dimension Injection into Metrics) 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