This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: otel-collector-tail-sampling-tracestate-retention

OpenTelemetry Collector Tail-Based Sampling and TraceState Retention Guardrail

Enforces deterministic tail-based sampling policies within OpenTelemetry Collector deployments to preserve complete distributed trace lineages exhibiting errors, high latency, or explicit sampling markers. Mandates proper traceID-based load-balancing and W3C TraceState preservation to prevent fractured trace graphs and corrupted downstream context propagation across microservice boundaries.

Prohibited Anti-Pattern: Fragmented Trace Topologies and Lost Root Lineages Due to Naive Head Sampling or Unpartitioned Tail Sampling

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Collector Tail-Based Sampling and TraceState Retention Guardrail - Enforces deterministic tail-based sampling policies within OpenTelemetry Collector deployments to preserve complete distributed trace lineages exhibiting errors, high latency, or explicit sampling markers. Mandates proper traceID-based load-balancing and W3C TraceState preservation to prevent fractured trace graphs and corrupted downstream context propagation across microservice boundaries.
globs: **/collector.yaml, **/collector.yml, **/otel-collector*.yaml, **/otel-collector*.yml, **/k8s/**/*.yaml, infra/monitoring/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-collector-tail-sampling-tracestate-retention"
---

# OpenTelemetry Collector Tail-Based Sampling and TraceState Retention Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Fragmented Trace Topologies and Lost Root Lineages Due to Naive Head Sampling or Unpartitioned Tail Sampling

## System Constraints
You are a Principal Observability Infrastructure Architect enforcing strict OpenTelemetry Collector configurations. Ensure tail_sampling processor topologies enforce deterministic trace routing via loadbalancing exporters, guarantee W3C TraceContext and TraceState retention, and prevent broken distributed span graphs by pairing multi-tier collectors correctly with memory limiters and non-dropping batch processors.

## Strict Guidelines
- Collectors deploying the `tail_sampling` processor MUST ALWAYS be preceded by a dedicated routing layer deploying the `loadbalancing` exporter partitioned by `trace_id`.
- Engineers MUST NOT run the `tail_sampling` processor behind round-robin or least-connection load balancers, as span fragments will diverge across distinct collector instances.
- Collector pipelines MUST ALWAYS declare `memory_limiter` as the very first processor in both traces and metrics pipelines to prevent OOM kills under traffic spikes.
- Tail-sampling policies MUST prioritize non-probabilistic invariants first (HTTP 5xx status codes, gRPC errors, latency threshold breaches) before evaluating downstream probabilistic drop rules.
- Services MUST NEVER mutate or strip the `tracestate` header across service hops or within Collector `transform` processors, ensuring vendor and tenant metadata remains intact.
- Collector pipelines MUST configure `decision_wait` to exceed the p99 end-to-end trace latency plus downstream network jitter (typically 10s-30s) to avoid premature partial trace eviction.
- Engineers MUST set `expected_new_traces_per_sec` accurately based on peak production throughput to avoid aggressive map reallocations and dropped span buffers.

## Bad vs Good Implementations
### Broken: Round-Robin Ingress to Single-Stage Collector with Headless Tail Sampling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spans of the same trace arrive at different collector instances via standard L7 routing, causing the tail_sampling processor to evaluate fragmented, incomplete spans. Short decision_wait (2s) drops slow spans, and omitting memory_limiter risks OOM crashes.
```yaml
processors:
  tail_sampling:
    decision_wait: 2s
    expected_new_traces_per_sec: 100
    policies:
      - name: latency-policy
        type: latency
        latency: { threshold_ms: 1000 }

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [tail_sampling, batch] # Missing memory_limiter; spans split randomly by L4/L7 load balancer
      exporters: [otlp/backend]
```

#### Production Standard (Correct)
> **Standard**: The pipeline integrates memory management upfront, provisions adequate decision buffer time (30s) and throughput scaling, prioritizes deterministic error and latency retention, drops synthetic noise, and retains nominal traces at a controlled 5% sample.
```yaml
processors:
  memory_limiter:
    check_interval: 1s
    limit_percentage: 75
    spike_limit_percentage: 20
  tail_sampling:
    decision_wait: 30s
    num_traces: 100000
    expected_new_traces_per_sec: 5000
    policies:
      - name: drop-healthchecks
        type: string_attribute
        string_attribute: { key: http.target, values: [ "/healthz", "/metrics" ], enabled_regex_matching: false, invert_match: true }
      - name: status-code-errors
        type: status_code
        status_code: { status_codes: [ ERROR ] }
      - name: latency-sla-breach
        type: latency
        latency: { threshold_ms: 2000 }
      - name: nominal-probabilistic-sample
        type: probabilistic
        probabilistic: { sampling_percentage: 5.0 }
  batch:
    send_batch_size: 8192
    timeout: 5s

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [memory_limiter, tail_sampling, batch]
      exporters: [otlp/backend]
```

### Deterministic Multi-Tier Routing: Front-Proxy Loadbalancing Exporter Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Round-robin resolution to a pool of tail-sampling collectors guarantees that child spans and root spans arrive at different nodes, causing tail-sampling processors to make sampling decisions on incomplete trace subsets.
```yaml
exporters:
  otlp:
    endpoint: "collector-pool.internal:4317" # Standard DNS round-robin breaks trace coherence

service:
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [otlp]
```

#### Production Standard (Correct)
> **Standard**: Uses the trace_id consistent hashing router in the front-proxy tier to guarantee all spans sharing the same TraceID arrive at the exact same tail-sampling collector replica.
```yaml
exporters:
  loadbalancing:
    protocol:
      otlp:
        tls:
          insecure: true
    resolver:
      dns:
        hostname: "collector-tail-sampling-headless.monitoring.svc.cluster.local"
        port: 4317
    routing_key: "trace_id"

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [memory_limiter]
      exporters: [loadbalancing]
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry Collector Tail-Based Sampling and TraceState Retention Guardrail

OpenTelemetry Collector Tail-Based Sampling and TraceState Retention Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic tail-based sampling policies within OpenTelemetry Collector deployments to preserve complete distributed trace lineages exhibiting errors, high latency, or explicit sampling markers. Mandates proper traceID-based load-balancing and W3C TraceState preservation to prevent fractured trace graphs and corrupted downstream context propagation across microservice 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: Fragmented Trace Topologies and Lost Root Lineages Due to Naive Head Sampling or Unpartitioned Tail Sampling 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 DriftFragmented Trace Topologies and Lost Root Lineages Due to Naive Head Sampling or Unpartitioned Tail SamplingCritical
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

Collectors deploying the `tail_sampling` processor MUST ALWAYS be preceded by a dedicated routing layer deploying the `loadbalancing` exporter partitioned by `trace_id`.

Collectors deploying the `tail_sampling` processor MUST ALWAYS be preceded by a dedicated routing layer deploying the `loadbalancing` exporter partitioned by `trace_id`.

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 run the `tail_sampling` processor behind round-robin or least-connection load balancers, as span fragments will diverge across distinct collector instances.

Engineers MUST NOT run the `tail_sampling` processor behind round-robin or least-connection load balancers, as span fragments will diverge across distinct collector instances.

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

Collector pipelines MUST ALWAYS declare `memory_limiter` as the very first processor in both traces and metrics pipelines to prevent OOM kills under traffic spikes.

Collector pipelines MUST ALWAYS declare `memory_limiter` as the very first processor in both traces and metrics pipelines to prevent OOM kills under traffic spikes.

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

Tail-sampling policies MUST prioritize non-probabilistic invariants first (HTTP 5xx status codes, gRPC errors, latency threshold breaches) before evaluating downstream probabilistic drop rules.

Tail-sampling policies MUST prioritize non-probabilistic invariants first (HTTP 5xx status codes, gRPC errors, latency threshold breaches) before evaluating downstream probabilistic drop rules.

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 NEVER mutate or strip the `tracestate` header across service hops or within Collector `transform` processors, ensuring vendor and tenant metadata remains intact.

Services MUST NEVER mutate or strip the `tracestate` header across service hops or within Collector `transform` processors, ensuring vendor and tenant metadata remains intact.

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

Collector pipelines MUST configure `decision_wait` to exceed the p99 end-to-end trace latency plus downstream network jitter (typically 10s-30s) to avoid premature partial trace eviction.

Collector pipelines MUST configure `decision_wait` to exceed the p99 end-to-end trace latency plus downstream network jitter (typically 10s-30s) to avoid premature partial trace eviction.

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.
7

Engineers MUST set `expected_new_traces_per_sec` accurately based on peak production throughput to avoid aggressive map reallocations and dropped span buffers.

Engineers MUST set `expected_new_traces_per_sec` accurately based on peak production throughput to avoid aggressive map reallocations and dropped span buffers.

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 Collector Tail-Based Sampling and TraceState Retention Guardrail critical for AI coding assistants?

Enforces deterministic tail-based sampling policies within OpenTelemetry Collector deployments to preserve complete distributed trace lineages exhibiting errors, high latency, or explicit sampling markers. Mandates proper traceID-based load-balancing and W3C TraceState preservation to prevent fractured trace graphs and corrupted downstream context propagation across microservice 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 (Fragmented Trace Topologies and Lost Root Lineages Due to Naive Head Sampling or Unpartitioned Tail Sampling) 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