Covers diagnosing broken distributed traces: confirming propagation on the wire, missing AddSource or instrumentation, inconsistent sampling, gateways stripping headers, Activity.Current lost across queues and background work, messaging without propagation, mixed propagation formats and split backends.
I'd measure first: a KQL query for requests whose operation_ParentId points at a span that doesn't exist, grouped by service, tells me which hop breaks. Then I check the wire: does the caller send traceparent, and does the callee receive it? That splits the causes:
HttpClient with propagation turned off, or an API gateway or proxy that strips or rewrites it (B3 vs W3C).AddSource, or exports to a different backend.Channel<T>, a queue or a new thread loses Activity.Current, so you pass the ActivityContext yourself.The trade-off: fixing each hop by hand is quick; preventing it needs a shared template and a propagation test.
"I treat a broken trace as a propagation bug at a specific hop, so the first job is to find the hop with data instead of guessing. In Application Insights I query for requests whose
operation_ParentIddoesn't match any span id in the same operation, grouped bycloud_RoleNameand route. That usually shows the breaks cluster in two or three places, for example every request into pricing and every Service Bus consumer.For each hop I check the wire. If
traceparentnever leaves the caller, it's a handler withActivityHeadersPropagatorset to no-output, a non-instrumented client, or a gateway or proxy stripping it; if it arrives but the callee's span has a new trace id, the callee isn't instrumented or doesn't extract it. If the parent was sent and the child is recorded but the parent is missing, it's sampling: one service using a ratio sampler that ignores the parent's flag, or ingestion sampling in the backend. In-process breaks show up as background work starting a new trace: anything that goes through aChannel<T>, a custom queue orExecutionContext.SuppressFlowlosesActivity.Current. For example, at [company] our traces broke at [an Azure API Management gateway and a Channel-based background processor]; after fixing both and making every service parent-based, the share of [broken traces fell from about 40% to under 2%].The mistake I see is fixing it one hop at a time with no measurement, so it quietly regresses with the next service. I keep the broken-trace ratio as a metric, and I add an integration test that sends a request through two services and a queue and asserts one trace id comes out the other end. Broken traces are a contract problem, so I test them like one."
| Symptom | Likely cause | Check |
|---|---|---|
| Callee's request has a new trace id | Header not sent, stripped, or not extracted | Log inbound headers at the callee; gateway trace |
| Callee span missing entirely | Not instrumented, source not registered, other backend | Callee's OpenTelemetry config; service.name in each backend |
| Child exists, parent missing (orphan) | Inconsistent sampling or ingestion sampling | Samplers per service; Application Insights sampling settings |
| Background work is a separate trace | Activity.Current lost across a queue or thread |
Code path through Channel<T>, Task.Factory.StartNew with LongRunning, SuppressFlow |
| Consumers start new traces | No context in messages | Message application properties |
| Breaks only through mesh or old services | B3 vs W3C mismatch | Inbound header names |
| Negative gaps or children before parents | Clock skew | Node time sync; trust parent/child structure, not timestamps |
In a 20-service platform, 38% of checkout traces were broken. KQL showed two hotspots: all requests through the API Management gateway (a policy rebuilt the outbound request without traceparent) and every job processed by a Channel<T> worker. Forwarding the header in the policy, carrying ActivityContext in the channel item and making two services parent-based brought broken traces under 2% within a sprint.
Checks that the candidate can debug propagation systematically, from measurement to wire to code, and knows the real-world causes.
Green flags
Activity.Current, gateways and messaging as causesRed flags
Activity.Current is lost across queues[browser] -> [gateway] -> API A --HTTP--> API B --SQL
|
+--Service Bus--> consumer C --> Channel<T> --> worker
Each arrow must carry the context:
HTTP: traceparent header (HttpClient injects, ASP.NET Core extracts)
gateway: must forward traceparent/tracestate unchanged (or create its own span)
Service Bus: application properties (you, or the experimental SDK tracing)
Channel<T>: the item must carry ActivityContext (AsyncLocal doesn't cross it)
A break at any arrow starts a new trace downstream or leaves an orphan.
In Application Insights, operation_Id is the trace id and operation_ParentId the parent span id. A request whose parent id doesn't exist as a dependency or request id in the same operation is an orphan; a request with no parent where you expected one is a new root.
Activity.Current is AsyncLocal, carried by ExecutionContext:
await, Task.Run, ThreadPool.QueueUserWorkItem: flows.ThreadPool.UnsafeQueueUserWorkItem, ExecutionContext.SuppressFlow(): doesn't flow.Channel<T> / BlockingCollection<T>: the reader's context is the one that started the loop (often at host start-up), not the writer's. The item must carry the context.BackgroundService.ExecuteAsync: runs outside any request, so it has no parent unless you pass one.PeriodicTimer): new root per tick, which is usually correct.With ParentBasedSampler, a downstream service records only if the parent did. If service B uses TraceIdRatioBasedSampler(0.5) alone while A uses 0.1, B records traces A dropped, producing children with missing parents, and drops some A kept. Backend ingestion sampling can also drop parent records independently. Fix: parent-based everywhere; sample in one place.
If service A exports to Application Insights and B to Jaeger, each backend shows half a trace. Make every service export to the same place, usually via a Collector that can fan out to several backends.
Spans are timestamped by each host's clock. A few milliseconds of skew can make a child appear to start before its parent. The tree is still correct; don't misread it as broken propagation.
traceparent and watch the trace split.Channel<T> from a request and log Activity.Current?.TraceId in the reader; then fix it by carrying ActivityContext.WebApplicationFactory for two services that asserts a shared trace id.Finding broken hops, then fixing the two most common in-code causes.
// 1. Which services receive requests whose parent span was never recorded?
let window = 1h;
let spans = union
(requests | where timestamp > ago(window) | project operation_Id, id),
(dependencies | where timestamp > ago(window) | project operation_Id, id);
requests
| where timestamp > ago(window)
| where isnotempty(operation_ParentId) and operation_ParentId != operation_Id
| join kind=leftanti spans on operation_Id, $left.operation_ParentId == $right.id
| summarize orphans = count() by cloud_RoleName, name
| order by orphans desc
// 2. Consumers or jobs that always start a new trace (no parent at all)
requests
| where timestamp > ago(1h)
| summarize total = count(), roots = countif(isempty(operation_ParentId) or operation_ParentId == operation_Id)
by cloud_RoleName, name
| extend rootPct = round(100.0 * roots / total, 1)
| where rootPct > 90
// Fix: carry the trace context through a Channel<T> explicitly.
namespace Contoso.Jobs;
using System.Diagnostics;
using System.Threading.Channels;
public sealed record ExportJob(Guid ReportId, ActivityContext Parent);
public sealed class ExportQueue
{
private readonly Channel<ExportJob> _channel = Channel.CreateBounded<ExportJob>(1_000);
// Called inside the HTTP request: capture the current context with the item.
public ValueTask EnqueueAsync(Guid reportId, CancellationToken ct) =>
_channel.Writer.WriteAsync(new ExportJob(reportId, Activity.Current?.Context ?? default), ct);
public IAsyncEnumerable<ExportJob> ReadAllAsync(CancellationToken ct) => _channel.Reader.ReadAllAsync(ct);
}
public sealed class ExportWorker(ExportQueue queue, ILogger<ExportWorker> logger) : BackgroundService
{
private static readonly ActivitySource Source = new("Contoso.Jobs");
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var job in queue.ReadAllAsync(stoppingToken))
{
// The reader's Activity.Current is empty: parent explicitly to the request that queued it.
// For work that may run long after the request, prefer a link: links: [new ActivityLink(job.Parent)].
using var activity = Source.StartActivity("export report", ActivityKind.Internal, job.Parent);
activity?.SetTag("report.id", job.ReportId);
logger.LogInformation("Exporting report {ReportId}", job.ReportId);
await Task.Delay(100, stoppingToken); // real work here
}
}
}
// Fix: one sampling policy for every service (shared extension in the service template).
builder.Services.AddOpenTelemetry().WithTracing(t => t
.SetSampler(new ParentBasedSampler(new TraceIdRatioBasedSampler(0.2)))
.AddSource("Contoso.*")
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddOtlpExporter());
traceparent disappears.ParentBasedSampler everywhere, from a shared template.Activity.Current crosses a Channel<T> or into a BackgroundService. Why it is wrong: the reader runs in its own execution context. Instead: carry ActivityContext with the item; parent or link explicitly.Broken traces are almost never one bug; they are the result of every team wiring telemetry slightly differently. The lasting fix is a shared service template (one extension method for OpenTelemetry with sampler, sources and exporter), a messaging wrapper that propagates context, and a gateway standard. Measure the broken-trace ratio per service and review it like any other quality metric.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Fix hop by hop | One or two breaks | Low | Recurring breaks across teams |
| Shared telemetry package/template | Many services, several teams | Maintaining a package | Single service |
| Collector with consistent processing | Mixed SDKs and languages | Running the Collector | Tiny estates |
| Propagation integration tests | Critical flows (checkout, payments) | Test infra (emulators, test hosts) | Never skip for critical paths |
Create a static ActivitySource, wrap the send in a Producer span and the handler in a Consumer span, and carry the context in the message. On send, call Propagators.DefaultTextMapPropagator.Inject to write traceparent (and tracestate/baggage) into ServiceBusMessage.ApplicationProperties. On receive, Extract it and pass the resulting ActivityContext as the parent to StartActivity, so the consumer's spans join the producer's trace.
The Azure SDK can do some of this itself: it writes Diagnostic-Id in traceparent format, and its own spans are experimental, needing the Azure.Experimental.EnableActivitySource switch and AddSource("Azure.Messaging.ServiceBus.*").
Tag spans with messaging semantic conventions. When one span handles a batch, or processing happens hours later, use span links instead of a parent. The trade-off: parent/child gives one tidy trace, but long-delayed work makes huge, misleading traces.
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.
I start from AppRequests for the time window and compute the failure rate by OperationName in 5-minute bins, rendered as a timechart, to see which endpoint broke and when. Then I break failures down by ResultCode, AppRoleName and, from AppExceptions, by ProblemId/ExceptionType, and check AppDependencies for the downstream Target that failed. To follow one request, I take its OperationId, which is the W3C trace id, and union requests, dependencies, exceptions and traces filtered on it, ordered by time. Finally I compare with a baseline and save the useful query as an alert. The trade-off: KQL lets you answer almost anything, but only if the telemetry is structured and correlated in the first place.
How to tell it (STAR)
**S:** At [company], during a pricing incident we couldn't follow checkout traces past our API gateway or into the export worker. **T:** I took on finding every place we were losing trace context. **A:** I ranked the breaks with two KQL queries, confirmed on the wire that the APIM policy dropped traceparent, fixed the channel-based worker to carry the trace context, and moved all services to one parent-based sampler in a shared template, plus an end-to-end propagation test. **R:** Broken checkout traces went from [38%] to under [2%], and the next incident was diagnosed from a single trace in [minutes].
Last updated 23 Nov 2026.