Sampling & Span Metrics
A service handling 2,000 requests per second with 10 spans each produces 1.7 billion spans a day. Storing all of them is expensive and mostly useless: thousands of identical fast redirects tell you nothing new. Sampling keeps a subset, and span metrics keep the counts and latencies of everything before sampling throws spans away.
Head sampling
The decision is made when the trace starts, in the first service, and travels downstream in the traceparent flags (-01 = sampled). Every later service follows the parent's decision (ParentBased sampler), so a trace is either complete or absent.
TraceIdRatioBased(0.1) keeps a trace when its trace ID, read as a number, falls below 10% of the ID space. Because the decision depends only on the trace ID, every service computes the same answer even without the flag, which is what makes it consistent. This model checks both properties on 100,000 random trace IDs:
import random
random.seed(2026)
RATIO = 0.10
LIMIT = int(RATIO * 2**56) # compare the lower 56 bits, like the OTel specification's "randomness" bits
def sampled(trace_id_hex):
return int(trace_id_hex[-14:], 16) < LIMIT
traces = [f"{random.getrandbits(128):032x}" for _ in range(100_000)]
kept = [t for t in traces if sampled(t)]
print(f"kept {len(kept)} of {len(traces)} traces ({len(kept) / len(traces):.2%})")
# three services decide independently from the same trace ID: always the same answer
disagreements = sum(len({sampled(t), sampled(t), sampled(t)}) > 1 for t in traces)
print("services disagreeing:", disagreements)
# but head sampling is blind to outcomes: errors are kept at the same 10%
errors = [t for t in traces if int(t[:2], 16) < 3] # ~1.2% of requests fail
print(f"errors: {len(errors)}, of which kept: {sum(sampled(t) for t in errors)}")kept 9894 of 100000 traces (9.89%)
services disagreeing: 0
errors: 1131, of which kept: 122
Head sampling is cheap and simple, and it reduces load everywhere (including the SDK's overhead). Its weakness is the last line: at the moment the trace starts, nobody knows whether the request will fail or be slow, so 90% of the interesting traces are dropped along with the boring ones.
Tail sampling
Tail sampling waits until a trace is complete (or a timeout passes), then decides with the whole trace in view: keep every trace with an error, every slow one, and a small percentage of the rest. It runs in the Collector's tail_sampling processor, which must see all spans of a trace (one gateway instance per trace, via a trace-ID-aware load balancer).
The session sends five single-span traces to a Collector: three fast, one slow (900 ms) and one failed. The tail-sampling pipeline keeps the slow and failed traces. In parallel, a second pipeline feeds all spans through the span_metrics connector, which turns them into request counts and latency histograms served on a Prometheus endpoint:
cat > otel.yaml <<'YML'
receivers:
otlp:
protocols:
http: {endpoint: 127.0.0.1:4318}
processors:
tail_sampling:
decision_wait: 1s # production: 10-30 s, the longest a trace takes to complete
policies:
- {name: errors, type: status_code, status_code: {status_codes: [ERROR]}}
- {name: slow, type: latency, latency: {threshold_ms: 500}}
# production: add {name: baseline, type: probabilistic, probabilistic: {sampling_percentage: 5}}
connectors:
span_metrics:
metrics_flush_interval: 1s
histogram:
explicit: {buckets: [100ms, 500ms, 2s]}
exporters:
file: {path: ./sampled.json}
prometheus: {endpoint: 127.0.0.1:8889}
service:
telemetry: {logs: {level: error}}
pipelines:
traces/all: # every span → metrics
receivers: [otlp]
exporters: [span_metrics]
traces/sampled: # only interesting traces → storage
receivers: [otlp]
processors: [tail_sampling]
exporters: [file]
metrics:
receivers: [span_metrics]
exporters: [prometheus]
YML
otelcol-contrib --config=otel.yaml >collector.log 2>&1 &
for i in $(seq 100); do curl -s -o /dev/null 127.0.0.1:4318/v1/traces && break; sleep 0.2; done
python3 - > spans.json <<'PY'
import json
def span(n, dur_ms, error=False):
s = {"traceId": f"{n:032x}", "spanId": f"{n:016x}", "name": "GET /{code}", "kind": 2,
"startTimeUnixNano": "1767261600000000000",
"endTimeUnixNano": str(1767261600000000000 + dur_ms * 1_000_000)}
if error:
s["status"] = {"code": 2} # STATUS_CODE_ERROR
return s
spans = [span(1, 12), span(2, 8), span(3, 900), span(4, 30, error=True), span(5, 15)]
print(json.dumps({"resourceSpans": [{
"resource": {"attributes": [{"key": "service.name", "value": {"stringValue": "linkly"}}]},
"scopeSpans": [{"spans": spans}]}]}))
PY
curl -s -H 'Content-Type: application/json' --data @spans.json 127.0.0.1:4318/v1/traces; echo
for i in $(seq 50); do
[ "$(jq -s '[.[].resourceSpans[].scopeSpans[].spans[]] | length' sampled.json 2>/dev/null)" = 2 ] && break; sleep 0.2
done
echo "--- kept by tail sampling:"
jq -c '.resourceSpans[].scopeSpans[].spans[] | {traceId: .traceId[-4:], status: (.status.code // 0)}' sampled.json | sort
for i in $(seq 50); do curl -s 127.0.0.1:8889/metrics | grep -q '^traces_span_metrics_calls_total' && break; sleep 0.2; done
echo "--- span metrics (all 5 requests), noisy labels removed:"
curl -s 127.0.0.1:8889/metrics | grep -E '^traces_span_metrics_(calls_total|duration_milliseconds_bucket)' |
sed -E 's/(collector_instance_id|job|otel_scope_name|otel_scope_schema_url|otel_scope_version|span_kind|span_name)="[^"]*",?//g' |
sort{"partialSuccess":{}}
--- kept by tail sampling:
{"traceId":"0003","status":0}
{"traceId":"0004","status":2}
--- span metrics (all 5 requests), noisy labels removed:
traces_span_metrics_calls_total{service_name="linkly",status_code="STATUS_CODE_ERROR"} 1
traces_span_metrics_calls_total{service_name="linkly",status_code="STATUS_CODE_UNSET"} 4
traces_span_metrics_duration_milliseconds_bucket{service_name="linkly",status_code="STATUS_CODE_ERROR",le="+Inf"} 1
traces_span_metrics_duration_milliseconds_bucket{service_name="linkly",status_code="STATUS_CODE_ERROR",le="100"} 1
traces_span_metrics_duration_milliseconds_bucket{service_name="linkly",status_code="STATUS_CODE_ERROR",le="2000"} 1
traces_span_metrics_duration_milliseconds_bucket{service_name="linkly",status_code="STATUS_CODE_ERROR",le="500"} 1
traces_span_metrics_duration_milliseconds_bucket{service_name="linkly",status_code="STATUS_CODE_UNSET",le="+Inf"} 4
traces_span_metrics_duration_milliseconds_bucket{service_name="linkly",status_code="STATUS_CODE_UNSET",le="100"} 3
traces_span_metrics_duration_milliseconds_bucket{service_name="linkly",status_code="STATUS_CODE_UNSET",le="2000"} 4
traces_span_metrics_duration_milliseconds_bucket{service_name="linkly",status_code="STATUS_CODE_UNSET",le="500"} 3
- Only traces 3 (slow) and 4 (error) were stored: 2 of 5. At real traffic levels with a small baseline percentage, tail sampling typically stores a few percent of traces while keeping nearly all the ones anyone will look at.
- The span metrics count all five requests, by status: 4 unset (OK) and 1 error, with a latency histogram (
lein milliseconds). That's RED from traces, computed before sampling, so dashboards stay accurate however aggressively you sample. Tempo's metrics-generator and Grafana Cloud do the same server-side. - The connector names its metrics
traces_span_metrics_*and addsservice_name,span_name,span_kindandstatus_codelabels; keep span names low-cardinality, or this becomes a cardinality problem.
Choosing
| Head | Tail | |
|---|---|---|
| decided | at the first span | after the trace completes |
| cost | lowest: unsampled spans are never even recorded | every span travels to the Collector and is held in memory for decision_wait |
| keeps errors and slow traces | only at the base rate | all of them (by policy) |
| complexity | an SDK setting | a stateful gateway tier with trace-ID load balancing |
Common setup: head sampling at a generous rate (or 100%) in the SDKs, tail sampling in a gateway, span metrics before the tail sampler. Always record the sampling rate on kept spans (the SDK sets it in tracestate) so backends can extrapolate counts.
Test yourself
Why can every service make the same TraceIdRatioBased decision independently?
- They share a database
- The decision is a function of the trace ID only
- The Collector tells them
- They use the same random seed
What is the main advantage of tail sampling?
- It's cheaper than head sampling
- It decides with the complete trace in view, so it can keep all errors and slow traces
- It needs no Collector
- It works without trace IDs
Why compute span metrics before the tail sampler?
- They're faster
- So request counts and latencies reflect all traffic, not just the sampled subset
- The connector requires it
- To reduce cardinality