Head-Based Sampling: Deciding Before Anything Has Happened
Where the Decision Happens, and Why It Is Irreversible
A Sampler is consulted exactly once per span, inside Tracer.Start(), before the span object exists in a usable form. For the root span — the one with no incoming traceparent — the sampler has almost nothing to work with: the trace ID, the span name, the initial attribute set, the span kind, and the links. It does not have the duration (the span has not run), the status (nothing has failed yet), or the HTTP response code (no response exists). It is being asked "is this request interesting?" at the only moment in the request's life when that question is unanswerable.
Whatever it answers gets written into one bit on the wire and then travels (see Context Propagation):
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
│ └┬┘
version trace-flags
bit 0 0x01 sampled set by the ROOT sampler; every downstream honors it
bit 1 0x02 random-trace-id asserts the rightmost 7 bytes of trace-id are
uniformly random over [0, 2^56-1] (trace-context L2)
bits 2-7 reserved MUST be propagated unchanged, MUST NOT be interpreted
00 = not sampled 01 = sampled
02 = not sampled, random 03 = sampled, randomEvery downstream SDK runs ParentBased, which is not itself a sampler but a five-way dispatcher. Its root delegate is required; the other four have defaults that exist precisely to make the bit binding:
ParentBased delegate | Fires when | Default |
|---|---|---|
root | No parent context — this is the trace's first span | required, no default |
remoteParentSampled | Parent came over the wire with sampled set | AlwaysOn |
remoteParentNotSampled | Parent came over the wire with sampled clear | AlwaysOff |
localParentSampled | Parent is an in-process span that was sampled | AlwaysOn |
localParentNotSampled | Parent is an in-process span that was not sampled | AlwaysOff |
Read those four defaults as a sentence: obey the parent, unconditionally, in both directions. That is what makes a head decision irreversible — service 19 cannot promote a trace it has decided is interesting, because its sampler was never asked; remoteParentNotSampled already answered AlwaysOff.
The composition is selected by two environment variables, spec-defined and honored identically by every SDK:
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.01 # probability in [0..1], default 1.0
# accepted values for OTEL_TRACES_SAMPLER:
# always_on always_off traceidratio
# parentbased_always_on <-- THE SPEC DEFAULT: samples 100%
# parentbased_always_off parentbased_traceidratio
# jaeger_remote parentbased_jaeger_remote xrayWhy It Must Be Deterministic on the Trace ID
The naive implementation — each service flips its own coin at rate p — fails in a way worth computing, because the failure is not "slightly lossy," it is total.
P(complete trace of N spans) = pN | P(at least one span kept) = 1 − (1−p)N
For a 23-service checkout producing N = 40 spans at p = 0.01: 0.01^40 = 10^-80 complete traces. That is not a small number, it is zero — fewer than the atoms in the observable universe. Meanwhile 1 − 0.99^40 = 0.331, so 33% of all traces produce at least one orphan span. At 10,000 req/s that is ~3,300 traces per second that exist in your backend as a single disconnected span with a parent_span_id pointing at nothing — the orphan-span pathology of the Trace part, manufactured at industrial scale — and essentially zero traces you can actually read.
TraceIdRatioBased deletes this by making the decision a pure function of a value every participant already has. The spec is explicit: "The sampling algorithm MUST be deterministic. A trace identified by a given TraceId is sampled or not independent of language, time, etc." and it must use a deterministic hash of the trace ID. Twenty-three services, five languages, four continents, zero coordination — same input, same answer. This property has a name: consistent sampling.
Dapper shipped exactly this in 2010 for its second-stage collection sampler: "For each span seen in the collection system, we hash the associated trace id as a scalar z, where 0 ≤ z ≤ 1. If z is less than our collection sampling coefficient, we keep the span… By depending on the trace id for our sampling decision, we either sample or discard entire traces rather than individual spans within traces."
The Three Decisions, and the One People Forget
SamplingDecision | IsRecording() | sampled flag | Reaches SpanProcessors | Reaches exporters |
|---|---|---|---|---|
DROP | false | not set | no | no |
RECORD_ONLY | true | MUST NOT be set | yes | no |
RECORD_AND_SAMPLE | true | MUST be set | yes | yes |
DROP is not merely "don't export" — it makes the span a no-op object: IsRecording() returns false, and every attribute, event and exception your instrumentation sets on it is discarded at the call site. That is the mechanism that makes head sampling genuinely cheap in the process (below), and it is also why an expensive attribute value should be computed behind an if span.IsRecording() guard.
RECORD_ONLY is the strange and useful one: the span is fully constructed and handed to every registered SpanProcessor, but the sampled bit stays clear so nothing is exported. This is how you compute request-rate, error-rate and latency-histogram metrics over 100% of spans while exporting 1% of them — the aggregate is derived in-process from a complete population, and only the individual exemplars are sampled. The What It Costs part owns the economics; the point here is that it is the sampler, not the exporter, that draws that line.
The Arithmetic That Answers the Question
Take the guide's Central Question literally. 10,000 req/s. 0.1% of requests are pathologically slow. That is 10 genuinely interesting requests per second — 36,000 per hour. At 1% head sampling you keep 0.1/s, or 360 per hour. Survivable. If the story ended there, head sampling would be fine, and Dapper's argument would hold: "if a notable execution pattern surfaces once in such systems, it will surface thousands of times."
But that is not the shape of a real incident. A real incident is: one customer, one endpoint, one code path, five times an hour. Now do the arithmetic.
P(nothing captured in a window W) = (1 − p)r·W
mean time to first captured occurrence = 1 / (p · r)
| Occurrences / hr (r) | Rate (p) | Kept / hr | Mean wait for one | P(zero captured in the 1 h you are paged) |
|---|---|---|---|---|
| 3 | 1% | 0.03 | 33 hours | 97.0% |
| 3 | 10% | 0.3 | 3 h 20 m | 72.9% |
| 10 | 1% | 0.1 | 10 hours | 90.4% |
| 10 | 10% | 1.0 | 1 hour | 34.9% |
| 60 (one a minute) | 1% | 0.6 | 1 h 40 m | 54.7% |
| 60 | 10% | 6.0 | 10 min | 0.18% |
| 600 | 1% | 6.0 | 10 min | 0.24% |
| 36,000 (whole 0.1% tail) | 1% | 360 | 10 s | ~0 |
Read the first row again. A failure occurring three times an hour, under 1% head sampling, leaves you with nothing to look at 97% of the time during the hour you are paged for it. Over a full 24-hour investigation window at 5/hr — 120 occurrences — you catch at least one with probability 1 − 0.99^120 = 70%. A 30% chance of a full day of investigation with zero evidence, and no signal anywhere telling you the evidence was discarded rather than absent.
Normal traces are abundant and nearly interchangeable: the 500,000th successful checkout trace teaches you nothing you did not learn from the 499,999th. Rare traces are the only ones carrying information. Head sampling is uniform — so it spends its entire budget on the category with no information content, and discards the category that holds all of it. That is not a tuning problem. It is what uniform means.
What Head Sampling Is Genuinely Good At
This is not a strawman, and the honest case for it is strong. Dapper measured it directly: tracing 1-in-1 requests cost 16.3% latency and 1.48% throughput on a web-search cluster; 1-in-1024 cost 0.20% latency and 0.06% throughput. Those numbers are the reason head sampling exists.
| Added latency | Zero — one hash, no buffering, no wait |
|---|---|
| Coordination | None — 23 services, no shared state |
| Cost predictability | Exactly p × traffic, always |
| Failure mode | Degrades to "less data," never to OOM |
Statistical Correctness: the Trap Everyone Walks Into
If you keep exactly 1%, you can still estimate population aggregates — weight each kept trace by 100. This is the adjusted count, and it is correct only while you actually know the rate. In practice you don't: the mobile SDK samples at 5%, the batch service at 0.1%, one team set a rate limiter, and a vendor agent applied its own second-stage sampling you never configured. The weights are now different per span and recorded nowhere.
OpenTelemetry's fix is consistent probability sampling — carry the rate in tracestate so it is machine-readable at the far end. The spec (currently at Development status; OTEP 235 and OTEP 250) defines an ot section with two sub-keys:
tracestate: ot=th:fd70a4;rv:c96a3bd2f5e841
th: rejection THRESHOLD, hex, no "0x", trailing zeros stripped
T = (1 − sampling_probability) × 2^56
p = 0.01 → 0.99 × 2^56 → th:fd70a4
rv: explicit 56-bit randomness value, used when the trace-id is
NOT known to be random (the 0x02 flag of §3 is clear)
keep if R >= T adjusted count = 2^56 / (2^56 − T) = 100Note what the threshold encoding buys you beyond bookkeeping: because a lower probability's threshold is strictly higher, sampling is monotone — every trace kept at 1% would also have been kept at 10%. A downstream stage can re-sample a 10% stream down to 1% and land on exactly the subset a 1% frontend would have chosen. That is what makes multi-stage sampling composable instead of multiplicative-and-unknowable.
Variants Beyond a Flat Ratio
| Variant | Mechanism | What it breaks / buys |
|---|---|---|
| Rate limiting (N traces/sec) | Leaky or token bucket per process | Bounds cost hard under a traffic spike — and destroys consistency: the decision now depends on that process's recent local traffic, not the trace ID, so two services disagree and you are back to fragments. Only safe at the root. |
| Per-operation rates | A rate table keyed by span name | Lets /healthz sample at 0 and /checkout at 10%. Still consistent if the root owns the decision. |
| Remote / adaptive | Sampler polls a control plane for per-service, per-operation rates; Jaeger computes them from observed traffic (see Jaeger Architecture) | Parameterized by traces per second per operation, not probability. Jaeger's no-config default is probabilistic 0.001. |
Adaptive sampling is underrated, and its benefit is precisely the one the flat-ratio arithmetic above exposes. A flat 1% gives a 50,000 req/s endpoint 500 traces/s and a 2 req/s endpoint one trace every 50 seconds — the rare endpoint, which is usually the interesting one, is drowned out by the loud one. Targeting traces per operation per second instead equalizes across operations: low-traffic endpoints float their rate up toward 100%, high-traffic ones sink. This is exactly why Dapper moved off uniform 1/1024 — "lower traffic workloads may miss important events at such low sampling rates, while tolerating higher sampling rates with acceptable performance overheads." It does not solve the rare-failure-on-a-busy-endpoint case in the table above, which is what the Tail-Based Sampling part is for.
- Guarantees: Every span of a kept trace is kept and every span of a dropped trace is dropped, with no coordination between services, no buffering, and no added latency — provided every participant uses a deterministic trace-ID sampler and honors
ParentBased. - Does not guarantee: That anything you care about is in the sample. The decision is uniform over requests and is made before any property that distinguishes an interesting request from a boring one is observable. It also does not guarantee that a count computed from the kept traces bears any fixed relationship to reality, unless the rate is propagated.