How-To Guide

How to Implement Trace Sampling Strategies

Choose head, tail and per-key sampling so traces stay useful and cheap: keep every error and slow request while sampling the boring majority.

On this page

  1. Introduction
  2. Head Sampling Versus Tail Sampling
  3. Consistent Sampling Across Services
  4. Tail Policies that Keep What Matters
  5. Sizing the Tail Sampler
  6. Sampling for Metrics and Logs Consistency
  7. Common Pitfalls and Conclusion

Introduction

Tracing every request is too expensive at scale; tracing a fixed percentage is either too sparse to debug a rare failure or too dense to afford. Sampling decides which traces exist at all, and a bad strategy silently discards the very traces you would want during an incident. Good sampling is deliberate: it keeps errors, keeps slow requests, keeps a representative baseline, and drops the uninteresting majority in a way that is consistent for a whole request.

Head Sampling Versus Tail Sampling

Head sampling decides whether to record a trace at the beginning, based on information available then: a percentage, or a deterministic hash of the trace id. It is cheap and stateless, but it cannot know the request will fail, so it discards most errors along with most successes. Tail sampling decides after the trace is complete, when the status and duration are known, so it can keep every error and every slow trace.

Tail sampling needs the whole trace buffered before the decision, which means a collector that holds spans until the trace finishes. That is more resource-intensive and adds a small delay, but it is the only way to guarantee that all errors and all slow requests are retained. In practice, teams combine a head sampler to reduce volume with a tail sampler to bias retention toward interesting traces.

processors:
  tail_sampling:
    decision_wait: 10s
    policies:
      - name: keep-errors
        type: status_code
        status_code: { status_codes: [ERROR] }
      - name: keep-slow
        type: latency
        latency: { threshold_ms: 500 }
      - name: baseline-percent
        type: probabilistic
        probabilistic: { sampling_percentage: 5 }

Consistent Sampling Across Services

A trace that is sampled in one service must be sampled in every service it touches, or you get partial traces with missing spans. The rule is to sample by trace id, so every service makes the same decision for the same trace. Probabilistic head sampling with a deterministic hash of the trace id gives this for free; naive per-service percentage sampling breaks it because each service decides independently.

Propagation is the other half: the sampling decision travels in the trace context headers, so downstream services honour the upstream decision rather than re-rolling. When you change the sampling rate, do it in a way that keeps already-sampled traces consistent for their lifetime, or you will mix rates within a single trace.

import { TraceIdRatioBasedSampler, ParentBasedSampler } from '@opentelemetry/sdk-trace-base';

// ParentBased: honour the upstream decision; only sample fresh roots.
// TraceIdRatioBased: deterministic, so every service agrees on a trace id.
export const sampler = new ParentBasedSampler({
  root: new TraceIdRatioBasedSampler(0.1), // 10% of new traces
});
// same sampler config in every service => consistent whole traces

Tail Policies that Keep What Matters

Tail sampling lets you write policies that express intent. Keep every trace with an error status. Keep every trace slower than a threshold. Keep a low-rate probabilistic baseline for healthy traffic. Optionally keep traces for specific routes, tenants or users during a rollout. Each policy contributes traces to the kept set, so they compose.

Combine the policies with AND and OR. A cheap policy such as “slow” alone catches latency regressions; combined with a route filter it catches them per route. Always include a small probabilistic baseline, because without healthy traffic you cannot compute what normal looks like or measure the effect of a change on ordinary requests.

Sizing the Tail Sampler

Tail sampling costs memory proportional to trace volume times decision wait. If you keep traces for ten seconds before deciding and you receive ten thousand spans per second, you hold on the order of a hundred thousand spans at once. The tail sampler must be deployed where it sees every span for a trace, which usually means load-balancing by trace id so all spans of a trace reach the same instance.

Watch the sampler’s own metrics: traces buffered, decisions made, kept and dropped, and the buffer eviction rate. If traces are being evicted before a decision, your decision wait or buffer size is too small, and you are silently losing traces you meant to keep. Tune the wait to the p99 trace duration.

# Load-balance by trace id so a whole trace lands on one sampler.
processors:
  routing:
    from_attribute: ""
    table:
      - value: ""
        exporters: [loadbalancing]
  # tail_sampling must see every span of a trace => sticky by trace id
connectors:
  loadbalancing:
    routing_key: traceID
service:
  pipelines:
    traces/in:
      receivers: [otlp]
      processors: [routing]
      exporters: [loadbalancing]
    traces/decide:
      receivers: [loadbalancing]
      processors: [tail_sampling]
      exporters: [otlp]

Sampling for Metrics and Logs Consistency

Trace sampling must not affect your metrics, which should count every request, sampled or not. If you derive metrics from sampled spans you will undercount, and burn-rate alerts will be wrong. Keep metrics on an unsampled path, and use sampled traces only for exemplars and detailed investigation.

Logs are a middle ground: logging every request is expensive, so correlate logs to trace sampling. Emit the trace id on every request so a sampled trace can be joined to its logs, and consider sampling verbose logs while keeping error logs at full fidelity. The goal is that any trace you did keep has matching logs.

Common Pitfalls and Conclusion

Do not sample per service with independent random decisions, which fragments traces. Do not forget the probabilistic baseline, or you lose visibility into healthy traffic. Do not tail-sample without enough buffer, or you evict traces before deciding. Do not let sampling leak into metrics. And do not treat the sampling rate as fixed forever; review it as volume and cost change.

Sampling is a policy about what evidence to keep. Head sampling reduces volume cheaply; tail sampling keeps errors and slow traces that matter; consistent sampling by trace id keeps whole traces intact; and a probabilistic baseline preserves the ordinary case. Combine them deliberately and the trace dataset stays both affordable and diagnostically complete.

Sources: OpenTelemetry: Sampling, Tail sampling processor, OpenTelemetry: Trace State / propagation.

FAQ

Why is per-service percentage sampling wrong?
Because each service rolls independently, so a trace may be kept by one service and dropped by the next, producing partial traces with missing spans. Sampling must be a consistent decision by trace id, propagated downstream.
Can tail sampling keep all errors and all slow traces?
Yes, if the sampler sees every span of a trace, which requires trace-id load balancing, and has enough buffer to hold traces until they finish. Policies for error status and latency threshold then keep exactly those traces.

Related Examples