Tracing and Observability for AI Systems › Sampling: Tracing Without Going Broke

Michael BrenndoerferDecember 2, 20264 min read
Language AI HandbookAll chapters
Part 64 of 67Compound AI System Design
Chapter 488Tracing and Observability for AI Systems › Sampling: Tracing Without Going Broke
Reading section 6 of 10 · Sampling: Tracing Without Going Broke · 4 minSection 6 of 10 · 4 min

Section 6 of 10 · 4 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Tracing every request at full payload fidelity is expensive: storage for prompts and completions is large, and computing judge scores on every trace is costly. Sampling is the standard answer, but sampling strategy affects what conclusions you can draw, so state it explicitly. The main strategies:

  • Head-based sampling makes an early decision using information already available. The example below uses a fixed probability and can miss failures that happen after the decision.
  • Tail-based sampling decides after observing more of the trace, for example by keeping traces with recorded errors or high latencies. The decision uses spans received within the configured wait and capacity limits.
  • Stratified sampling: sample at different rates per route or tenant so small but important populations are represented.

A tail sampler downstream of a head drop cannot recover the traces that never reach it. To combine a traffic sample with additional diagnostic traces, mark the probability sample separately and give the tail policy access to the candidate stream before that drop. The tail policy can keep observed errors and slow requests, subject to incomplete exports, late spans, or capacity limits. Use the probability sample for traffic-wide estimates, with appropriate inclusion and labeling assumptions.

A quality average on retained traces describes the retained population. To estimate a traffic-wide average, use a probability sample with known positive inclusion probabilities for all eligible requests and account for missing evaluation labels. A tail policy that discards every ordinary successful request leaves no retained evidence about their quality.

PythonIn [23]
CollapseExpand
import hashlib


def head_sample(trace_id: str, rate: float) -> bool:
    """Deterministic head sampling by hashing the trace id."""
    if not 0.0 <= rate <= 1.0:
        raise ValueError("rate must be in [0, 1]")
    digest = hashlib.sha256(trace_id.encode("utf-8")).hexdigest()
    bucket = int(digest[:8], 16) / (1 << 32)  # uniform buckets in [0, 1)
    return bucket < rate


def tail_keep(trace: Trace, max_latency_ms: int = 1000) -> bool:
    """Keep traces that errored or exceeded a latency budget."""
    errored = any(s.status == "error" for s in trace.spans)
    slow = trace.root().duration_ms > max_latency_ms
    return errored or slow
ConsoleOut [24]
CollapseExpand
head_sample(trace-0001, 0.10): False
head_sample(trace-0002, 0.10): True
tail_keep(example_trace): True

The tail helper keeps the observed 1,420 ms trace because it exceeds the 1,000 ms budget. It can make this decision only if the trace reaches it. Deterministic head sampling by hashing the trace ID makes sampling reproducible and independent of arrival order, which matters when you re-run analysis. Identical inputs and sampler settings reproduce the decision. In a multi-service system, propagate the decision under the tracing policy, and expect partial traces if spans are lost or boundaries apply different settings.

In this deterministic fixture, raising the threshold preserves every ID already selected at a lower threshold and can add more. The realized fraction need not match the configured probability exactly.

PythonIn [25]
CollapseExpand
sampling_ids = [f"simulation-{n:04d}" for n in range(600)]
sampling_rates = [n / 20 for n in range(21)]
actual_sampling_rates = [
    sum(head_sample(trace_id, rate) for trace_id in sampling_ids)
    / len(sampling_ids)
    for rate in sampling_rates
]
VisualizationOut [26]
CollapseExpand
The observed sampling curve stays near the diagonal reference line.
Observed head-sampling fraction versus configured rate for 600 fictional request IDs. The diagonal shows equality between realized and configured rates. This fixed collection of IDs illustrates the sampler and does not measure representativeness in deployed traffic.
Sampling bias is an evaluation assumption

If you compute a metric only over sampled traces, report the sampling scheme and rate alongside the metric. A quality number computed over tail-sampled (error-biased) traces is not an estimate of overall quality; it is an estimate of quality conditional on the tail condition.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy