Covers head sampling (ParentBased, TraceIdRatioBased, rate-limited), tail sampling in the OpenTelemetry Collector with its load-balancing requirement, keeping errors and slow traces, Azure Monitor sampling and item counts, and the cost/visibility trade-off.
Head sampling decides at the start of a trace: the root service keeps, say, 10%, and the decision travels in the traceparent sampled flag so every service records the same traces. In .NET that's ParentBasedSampler(new TraceIdRatioBasedSampler(0.1)). It's cheap, but it decides before knowing whether the request will fail.
Tail sampling decides after the trace completes: the OpenTelemetry Collector buffers spans (about 30 s), then keeps all errors, all traces slower than a threshold, and a small random baseline. It needs every span of a trace on the same Collector, so you route by trace id with the loadbalancing exporter, and it costs memory.
Always compute metrics before sampling, so dashboards and alerts stay accurate. The trade-off: head sampling is simple and cheap; tail sampling keeps the interesting traces but adds infrastructure you must run.
"Tracing every request at scale is usually unaffordable, so the question is which traces you keep. Head sampling makes the decision when the root span starts. OpenTelemetry's
TraceIdRatioBasedSamplerhashes the trace id, so any service seeing the same trace id makes the same decision, and wrapping it inParentBasedSamplermeans downstream services simply follow the caller's sampled flag. You get complete traces at a predictable cost. The weakness is that the decision is made before you know the outcome: at 5% you throw away 95% of your errors.Tail sampling fixes that by deciding after the trace finishes. Services send 100% of spans to an OpenTelemetry Collector tier, the
tail_samplingprocessor waits around 30 seconds for the trace to complete, and policies keep every trace with an error status, every trace over, say, 1 second, and a 5% baseline of the rest. For example, at [company] we [cut tracing ingestion by about 80%] while keeping every failed checkout trace. The cost is operational: the Collector holds traces in memory, so you size it for spans per second times the wait time, and because every span of a trace has to reach the same instance, you need a first tier with theloadbalancingexporter routing by trace id.The mistake I see is sampling before computing metrics, then wondering why request counts on the dashboard are a tenth of reality. RED metrics come from the OpenTelemetry metrics pipeline, which isn't sampled, or from the Collector's span-metrics connector placed before the sampler. On Azure Monitor, sampled telemetry carries an item count so counts are extrapolated, but percentiles from sampled data are still estimates. Sample traces for examples; never sample the numbers you alert on."
| Head sampling | Tail sampling | |
|---|---|---|
| Decides | At the root span | After the trace completes |
| Where | In the SDK | In the Collector (or vendor backend) |
| Keeps errors? | Only at the sample rate | Yes, by policy |
| Network cost | Only sampled spans leave the app | All spans go to the Collector |
| Infrastructure | None | Collector tier, load balancing by trace id, memory |
| Failure mode | Missing the trace you need | Collector overload drops traces; late spans miss the decision |
| Sampler | Behaviour |
|---|---|
AlwaysOnSampler |
Keep everything (the SDK default root sampler) |
AlwaysOffSampler |
Keep nothing |
TraceIdRatioBasedSampler(p) |
Keep fraction p, consistent by trace id |
ParentBasedSampler(root) |
Follow the parent's flag; use root only for new traces |
| Azure Monitor distro | SamplingRatio (fixed percentage) or TracesPerSecond (rate-limited) |
| Policy | Keeps |
|---|---|
status_code: ERROR |
Every failed trace |
latency: threshold_ms: 1000 |
Every slow trace |
string_attribute on http.route |
100% of critical routes such as /checkout |
probabilistic: 5% |
Baseline of normal traffic |
rate_limiting |
Hard cap on spans per second |
A platform producing about 40,000 spans per second sent everything to Application Insights at a cost of [about A$X per month]. Moving to a two-tier Collector with tail sampling (errors, > 800 ms, 5% baseline) cut ingested spans to roughly 3,500 per second, an 91% reduction, while every failed checkout remained traceable. RED metrics stayed exact because they came from OpenTelemetry metrics.
Checks that the candidate can make a cost-versus-visibility decision with real mechanisms and knows how sampling interacts with metrics and Azure Monitor.
Green flags
Red flags
Cost scales with spans: spans/s x average size x retention x price per GB. At 10,000 requests per second with 15 spans each and ~1 KB per span, that's about 150 MB/s, roughly 13 TB per day. Nobody looks at 99.9% of those traces; you need the failures, the slow ones, and a representative sample.
TraceIdRatioBasedSampler compares part of the trace id with a threshold derived from p. Because the trace id is random and shared, every service independently reaches the same decision, but in practice you use ParentBasedSampler so services just obey the inbound flag:
root (edge): new trace -> ratio sampler -> sampled=1 (10% of the time)
downstream: traceparent flags=01 -> ParentBased -> record
traceparent flags=00 -> ParentBased -> drop
If one service uses a non-parent-based sampler, you get broken traces: some hops recorded, others not.
services (100% of spans, OTLP)
|
v
Collector tier 1: loadbalancing exporter, routing_key: traceID
| (consistent hashing over tier-2 instances)
v
Collector tier 2: tail_sampling processor
| buffers spans per trace for decision_wait (default 30s)
| evaluates policies -> keep or drop whole trace
v
backend (Application Insights, Jaeger, Tempo ...)
Memory needed is roughly spans/s x decision_wait x span size: 40,000 x 30 x 1 KB is about 1.2 GB per tier before overhead, spread across instances. num_traces (default 50,000) caps the traces held; set it above traces/s x decision_wait or traces get evicted before decisions. Spans arriving after the decision (long async work) are handled by the decision cache settings; without them they are dropped or start a new decision.
http.server.request.duration) are aggregated in-process and never sampled.itemCount on each sampled record; summarize sum(itemCount) instead of count() gives estimated totals.SamplingRatio) and a rate-limited sampler (TracesPerSecond). Microsoft's readme for recent versions documents rate-limited sampling at 5 traces per second as the default, while older versions defaulted to 100%. Check the defaults in the package version you deploy rather than assuming.Security and audit events (logins, permission changes, data exports) must be complete and kept for their own retention period, often years for compliance. Send them as logs or to a dedicated store, not as span events subject to sampling.
ParentBasedSampler(new TraceIdRatioBasedSampler(0.1)) in two services and send 1,000 requests; count traces in Jaeger and check none are partial.TraceIdRatioBasedSampler(0.5) without ParentBased and observe broken traces.tail_sampling processor keeping errors and 5%; send traffic with 2% errors and confirm all errors are kept.count() and sum(itemCount) on the requests table with sampling on.Head sampling in the SDK, and a tail-sampling Collector configuration.
// Program.cs: plain OpenTelemetry with consistent head sampling
using OpenTelemetry.Trace;
builder.Services.AddOpenTelemetry()
.WithTracing(t => t
// New traces: keep 10%. Existing traces: follow the caller's sampled flag.
.SetSampler(new ParentBasedSampler(new TraceIdRatioBasedSampler(0.10)))
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddOtlpExporter())
.WithMetrics(m => m // metrics are not sampled: RED stays exact
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddOtlpExporter());
// With tail sampling in the Collector instead, send 100% from the app:
// .SetSampler(new AlwaysOnSampler())
// Program.cs: Azure Monitor distro, choose the sampler explicitly instead of relying on a version's default
using Azure.Monitor.OpenTelemetry.AspNetCore;
builder.Services.AddOpenTelemetry().UseAzureMonitor(o =>
{
o.TracesPerSecond = null; // turn off rate-limited sampling
o.SamplingRatio = 0.2F; // keep 20% of traces, item counts extrapolate totals
});
# collector-tier2.yaml: tail sampling (tier 1 uses the loadbalancing exporter with routing_key: traceID)
receivers:
otlp:
protocols: { grpc: {}, http: {} }
processors:
memory_limiter: { check_interval: 1s, limit_percentage: 80, spike_limit_percentage: 20 }
tail_sampling:
decision_wait: 30s
num_traces: 200000
policies:
- name: keep-errors
type: status_code
status_code: { status_codes: [ERROR] }
- name: keep-slow
type: latency
latency: { threshold_ms: 1000 }
- name: keep-checkout
type: string_attribute
string_attribute: { key: http.route, values: ["/api/checkout"] }
- name: baseline
type: probabilistic
probabilistic: { sampling_percentage: 5 }
batch: {}
exporters:
otlphttp:
endpoint: https://tracing-backend.internal:4318
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, tail_sampling, batch]
exporters: [otlphttp]
// Application Insights: estimated request totals with sampling on
requests
| where timestamp > ago(1h)
| summarize sampled = count(), estimated = sum(itemCount) by bin(timestamp, 5m)
ParentBasedSampler in downstream services. Why it is wrong: each service decides independently, producing partial traces. Instead: ParentBased everywhere, ratio only at the root.count(). Why it is wrong: counts are a fraction of reality. Instead: use OpenTelemetry metrics, or sum(itemCount) in Application Insights.loadbalancing exporter routing by trace id.decision_wait; memory is the limit and overload drops data. Instead: size for spans/s x wait x span size, add memory_limiter, and alert on dropped spans.SamplingRatio or TracesPerSecond explicitly.Start with a budget, not a rate: work out what you can afford to ingest and retain, then choose the cheapest strategy that keeps the traces you actually use during incidents, which are almost always errors and slow requests on critical paths. For most teams that means head sampling at 5–20% until volume or missed-error complaints justify a tail-sampling tier. Measure it: alert on Collector otelcol_processor_dropped_spans and refused spans, and review monthly ingestion per service.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| No sampling | < ~100 req/s, or short debugging windows | Highest ingestion | High-traffic production |
| Head, ParentBased ratio | Most services; simple, predictable | Lowest | When rare errors must always be traced |
Rate-limited (Azure distro TracesPerSecond) |
Predictable bill on Azure Monitor | Fixed | Bursty traffic where you need proportional samples |
| Tail in Collector | High volume, must keep every error | Collector tier, memory, ops effort | Small teams without platform support |
OpenTelemetry gives you three correlated signals: traces (a span per operation, linked by trace id), metrics (cheap aggregated counters and histograms) and logs (events that carry the TraceId and SpanId of the span they were written in).
In .NET the runtime already emits Activity and Meter data; you call AddOpenTelemetry() with WithTracing, WithMetrics and WithLogging, set a resource (service.name), and choose an exporter: UseOtlpExporter() for any OTLP back end or Collector (endpoint from OTEL_EXPORTER_OTLP_ENDPOINT or options), or the Azure Monitor distro (UseAzureMonitor()) for Application Insights.
For cost: metrics for rates and latency (never sampled), sampled traces (the distro now defaults to a rate-limited sampler of 5 traces per second, which adapts the kept percentage to load; you can change the rate or switch to a fixed SamplingRatio), level-filtered logs, and tail sampling in a Collector, configured with policies to keep errors and slow traces. The trade-off is completeness versus ingestion cost.
Services log with ILogger + OpenTelemetry and send OTLP to an OpenTelemetry Collector, never to a vendor directly. I run the Collector as an agent per node for buffering and Kubernetes metadata, and as a gateway for central policy: enrich (service, version, environment, pod), filter noise such as health checks, mask personal data (after masking at source), sample high-volume Information logs, then route by data class: operational logs to Log Analytics with 30 days, audit and security to a cheaper long-retention store, debug to a short-lived tier. I protect it with memory limits, persistent queues and alerts on dropped data. The trade-off: a pipeline gives control and vendor freedom, but it is another production system you must run and monitor.
An average mixes fast and slow requests into one number that describes almost nobody. If 95 requests take 50 ms and 5 take 3 s, the average is (95 × 50 + 5 × 3,000) / 100 ≈ 198 ms, which looks fine while 1 in 20 customers waits 3 seconds. Percentiles describe the distribution: p50 is the typical request, p95/p99 is the slow tail people complain about.
Percentiles come from a histogram: count requests into buckets, then find the bucket where 99% of the count is reached and interpolate (put bucket boundaries close to your SLO threshold so the estimate is tight). Because a percentile is not additive, you cannot average p99 across pods or time windows; you merge the bucket counts first and then take the quantile, which is what histogram_quantile(0.99, sum by (le) (rate(...[5m]))) does.
The trade-off: high percentiles need enough traffic and well-chosen buckets to be trustworthy, so chart the request count next to them and alert on SLO burn rate rather than a raw p99.
How to tell it (STAR)
**S:** At [company], our tracing bill tripled in a sales event, and a rushed sampling change then hid the traces of a live payment failure. **T:** I was asked to cut cost without losing the traces we need in incidents. **A:** I found the top span producers with KQL, fixed two chatty services, made every service parent-based, and built a two-tier Collector with tail sampling that keeps every error and slow checkout plus a 5% baseline. **R:** Ingestion dropped by [about 85%] from the peak, every failed checkout stayed traceable, and the next payment incident was diagnosed in [under 15 minutes].
Last updated 23 Nov 2026.