This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: opentelemetry-tail-sampling-error-preservation-standard

OpenTelemetry Tail-Based Sampling and Trace Error Preservation Guardrail

Enforces 100% trace capture for all error trees and high-latency anomalies via OpenTelemetry Collector tail-sampling policies while downsampling nominal traffic to protect ingest quotas. Prevents distributed trace fragmentation caused by aggressive upstream head-based sampling and premature collector decision windows.

Prohibited Anti-Pattern: Premature Head-Based Probabilistic Dropping of Distributed Traces and Incomplete Leaf-Span Error Capture

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Tail-Based Sampling and Trace Error Preservation Guardrail - Enforces 100% trace capture for all error trees and high-latency anomalies via OpenTelemetry Collector tail-sampling policies while downsampling nominal traffic to protect ingest quotas. Prevents distributed trace fragmentation caused by aggressive upstream head-based sampling and premature collector decision windows.
globs: **/otel-collector*.{yaml,yml}, **/collector/**/*.{yaml,yml}, src/telemetry/**/*.{ts,js,go,py}, src/instrumentation/**/*.{ts,js,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-tail-sampling-error-preservation-standard"
---

# OpenTelemetry Tail-Based Sampling and Trace Error Preservation Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Premature Head-Based Probabilistic Dropping of Distributed Traces and Incomplete Leaf-Span Error Capture

## System Constraints
You are a Principal Observability and Infrastructure Architect enforcing the OpenTelemetry Tail-Based Trace Sampling Error-Preservation Standard. Mandate that application SDKs always emit 100% of spans upstream (head-sampling disabled or set to 1.0) and that routing collectors employ stateful tail-sampling processors configured to unconditionally preserve 100% of error traces (status_code=ERROR, HTTP 5xx, or exception events) and latency outliers, while deterministically downsampling nominal spans. Enforce strict decision-wait window buffers and trace-ID routing affinity.

## Strict Guidelines
- Engineers MUST ALWAYS configure edge/application OpenTelemetry SDKs with `AlwaysOnSampler` (or parent-based equivalent) to delegate sampling decisions entirely to the collector layer.
- Engineers MUST NOT apply probabilistic head-based sampling at the application layer when root-cause trace context across downstream microservices is required.
- Collector pipelines MUST configure the `tail_sampling` processor with policy rules evaluating `status_code` (`ERROR`), explicit error attributes (`error=true`, `http.status_code >= 500`), and latency thresholds before falling back to probabilistic rules.
- The `tail_sampling` processor MUST define a `decision_wait` window that strictly exceeds the 99th percentile end-to-end distributed transaction duration (minimum recommended: 10s-30s) to prevent orphan child span collection.
- Collector instances executing tail sampling MUST sit behind a trace-ID-consistent load-balancing layer (e.g., OpenTelemetry Load-Balancing Exporter using `routing_key: trace_id`) to ensure all spans for a trace arrive at the same collector instance.
- Application code MUST explicitly set span status to `StatusCode.ERROR` and record exceptions using `span.recordException(err)` rather than merely logging errors to stdout.
- Components NEVER drop root spans of failed requests; any error anywhere in the distributed trace tree MUST trigger the retention of the entire root-to-leaf trace execution path.

## Bad vs Good Implementations
### OpenTelemetry Collector Tail-Sampling Processor Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Probabilistic sampling executes blind downsampling before a trace completes. If an error occurs in downstream services (e.g., database failure or HTTP 500), 95% of those failing traces are permanently dropped, making distributed debugging impossible.
```yaml
# INSECURE/DEFECTIVE: Naive probabilistic head sampling drops 99% of error traces
processors:
  probabilistic_sampler:
    sampling_percentage: 5.0

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

#### Production Standard (Correct)
> **Standard**: The tail_sampling processor retains spans in memory for 30s across all services. If any span within the trace registers an ERROR status, HTTP 5xx code, or exceeds 2000ms latency, 100% of the entire trace tree is preserved, while nominal healthchecks and nominal baseline requests are safely downsampled.
```yaml
# PRODUCTION STANDARD: Tail-based sampling guarantees 100% error and latency capture
processors:
  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: false }
      - name: preserve-errors
        type: status_code
        status_code: { status_codes: [ ERROR ] }
      - name: preserve-http-server-errors
        type: numeric_attribute
        numeric_attribute: { key: http.status_code, min_value: 500, max_value: 599 }
      - name: preserve-latency-anomalies
        type: latency
        latency: { threshold_ms: 2000 }
      - name: sample-nominal-traffic
        type: probabilistic
        probabilistic: { sampling_percentage: 1.0 }

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

### Application-Side Semantic Error and Exception Recording (TypeScript)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to invoke span.setStatus({ code: SpanStatusCode.ERROR }) and span.recordException(err) keeps the span status as UNSET. The downstream tail sampler will not recognize this trace as an error and will subject it to probabilistic dropping.
```typescript
import { trace } from '@opentelemetry/api';

const tracer = trace.getTracer('checkout-service');

export async function handlePayment(paymentId: string) {
  return tracer.startActiveSpan('handlePayment', async (span) => {
    try {
      return await processCharge(paymentId);
    } catch (err: any) {
      // VIOLATION: Logging without setting OTel span status leaves span nominal (UNSET),
      // causing the tail sampler to misclassify the trace as successful.
      console.error('Payment failed', err);
      throw err;
    } finally {
      span.end();
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly marks the span status as SpanStatusCode.ERROR and records structured exception events. This guarantees that the collector's tail-sampling processor status_code policy matches and preserves the full trace context.
```typescript
import { trace, SpanStatusCode } from '@opentelemetry/api';

const tracer = trace.getTracer('checkout-service');

export async function handlePayment(paymentId: string) {
  return tracer.startActiveSpan('handlePayment', async (span) => {
    try {
      const result = await processCharge(paymentId);
      span.setStatus({ code: SpanStatusCode.OK });
      return result;
    } catch (err: unknown) {
      const error = err instanceof Error ? err : new Error(String(err));
      // Mandated invariant: Record exception details and explicitly flag ERROR status
      span.recordException(error);
      span.setStatus({
        code: SpanStatusCode.ERROR,
        message: error.message,
      });
      span.setAttribute('error', true);
      throw error;
    } finally {
      span.end();
    }
  });
}
```

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 Tail-Based Sampling and Trace Error Preservation Guardrail

OpenTelemetry Tail-Based Sampling and Trace Error Preservation Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces 100% trace capture for all error trees and high-latency anomalies via OpenTelemetry Collector tail-sampling policies while downsampling nominal traffic to protect ingest quotas. Prevents distributed trace fragmentation caused by aggressive upstream head-based sampling and premature collector decision windows. 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: Premature Head-Based Probabilistic Dropping of Distributed Traces and Incomplete Leaf-Span Error Capture 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 DriftPremature Head-Based Probabilistic Dropping of Distributed Traces and Incomplete Leaf-Span Error CaptureCritical
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 configure edge/application OpenTelemetry SDKs with `AlwaysOnSampler` (or parent-based equivalent) to delegate sampling decisions entirely to the collector layer.

Engineers MUST ALWAYS configure edge/application OpenTelemetry SDKs with `AlwaysOnSampler` (or parent-based equivalent) to delegate sampling decisions entirely to the collector layer.

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 apply probabilistic head-based sampling at the application layer when root-cause trace context across downstream microservices is required.

Engineers MUST NOT apply probabilistic head-based sampling at the application layer when root-cause trace context across downstream microservices is required.

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 configure the `tail_sampling` processor with policy rules evaluating `status_code` (`ERROR`), explicit error attributes (`error=true`, `http.status_code >= 500`), and latency thresholds before falling back to probabilistic rules.

Collector pipelines MUST configure the `tail_sampling` processor with policy rules evaluating `status_code` (`ERROR`), explicit error attributes (`error=true`, `http.status_code >= 500`), and latency thresholds before falling back to probabilistic 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.
4

The `tail_sampling` processor MUST define a `decision_wait` window that strictly exceeds the 99th percentile end-to-end distributed transaction duration (minimum recommended

The `tail_sampling` processor MUST define a `decision_wait` window that strictly exceeds the 99th percentile end-to-end distributed transaction duration (minimum recommended: 10s-30s) to prevent orphan child span collection.

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

Collector instances executing tail sampling MUST sit behind a trace-ID-consistent load-balancing layer (e.g., OpenTelemetry Load-Balancing Exporter using `routing_key

Collector instances executing tail sampling MUST sit behind a trace-ID-consistent load-balancing layer (e.g., OpenTelemetry Load-Balancing Exporter using `routing_key: trace_id`) to ensure all spans for a trace arrive at the same collector instance.

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

Application code MUST explicitly set span status to `StatusCode.ERROR` and record exceptions using `span.recordException(err)` rather than merely logging errors to stdout.

Application code MUST explicitly set span status to `StatusCode.ERROR` and record exceptions using `span.recordException(err)` rather than merely logging errors to stdout.

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

Components NEVER drop root spans of failed requests

Components NEVER drop root spans of failed requests; any error anywhere in the distributed trace tree MUST trigger the retention of the entire root-to-leaf trace execution path.

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 Tail-Based Sampling and Trace Error Preservation Guardrail critical for AI coding assistants?

Enforces 100% trace capture for all error trees and high-latency anomalies via OpenTelemetry Collector tail-sampling policies while downsampling nominal traffic to protect ingest quotas. Prevents distributed trace fragmentation caused by aggressive upstream head-based sampling and premature collector decision windows. 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 (Premature Head-Based Probabilistic Dropping of Distributed Traces and Incomplete Leaf-Span Error Capture) 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