Tail-Based Sampling: Buying the Decision Back with RAM

The Inversion

Sample nothing at the source. Export 100% of spans. Buffer every span of every trace in a collector's heap, keyed by trace ID, and start a timer. When the timer fires, run policies against the assembled trace and then decide. You now get to condition on facts that did not exist when the Head-Based Sampling part's root sampler was asked:

Statusany span in the trace has ERROR
Durationearliest start → latest end > 2 s
Shapetrace has > 200 spans (an N+1 loop)
Identityenduser.id = the customer who complained

The Head-Based Sampling table is now irrelevant: a failure occurring three times an hour is captured three times an hour, because the policy sees the error. That is the whole prize, and everything below is the invoice.

The Completeness Problem — the Load-Bearing Difficulty

From see The Trace: no span says "I am last." There is no field, no count, no terminator. A trace is a set of spans that happens to share an ID, and the only way to know the set is complete is to stop receiving new members — which is indistinguishable from a slow network. So the decision cannot be triggered by a signal. It is triggered by a timer.

In the collector's tail_sampling processor, that timer is decision_wait, default 30s (verified in factory.go: DecisionWait: 30 * time.Second). A newer option, decision_wait_after_root_received (default 0s, disabled), lets you cut the wait short once the root span arrives — the root normally ends last, so its arrival is the best available "probably complete" heuristic — though an async child can and does outlive it, which is where the late spans below come from. Honeycomb's Refinery has the same pair under different names: Traces.TraceTimeout (default 60s) and Traces.SendDelay (default 2s after the root arrives).

first span of trace X arrives
│
├──────────────── decision_wait = 30s ────────────────┤
│                                                     │
▼                                                     ▼
t=0s        t=4s      t=11s                        t=30s          t=34s
│           │         │                            │              │
span A      span B    root span ends               TIMER FIRES    span C
(child)     (child)   ├─ decision_wait_after_      evaluate       (async
                      │  root_received = 5s        policies on    retry)
                      └─ short-circuits to t=16s   A,B,root       ← LATE
                                                                    span

  at t=16s or t=30s: keep-or-drop, trace freed from the heap
  at t=34s: span C's fate depends entirely on decision_cache
            cache hit  → inherits the verdict
            cache miss → starts a NEW 30s buffer entry, decided ALONE

Every operational property of tail sampling falls out of that timer:

  1. It adds decision_wait of latency before a trace is queryable. At the default, a trace that completed at 14:03:00 cannot be searched for until 14:03:30, plus export and ingest. During an incident, thirty seconds of "the trace isn't there yet" is indistinguishable from "tracing is broken," and people start restarting collectors — which, per the restart note below, makes it worse.

  2. Late spans get one of three fates. A span is "late" if it arrives after its trace's decision was made. (1) While the decided trace is still in the num_traces circular buffer, the late span inherits the decision — and, importantly, does not influence it. (2) Default, no decision cache: once evicted, the processor has no memory of the trace, so the late span starts a brand-new buffer entry and waits another full decision_wait, then gets decided on its own — a fragment judged in isolation. (3) With decision_cache.sampled_cache_size / non_sampled_cache_size set (both default 0, i.e. inactive), trace IDs are remembered in an LRU after the span data is freed, and the late span rejoins the original verdict. Configure these much larger than num_traces; the metric otelcol_processor_tail_sampling_sampling_late_span_age tells you how much lateness you actually have.

  3. The timer must exceed your longest realistic trace — and your longest traces are the ones you are trying to catch. This is the vicious part. Set decision_wait to 10s to halve your memory bill and every trace slower than 10 seconds gets decided on a prefix: the latency policy measures earliest-start to latest-end of what has arrived, so a 14-second trace looks like a 9-second trace, may fall under your threshold entirely, and even if kept arrives missing its tail — which is exactly where the stall was.

The Memory Math

buffered_bytes ≈ span_rate × decision_wait × bytes_per_span
num_traces_required ≈ trace_rate × decision_wait

Central Question numbers: 10,000 req/s × 40 spans = 400,000 spans/s, at ~700 bytes per OTLP-encoded span (the What It Costs part derives that figure).

decision_waitSpans residentBytes residentnum_traces needed at 10k traces/s
5 s2.0 M1.4 GB50,000  = the default, exactly
10 s4.0 M2.8 GB100,000
30 s (default)12.0 M8.4 GB300,000
60 s24.0 M16.8 GB600,000
120 s48.0 M33.6 GB1,200,000

8.4 GB, held continuously, spread across the tail tier — and that is the wire size. The in-heap pdata representation, with per-attribute maps and Go slice headers, is meaningfully larger; a 2-3× multiplier is the usual planning rule (reasoned from the data structures, not a published figure). Budget accordingly.

num_traces (default 50,000) is a hard cap on in-flight traces, enforced by a circular buffer: "When a new trace arrives, the oldest trace is removed. This can cause a trace to be dropped before it's sampled." Look at the last column. The two defaults are only mutually consistent below ~1,667 traces/s. At 10,000 traces/s the default buffer holds 5 seconds of traffic while the timer waits 30 — so 83% of traces are evicted before anyone ever evaluates a policy on them.

The Routing Prerequisite, and Why Scaling Is Dangerous

The README states the constraint flatly: "All spans for a given trace MUST be received by the same collector instance for effective sampling decisions." This is the Collector's mismatch in its purest form — the data model is a graph, the transport is a per-span stream, and buffering the graph requires forcing every edge of it onto one heap. Hence two tiers: a stateless first tier running only the loadbalancing exporter (routing_key: traceID, which is already the default for traces) hashing each span onto a backend, and a stateful second tier running tail_sampling. The docs recommend separating the layers rather than co-locating the pipelines, for failure isolation.

Two tiers: stateless hashing in front, a timer and a heap behind
Two tiers: stateless hashing in front, a timer and a heap behind

The rebalancing problem is the one that surprises people, because the tier looks stateless — it's a collector, it has no disk, Kubernetes will happily give it an HPA. But when tier 2 scales from 6 replicas to 8, the hash ring changes, and every trace currently mid-flight gets its remaining spans routed to a different instance than its first spans. Each instance now holds a fragment. Each fragment independently waits decision_wait and is judged alone: the fragment containing the error is kept, the fragment containing the root and the first 30 spans is dropped, and you get a trace in your UI that starts at span 31 with no context. Honeycomb says this about Refinery in as many words: "Refinery is a stateful service and is not optimized for dynamic auto-scaling. Changes in cluster membership can temporarily cause inconsistent sampling decisions or dropped traces," and recommends vertical scaling and provisioning for peak over autoscaling. The same reasoning applies to the collector's tail tier. Treat it like a database: scale it deliberately, roll it slowly, one pod at a time with a drain longer than decision_wait.

Policies

The real policy types in tail_sampling: always_sample, latency, numeric_attribute, probabilistic, status_code, string_attribute, trace_state, trace_flags, rate_limiting, bytes_limiting, span_count, boolean_attribute, ottl_condition, plus the combinators and, not, drop and composite. (The old invert_match "inverted decision" mechanism is deprecated in favour of not and drop.) Evaluation is OR-by-default across the top-level list — any policy voting sample wins — except that a drop decision is absolute and beats everything.

processors:
  tail_sampling:
    decision_wait: 30s                    # MUST exceed p99.9 trace duration
    decision_wait_after_root_received: 5s  # short-circuit the fast common case
    num_traces: 300000                    # = trace_rate x decision_wait
    expected_new_traces_per_sec: 10000    # pre-sizes the maps
    decision_cache:
      sampled_cache_size: 3000000         # >> num_traces, for late spans
      non_sampled_cache_size: 3000000
    policies:
      - name: drop-health-checks          # evaluated first; drop beats everything
        type: drop
        drop:
          drop_sub_policy:
            - name: healthz
              type: ottl_condition
              ottl_condition:
                error_mode: ignore
                span: ['span.name == "GET /healthz"']

      - name: all-errors                  # 100% of anything that failed
        type: status_code
        status_code: {status_codes: [ERROR]}

      - name: slow-traces                 # 100% of anything over 2s
        type: latency
        latency: {threshold_ms: 2000}

      - name: n-plus-one                  # pathological fan-out
        type: span_count
        span_count: {min_spans: 200}

      - name: baseline                    # a readable slice of "normal"
        type: probabilistic
        probabilistic: {sampling_percentage: 5}

      - name: global-guard                # THE ONE PEOPLE OMIT
        type: rate_limiting
        rate_limiting: {spans_per_second: 20000, burst_capacity: 40000}

What Tail Sampling Does Not Save, and What It Cannot Do

Costs it does not remove

Span creation and attribute-building CPU in the app. Serialization. App→collector network bytes — 100% of them, cross-AZ if your collector isn't node-local. Tier-1 collector CPU, which now sees every span. The tier-2 heap. You moved all the data and stored 5% of it.

What it does cut is backend ingest and storage — typically the dominant line item by an order of magnitude (see What It Costs), which is why it is worth doing anyway. But say the split out loud when someone claims "tail sampling cut our tracing cost 95%."

Things it structurally cannot do

Cross-region traces. Buffering requires every span on one heap; a trace spanning two regions means shipping one region's spans to the other, and cross-region egress is the expensive network there is. In practice you tail-sample per region and accept that cross-region traces are decided on a regional fragment.

Survive a restart cleanly. Refinery flushes in-flight traces upstream on shutdown but loses its record of past decisions, so post-restart late spans get fresh verdicts. The collector's default is the opposite: it makes a decision on the partial data already ingested (set drop_pending_traces_on_shutdown: true to discard instead). Either way a restart produces a cohort of traces judged on fragments.

Condition on facts outside the trace. "This user filed a ticket an hour later" is not a span attribute. No policy can see it.

The Decision Table

Head only (1%)Tail onlyHybridNo sampling + aggregate-first
Where cost is cutAt the source — app CPU, all network, ingest, storageBackend ingest + storage onlySource cuts the flood; tail curates the restNothing is cut; you pay full ingest
Latency to queryableExport delay only (~seconds)+ decision_wait (30 s default)+ decision_wait on the tail pathExport delay only
Statistical soundnessSound if the rate is propagated; otherwise counts are wrong by an unknown factorDeliberately biased toward errors — never count from itSame caveat, two rates to trackExact
Captures a 3/hr failure3% of the timealwaysalwaysalways
Operational complexityOne env varTwo tiers, hash routing, careful rolloutsTwo tiers + per-service rate configNone in the pipeline; all of it in storage (see Trace Storage)
Memory held~0span_rate × wait × bytes — GBsSame formula, smaller span_rate~0
Failure modeYou silently have no evidenceOOM, silent eviction, split traces on rescale, bill spike under outageBoth, attenuatedStorage cost and index explosion

The user's conclusion is right and needs one qualification. Tail-based sampling does produce a far more useful corpus — 100% of errors plus a readable slice of normal, instead of a uniform sample of mostly-boring. But it is not free and it is not a drop-in: it costs a stateful tier you must scale like a database, single-digit GBs of resident RAM per 400k spans/s, decision_wait seconds of blindness during incidents, and a genuinely new failure mode where an in-flight trace splits across two deciders. For most teams the honest recommendation is the hybrid: head-sample at a generous rate to knock the flood down at the source where it is cheapest to cut, then tail-sample the survivors so the corpus is curated rather than uniform.

  • Guarantees: A sampling decision informed by the whole trace — its status, its total duration, its span count, any attribute on any span — and therefore near-certain capture of rare failures that head sampling loses with ~97% probability per incident hour.
  • Does not guarantee: That the trace it decided on was complete. The "trace" is whatever arrived before a timer expired on one collector instance, and a slow span, a rescale, a restart, or a full num_traces buffer each silently reduce it to a fragment — with the decision still being made, and made confidently.