Head sampling decides before a trace exists: the SDK hashes the trace ID, applies traceidratio, and discards 90% of traces at the very first span — including the one that took eleven seconds and returned a 500. Tail sampling moves the decision to the end, once every span has arrived and the latency and status codes are visible. That is the only mechanism that can express “keep all errors, keep everything slower than 2s, keep 1% of the boring remainder.” The cost is architectural: the tail_sampling processor buffers whole traces in memory, so every span of a given trace must reach the same collector process. This guide builds the two-tier layout that makes that true — stateless agent collectors routing by trace ID into a stateful sampling tier — and gives you working YAML for both.
What you’ll accomplish
- Replace SDK-side ratio sampling with a policy set that keeps errors, slow requests and a small random baseline.
- Stand up the agent tier and the sampling-gateway tier, with a
loadbalancingexporter guaranteeing trace affinity. - Size
decision_wait,num_tracesandmemory_limiteragainst your real trace volume instead of copying a blog default. - Compose policies with
andandcompositeso you stop keeping ten times more than you intended. - Read the processor’s own metrics to confirm what is being kept, what is being dropped, and what is being evicted too early.
Prerequisites
- The
otelcol-contribdistribution.tail_samplingandloadbalancingare not in the coreotelcolbinary. Runningotelcolwith atail_samplingblock gives youerror decoding 'processors': unknown type: "tail_sampling"and the process exits. Use the contrib image (otel/opentelemetry-collector-contrib) or a custom build made with the OpenTelemetry Collector Builder that includes both components. - A trace backend that accepts OTLP — Tempo, Jaeger, or a vendor endpoint. If you do not have one yet, the Kubernetes observability stack guide stands up Tempo alongside Prometheus, Grafana and Loki.
- Services actually instrumented and emitting complete traces. Tail sampling on a partially instrumented system will look broken, because it is seeing partial traces.
- Somewhere to run two collector tiers. Examples below are Kubernetes; the same split works on VMs, and the single-tier gateway build is covered in deploying the collector in gateway mode.
- Prometheus scraping the collectors’ own
:8888metrics endpoint. Without it you are tuning blind.
How it works
The processor keeps a map of trace ID to buffered spans. When the first span of a new trace arrives it starts a timer of decision_wait. Spans that arrive before the timer expires join the buffer. When the timer expires, the processor evaluates every configured policy against the accumulated spans, and a single “keep” verdict sends the whole trace downstream. Everything else is freed.
That design has one non-negotiable consequence: a trace split across two collector instances produces two independent, wrong decisions on two half-traces. Neither instance can see the error span the other one holds. So the agent tier must never fan spans out randomly — it has to hash on trace ID.
The loadbalancing exporter does exactly that. With routing_key: traceID it hashes each trace ID onto a ring of backend endpoints discovered by a resolver, and every span carrying that trace ID goes to the same endpoint. The agent tier stays stateless and scales like any Deployment. The sampling tier does not: changing its replica count reshuffles the ring, and traces in flight at that moment get split. Treat scaling it as a planned, stateful operation, not something an HPA does at 3 a.m. on a CPU spike.
The second thing worth internalising is the decision timeline, because it explains most surprises.
Policies are OR-ed. Every policy is evaluated independently, and the first one that says “sampled” keeps the trace. There is no implicit AND, no priority order, no “the last one wins.” If you want “slow and on the checkout route,” that is a type: and policy with sub-policies, not two entries in the list.
Step-by-step
1. Turn head sampling off (or nearly off) in the SDKs. Tail sampling can only see traces that were exported in the first place. If the SDK is dropping 90% at the source, the collector never gets the chance to keep your errors.
export OTEL_TRACES_SAMPLER=parentbased_always_on
export OTEL_EXPORTER_OTLP_ENDPOINT=http://$(NODE_IP):4318
# No output; verify by watching span volume rise at the agent tier
If full volume is genuinely unaffordable on the wire, keep a generous head sample — parentbased_traceidratio at 0.5 — rather than 0.01. You cannot recover what the SDK never sent.
2. Deploy the agent tier with the loadbalancing exporter. One collector per node, no sampling, no state.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 400
spike_limit_mib: 100
batch:
timeout: 1s
send_batch_size: 1024
exporters:
loadbalancing:
# Hash on trace ID so all spans of a trace reach one gateway.
routing_key: traceID
protocol:
otlp:
timeout: 10s
tls:
insecure: true
resolver:
k8s:
service: otel-sampler.observability
ports:
- 4317
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [loadbalancing]
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
routing_key: traceID is the default, but write it down anyway — the day someone sets service to shard by service name is the day traces start arriving in halves.
3. Give the agents permission to resolve the gateway endpoints. The k8s resolver reads Endpoints, so the agent ServiceAccount needs RBAC for them.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: otel-agent-endpoints
rules:
- apiGroups: [""]
resources: ["endpoints"]
verbs: ["get", "list", "watch"]
kubectl apply -f otel-agent-rbac.yaml
clusterrole.rbac.authorization.k8s.io/otel-agent-endpoints created
On VMs, swap the resolver for dns with a hostname that resolves to all gateway addresses, and an interval that matches how often that record changes.
4. Configure the sampling gateway tier. This is where the state lives.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
processors:
memory_limiter:
check_interval: 1s
limit_mib: 3500
spike_limit_mib: 500
tail_sampling:
# Must exceed the p99 duration of your longest real trace.
decision_wait: 30s
num_traces: 200000
expected_new_traces_per_sec: 2000
policies:
- name: keep-all-errors
type: status_code
status_code:
status_codes: [ERROR]
- name: keep-slow-traces
type: latency
latency:
threshold_ms: 2000
- name: keep-slow-checkout
type: and
and:
and_sub_policy:
- name: route-is-checkout
type: string_attribute
string_attribute:
key: http.route
values: [/api/checkout]
- name: over-800ms
type: latency
latency:
threshold_ms: 800
- name: keep-large-carts
type: numeric_attribute
numeric_attribute:
key: cart.item_count
min_value: 50
max_value: 100000
- name: baseline-sample
type: probabilistic
probabilistic:
sampling_percentage: 1
batch:
timeout: 5s
send_batch_size: 1024
exporters:
otlp/tempo:
endpoint: tempo-distributor.observability:4317
tls:
insecure: true
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, tail_sampling, batch]
exporters: [otlp/tempo]
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
Order matters in that pipeline. memory_limiter first so it can refuse data before the buffer grows; tail_sampling next; batch last, so you batch only what survived.
5. Size the memory before you deploy it. The buffer is num_traces slots, and each slot holds the spans of one trace. A rough working figure is 1–2 KB per span, so a 20-span trace is roughly 30 KB.
200000 traces x 30 KB ≈ 6 GB
That is far more than limit_mib: 3500 allows, so either drop num_traces to 100000 or give the pod 8 GB. num_traces is a hard cap on the buffer, not a hint: once it is full, the oldest traces are evicted before their timer fires and get a decision on partial data. expected_new_traces_per_sec pre-allocates the internal maps; set it near your real rate to avoid churn, and remember num_traces should comfortably exceed expected_new_traces_per_sec × decision_wait.
6. Run the gateway tier as a StatefulSet with a slow shutdown. A pod that dies instantly takes its whole buffer with it.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: otel-sampler
namespace: observability
spec:
serviceName: otel-sampler
replicas: 3
selector:
matchLabels:
app: otel-sampler
template:
metadata:
labels:
app: otel-sampler
spec:
# Longer than decision_wait so in-flight traces still get decided.
terminationGracePeriodSeconds: 60
containers:
- name: collector
image: otel/opentelemetry-collector-contrib:0.130.0
args: ["--config=/conf/collector.yaml"]
ports:
- containerPort: 4317
- containerPort: 8888
resources:
requests:
cpu: "2"
memory: 8Gi
limits:
memory: 8Gi
7. Cap total volume with composite if the OR is keeping too much. A bare rate_limiting policy sitting alongside the others is another OR branch — it adds traces up to its rate rather than capping anything. The ceiling you actually want is composite:
tail_sampling:
decision_wait: 30s
num_traces: 100000
expected_new_traces_per_sec: 2000
policies:
- name: capped
type: composite
composite:
max_total_spans_per_second: 1500
policy_order: [keep-all-errors, keep-slow-traces, baseline-sample]
composite_sub_policy:
- name: keep-all-errors
type: status_code
status_code:
status_codes: [ERROR]
- name: keep-slow-traces
type: latency
latency:
threshold_ms: 2000
- name: baseline-sample
type: probabilistic
probabilistic:
sampling_percentage: 1
rate_allocation:
- policy: keep-all-errors
percent: 50
- policy: keep-slow-traces
percent: 30
- policy: baseline-sample
percent: 20
policy_order is the priority: when the budget runs out, the policies listed last are the ones starved.
Validate it works
Start with the processor’s own counters on any gateway pod:
kubectl -n observability exec otel-sampler-0 -- \
curl -s localhost:8888/metrics | grep tail_sampling
otelcol_processor_tail_sampling_count_traces_sampled{policy="keep-all-errors",sampled="true"} 412
otelcol_processor_tail_sampling_count_traces_sampled{policy="keep-slow-traces",sampled="true"} 96
otelcol_processor_tail_sampling_count_traces_sampled{policy="baseline-sample",sampled="false"} 38791
otelcol_processor_tail_sampling_sampling_traces_on_memory 8134
otelcol_processor_tail_sampling_new_trace_id_received 39412
otelcol_processor_tail_sampling_sampling_trace_dropped_too_early 0
Three readings matter. sampling_trace_dropped_too_early must stay at zero — anything above it means num_traces is too small and traces are being judged before their timer fires. sampling_traces_on_memory is your live buffer occupancy; if it sits near num_traces, you are one traffic spike away from eviction. And the ratio of count_traces_sampled with sampled="true" to new_trace_id_received is your actual keep rate.
Now prove the policies. Generate a request that should be kept:
curl -s -o /dev/null -w '%{http_code} %{time_total}s\n' \
'https://shop.example.com/api/checkout?fail=1'
500 0.412s
Wait longer than decision_wait, then search the backend for it. In Tempo the TraceQL is { status = error }; in Jaeger, filter the service by error=true. The trace should be there, complete, with every span present — that completeness is the real proof that trace affinity is working.
Then prove a boring trace was dropped. Fire a hundred fast, successful requests, note one trace ID from the response headers, wait out decision_wait plus the batch timeout, and look it up directly:
curl -s "http://tempo-query.observability:3200/api/traces/$TRACE_ID" | head -c 200
trace not found
With sampling_percentage: 1, roughly one in a hundred of those will be found anyway. That is the baseline policy doing its job, not a bug.
Troubleshooting
Traces in the backend are missing spans. This is the signature failure, and it always means spans of one trace reached different gateways. Check that the agents export through loadbalancing and not directly to the gateway Service — a plain otlp exporter pointed at a ClusterIP round-robins per connection and shreds traces. Check routing_key is traceID. Check the resolver actually lists all gateway pods: if RBAC on Endpoints is missing, the exporter falls back to whatever it can see and re-hashes when that changes. Also look for services exporting straight to the gateway tier, bypassing the agents entirely.
Memory climbs until the pod is OOMKilled. num_traces × average trace size exceeded the limit. Either lower num_traces, raise the memory request, or reduce decision_wait so traces leave the buffer sooner. Confirm memory_limiter is the first processor — behind tail_sampling it protects nothing. Watch otelcol_processor_refused_spans on the gateway: a rising count is memory_limiter doing its job and telling you the tier is undersized.
Long traces get sampled on partial data. If decision_wait is 5s and a batch job produces traces lasting 40s, the decision fires while spans are still arriving, and late spans of an already-dropped trace are discarded outright. Set decision_wait above the p99 duration of your longest realistic trace, then re-check the memory arithmetic, because a longer wait means a bigger buffer. Traces that genuinely last minutes do not belong in this pipeline at all.
You are keeping far more than expected. Almost always the OR semantics. status_code plus latency plus probabilistic plus string_attribute keeps the union of all four, not the intersection. Read the per-policy count_traces_sampled{sampled="true"} counters to see which one is loose — a latency threshold below your median response time keeps everything. Collapse the conditions you meant to combine into a single type: and policy, and put a composite ceiling around the whole set.
The collector will not start: unknown type “tail_sampling”. You are on the core distribution. Switch the image to otel/opentelemetry-collector-contrib, or rebuild with the builder including tailsamplingprocessor and loadbalancingexporter. The same error with loadbalancing under exporters has the same cause.
When this is the wrong approach
- Low trace volume. Under a few hundred traces per second, keeping everything is cheaper than running and operating a second collector tier. Sample when storage or egress actually hurts, not before.
- Your backend already samples at ingest. Several commercial trace backends run their own tail-based sampling on the receiving side. Doing it twice compounds the ratios, and the vendor’s view of “kept” stops matching yours.
- You need exact counts. Sampled traces are useless for measuring request rates or error percentages. Derive those from span metrics — the
spanmetricsconnector generates RED metrics before sampling — and use traces only for looking at individual requests. - Nobody owns the gateway tier. It is stateful, memory-hungry, and cannot be autoscaled casually. If there is no one to resize it when traffic doubles, a head sample at a fixed ratio is the less fragile choice.
- Traces that span minutes. Long-running workflows do not fit a
decision_waitwindow. Instrument them as linked shorter traces, or accept head sampling for that specific service.
The reference material worth having open is the OpenTelemetry Collector documentation and the sampling concepts page, which covers the head-versus-tail trade-off in the vendor-neutral terms the processor config assumes.
If alerts fire into an empty room after hours, that’s exactly what 24/7 Monitoring & Response closes — book a monitoring and response review.