📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you sample traces in production? Compare head-based and tail-based sampling, explain parent-based and trace-id-ratio samplers, how you make sure errors and slow requests are always kept, what Application Insights and the Azure Monitor distro do, and how you balance cost against visibility.

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.

Senior Theory Advanced application-insights cost-optimisation distributed-tracing observability opentelemetry-collector sampling

🎯 Key points

  • Head sampling decides at the root and propagates the sampled flag; cheap but blind to the outcome
  • ParentBasedSampler(TraceIdRatioBasedSampler(p)) keeps whole traces consistent across services; a non-parent-based service causes partial traces
  • Tail sampling buffers complete traces in the Collector (decision_wait, default 30 s) and keeps errors, slow traces and a baseline percentage
  • Tail sampling needs all spans of a trace on one Collector (loadbalancing exporter by trace id); protect it with memory_limiter and alert on dropped spans
  • Compute RED metrics before sampling (OpenTelemetry metrics or spanmetrics connector) so counts and alerts stay true
  • Azure Monitor: item counts extrapolate totals; distro defaults have changed between versions (fixed 100% vs rate-limited), so set SamplingRatio or TracesPerSecond explicitly
  • Size it: spans per second x bytes x retention x price; target a budget, then tune
  • Never sample audit or security events through tracing; those belong in logs with their own retention

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 TraceIdRatioBasedSampler hashes the trace id, so any service seeing the same trace id makes the same decision, and wrapping it in ParentBasedSampler means 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_sampling processor 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 the loadbalancing exporter 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 vs tail

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

OpenTelemetry .NET samplers

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)

Typical tail policy set

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains ParentBased + ratio and why consistency matters
  • Knows tail sampling needs trace-id-aware load balancing and memory
  • Keeps metrics unsampled or extrapolated with item counts
  • Mentions explicit Azure Monitor sampler settings and checking defaults

Red flags

  • "Just sample 1% everywhere" with no thought for errors
  • Counts requests from sampled traces
  • Doesn't know where tail sampling runs

📚 Learn in depth

1. Why sampling exists

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.

2. Consistent head sampling

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.

3. Tail sampling architecture

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.

4. Keeping metrics true

  • OpenTelemetry metrics (http.server.request.duration) are aggregated in-process and never sampled.
  • The Collector's spanmetrics connector can derive RED metrics from spans, but it must sit in a pipeline that sees spans before tail sampling.
  • Application Insights stores an itemCount on each sampled record; summarize sum(itemCount) instead of count() gives estimated totals.

5. Azure Monitor specifics (as of late 2026)

  • The classic Application Insights SDK used adaptive sampling by default, varying the rate to hit a target items/second.
  • The Azure Monitor OpenTelemetry Distro supports a fixed-percentage sampler (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.
  • Ingestion sampling in the Application Insights resource drops data at the service after you've paid for network but before storage cost; use it only as a last resort.
  • The distro's sampler is trace-id based, so logs correlated to a dropped trace may also be dropped depending on configuration; check this before relying on logs for audit.

6. What not to sample through traces

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.

Try it yourself

  1. Configure ParentBasedSampler(new TraceIdRatioBasedSampler(0.1)) in two services and send 1,000 requests; count traces in Jaeger and check none are partial.
  2. Change the downstream service to TraceIdRatioBasedSampler(0.5) without ParentBased and observe broken traces.
  3. Run the Collector contrib image with a tail_sampling processor keeping errors and 5%; send traffic with 2% errors and confirm all errors are kept.
  4. In Application Insights, compare count() and sum(itemCount) on the requests table with sampling on.
  5. Calculate your monthly span volume from current request rate and spans per request, and the sampling rate needed to fit a set budget.

💻 Code

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)

⚠ Common mistakes

  • Mistake: Using a ratio sampler without ParentBasedSampler in downstream services. Why it is wrong: each service decides independently, producing partial traces. Instead: ParentBased everywhere, ratio only at the root.
  • Mistake: Deriving dashboard request counts from sampled traces with count(). Why it is wrong: counts are a fraction of reality. Instead: use OpenTelemetry metrics, or sum(itemCount) in Application Insights.
  • Mistake: Running tail sampling on several Collector replicas behind a round-robin load balancer. Why it is wrong: spans of one trace land on different instances, so policies see fragments. Instead: a tier-1 loadbalancing exporter routing by trace id.
  • Mistake: Sizing the tail-sampling Collector by CPU only. Why it is wrong: it buffers every trace for 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.
  • Mistake: Assuming the Azure Monitor distro keeps 100% of traces. Why it is wrong: defaults differ by version, and recent versions document rate-limited sampling. Instead: set SamplingRatio or TracesPerSecond explicitly.
  • Mistake: Relying on traces for audit or security events. Why it is wrong: sampling drops them. Instead: dedicated logs with fixed retention.
  • Mistake: Turning on ingestion sampling as the main cost control. Why it is wrong: you still pay to send the data and lose control over which traces survive. Instead: sample in the SDK or Collector.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the Azure Monitor distro or OTLP exporter Why: Checks overall OpenTelemetry setup and where sampling is configured
    How to answer

    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.

  2. When: Candidate mentions the OpenTelemetry Collector Why: Checks pipeline design, Collector placement and its failure modes
    How to answer

    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.

  3. When: Candidate says percentiles from sampled data are estimates Why: Checks their understanding of percentiles and histograms
    How to answer

    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.

🛠 Real-world problems: how you handle them

Tracing bill tripled and the one failed trace you need was sampled away
Situation
A retail platform [about 30 .NET services on AKS] sent 100% of traces to Application Insights. Ingestion cost tripled during a sales event, finance asked for cuts, and a hurried 1% ingestion-sampling setting then hid the traces for a payment failure affecting [about 0.5%] of checkouts.
Signals
Azure Cost Management showed Log Analytics ingestion as the top cost line. After the cut, on-call could see the payment error rate rising on the RED dashboard but found no failed traces in the transaction search.
Investigation
Used KQL on the `AppDependencies`/`AppRequests` tables with `sum(_BilledSize)` by `AppRoleName` to find the top producers (two chatty services generated [60%] of spans). Confirmed ingestion sampling was dropping traces uniformly regardless of outcome. Reviewed each service's sampler: three used non-parent-based samplers, producing partial traces.
Resolution
Immediately removed ingestion sampling and set the distro's `SamplingRatio` to 0.2 with ParentBased behaviour everywhere, plus a targeted fix to stop the chatty services creating a span per cache lookup. Then deployed a two-tier OpenTelemetry Collector with tail sampling (all errors, > 800 ms, 100% of /checkout, 5% baseline) and switched services to send 100% to it.
Prevention
Monthly ingestion review per service with a budget; alert when a service's daily ingestion exceeds its budget by 50% (team channel, not paged). Alert on Collector dropped spans > 0.1% for 15 minutes, paging the platform on-call with a runbook for scaling tier 2. Sampler configuration is now part of the shared service template.

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].

↩ Usually asked after

More in Tracing

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me