Sub topic 17
Sampling and cost control
This chapter assumes you can already create spans in Python, run an OpenTelemetry Collector, and read a trace tree. It covers how to keep trace volume and cost down without losing the traces you need for debugging.
Why LLM traces cost more than ordinary traces
A web request trace usually has a few dozen small spans. An agent run can have hundreds. Each loop iteration adds a model call, one or more tool calls, and sometimes a retrieval. If you capture prompts and responses, each span can also carry kilobytes of text.
Cost comes from three places:
- The number of traces you export.
- The number of spans in each trace, which grows with agent loop length.
- The size of each span, mostly from prompt and response content.
Sampling addresses the first. Span limits and content settings address the other two.
Head sampling
Head sampling decides at the start of a trace, before any child span exists. The decision depends only on information available then, such as the trace ID. It is cheap, because unsampled traces never leave the process.
The usual setup is ParentBased wrapped around a ratio sampler:
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
resource = Resource.create({"service.name": "support-agent"})
sampler = ParentBased(root=TraceIdRatioBased(0.1)) # keep about 10% of new traces
provider = TracerProvider(resource=resource, sampler=sampler)
trace.set_tracer_provider(provider)TraceIdRatioBased(0.1) derives its decision from the trace ID, so every service that uses the same ratio makes the same choice for the same trace. ParentBased makes a span follow its parent's decision. Only root spans go through the ratio sampler. Without ParentBased, each service in a call chain could sample independently, and you would get traces with missing pieces.
You can set the same thing with environment variables, with no code change:
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1The limit of head sampling
At the start of a trace you don't yet know whether the run will fail, loop 30 times, or take 40 seconds. A 10% head sampler drops 90% of your failures along with the successes. For LLM apps, where the interesting traces are the rare bad ones, this is a real problem.
Tail sampling
Tail sampling decides after the trace is complete, so it can use the outcome. The Collector's tail_sampling processor does this. It buffers spans in memory, groups them by trace ID, waits for decision_wait, then applies policies.
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 1024
tail_sampling:
decision_wait: 30s
num_traces: 50000
policies:
- name: keep-errors
type: status_code
status_code:
status_codes: [ERROR]
- name: keep-slow
type: latency
latency:
threshold_ms: 10000
- name: sample-the-rest
type: probabilistic
probabilistic:
sampling_percentage: 5
batch: {}
exporters:
otlphttp:
endpoint: https://traces.example.com:4318
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, tail_sampling, batch]
exporters: [otlphttp]A trace is kept if any policy matches. This configuration keeps every trace with an error span, every trace slower than 10 seconds, and 5% of everything else. The tail_sampling processor ships in the Collector contrib distribution, not the core one.
The latency policy measures the whole trace duration, so a slow agent run is caught even if no single span is slow.
Gotchas with tail sampling
- All spans of a trace must reach the same Collector instance. If you run several replicas behind a plain load balancer, the spans of one trace get split and each replica decides on a fragment. Put a first tier of Collectors with the
loadbalancingexporter, keyed by trace ID, in front of a second tier that does the sampling. - Memory grows with
decision_waitand traffic. Long agent runs need a longer wait. A run that outlastsdecision_waitgets evaluated on partial data. Size the wait to your longest normal run, and usememory_limiterfirst in the pipeline. - Late spans are lost or orphaned. Spans that arrive after the decision are handled on their own, not as part of the trace decision.
- Head and tail sampling don't combine for free. If the SDK head-samples at 10%, the Collector only ever sees that 10%. Tail sampling can't recover traces the SDK already dropped. When you use tail sampling, run the SDK with the default always-on sampler.
Choosing between them
| Approach | Decides | Strength | Weakness |
|---|---|---|---|
| Head sampling | At trace start | No buffering, low overhead | Blind to errors and latency |
| Tail sampling | After trace ends | Keeps errors and slow runs | Needs Collector memory and trace-ID routing |
| Both | Start and end | Cuts SDK export volume | Tail stage only sees what head kept |
A reasonable default for an LLM app: SDK always-on, a Collector doing tail sampling, 100% of errors and slow traces, and a low percentage of the rest. If your traffic is too high to ship every span to a Collector, add a conservative head ratio and accept that you lose some failures.
Cut volume without sampling
Limit span size and count
Content capture makes individual spans large. Set limits in the SDK so a single oversized prompt can't bloat a span:
from opentelemetry.sdk.trace import SpanLimits, TracerProvider
limits = SpanLimits(
max_attributes=64,
max_events=32,
max_attribute_length=4096, # longer string attributes are truncated
)
provider = TracerProvider(span_limits=limits)max_attribute_length truncates string attribute values. That caps the cost of captured prompt text. Better still, leave content capture off by default and enable it for sampled debug sessions only, as covered in the privacy chapter.
Watch for runaway loops
A buggy agent that loops 500 times produces 500 times the spans. Cap the loop count in your agent code, and add the iteration count as an attribute on the agent span so you can find these runs. The tail-sampling span_count policy can also keep unusually large traces for review:
- name: keep-big-traces
type: span_count
span_count:
min_spans: 100Retention
Most backends charge for storage time. Keep full traces for days, not months. If you need long-term numbers such as cost per day, derive them from metrics instead of keeping old traces.
Keep cost numbers accurate with metrics
Sampled traces give wrong totals. If you add up gen_ai.usage.input_tokens across traces sampled at 5%, you see about 5% of your usage. Record token counts with the GenAI metrics as well, since metrics are aggregated before export and are not affected by trace sampling. Use traces to explain individual runs, and metrics to count spend.
Checklist
- Run the SDK with
ParentBasedso services agree on decisions. - Use tail sampling in a Collector to keep errors, slow traces and large traces.
- Route by trace ID if you run more than one sampling Collector.
- Set
SpanLimitsand keep content capture off unless needed. - Cap agent loop iterations.
- Track token spend with metrics, not sampled spans.
Exercise
Your SDK uses ParentBased(TraceIdRatioBased(0.2)), and you add a Collector with a tail_sampling policy that keeps all error traces. Users report that many failed agent runs still have no trace. Why, and what do you change?
Show answer
The SDK drops 80% of traces at the root before they reach the Collector, so the tail sampler never sees most failures. Switch the SDK to the default always-on sampler (remove the ratio sampler) and let the Collector's tail_sampling policies decide. If SDK export volume is too high, lower it by other means, such as a higher head ratio you accept as a trade-off.
Exercise
You run three Collector replicas behind a round-robin load balancer, each with the same tail_sampling config. Traces sometimes show up in the backend missing their model-call spans. What is the likely cause and fix?
Show answer
Round-robin splits one trace's spans across replicas, so each replica decides on a partial trace. Add a first-tier Collector using the loadbalancing exporter keyed by trace ID, so all spans of a trace go to the same second-tier Collector that runs tail_sampling.