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

📚 Interview question

Your traces are broken. In Application Insights a checkout shows the API request but not the downstream pricing call's server span, background jobs and Service Bus consumers appear as separate traces, and some traces have orphan spans with missing parents. How do you find where trace context is being lost, and how do you fix each cause?

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.

Senior Debugging Advanced application-insights context-propagation debugging distributed-tracing observability opentelemetry

🎯 Key points

  • Measure first: KQL for requests whose operation_ParentId points at no existing span, by service and route
  • Check the wire: is traceparent sent by the caller and received by the callee (DelegatingHandler, gateway logs)
  • Missing spans: source not registered with AddSource, instrumentation missing, or a different exporter/backend per service
  • Orphans: services with non-parent-based samplers, or ingestion sampling dropping parents
  • Lost in-process: Channel<T>, custom queues, Task.Run with suppressed flow or new threads; pass ActivityContext explicitly
  • Messaging: inject/extract traceparent in message properties; links for batches and delayed work
  • Gateways, proxies and meshes stripping or rewriting headers (B3 vs W3C); composite propagator during migration
  • Prevent: integration tests through HTTP, gateway and queue asserting one trace id, a shared telemetry template, and a broken-trace ratio per service reviewed regularly with an alert

⏱ 30-second answer

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:

  • Header never sent: a hand-built HttpClient with propagation turned off, or an API gateway or proxy that strips or rewrites it (B3 vs W3C).
  • Sent but no span: the callee is missing instrumentation, AddSource, or exports to a different backend.
  • Orphan spans: a service uses a non-parent-based sampler, or ingestion sampling dropped the parent.
  • Lost in-process: work handed through Channel<T>, a queue or a new thread loses Activity.Current, so you pass the ActivityContext yourself.
  • Messaging: nobody injects context into Service Bus messages.

The trade-off: fixing each hop by hand is quick; preventing it needs a shared template and a propagation test.

🗣 Full answer (senior)

How I would answer this in an interview

"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_ParentId doesn't match any span id in the same operation, grouped by cloud_RoleName and 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 traceparent never leaves the caller, it's a handler with ActivityHeadersPropagator set 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 a Channel<T>, a custom queue or ExecutionContext.SuppressFlow loses Activity.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 to cause

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can debug propagation systematically, from measurement to wire to code, and knows the real-world causes.

Green flags

  • Starts by measuring where traces break (KQL, per service and route)
  • Checks headers on the wire before reading code
  • Names sampling inconsistency, lost Activity.Current, gateways and messaging as causes
  • Proposes prevention: shared template, tests, a broken-trace metric

Red flags

  • Guesses and adds random spans
  • Doesn't know Activity.Current is lost across queues
  • Ignores sampling as a cause of orphans

📚 Learn in depth

1. How propagation should work, end to end

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

2. Finding the hop with KQL

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.

3. Why Activity.Current gets lost

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.
  • Timers (PeriodicTimer): new root per tick, which is usually correct.

4. Sampling-induced orphans

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.

5. Gateways, proxies and meshes

  • Reverse proxies (YARP, NGINX, Application Gateway) forward headers by default, but custom policies that rebuild requests often don't.
  • Azure API Management can create its own spans when configured for Application Insights; check that outbound requests carry the context.
  • Service meshes may use B3 headers; if your services speak only W3C, configure the mesh for W3C or use a composite propagator.

6. Split backends

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.

7. Clock skew

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.

Try it yourself

  1. Run two services and a gateway (YARP) locally; add a transform that removes traceparent and watch the trace split.
  2. Write to a Channel<T> from a request and log Activity.Current?.TraceId in the reader; then fix it by carrying ActivityContext.
  3. Give one service a non-parent-based sampler and count orphans in Jaeger.
  4. Run the KQL orphan query below against a test Application Insights resource.
  5. Write an integration test with WebApplicationFactory for two services that asserts a shared trace id.

💻 Code

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());

⚠ Common mistakes

  • Mistake: Adding more custom spans to "fill the gaps". Why it is wrong: the problem is lost context, and new spans just create more orphans. Instead: find the hop where traceparent disappears.
  • Mistake: Checking only the caller's code. Why it is wrong: gateways and proxies between services often drop or rewrite headers. Instead: log inbound headers at the callee and check gateway policies.
  • Mistake: Mixing parent-based and independent ratio samplers across services. Why it is wrong: produces orphans and partial traces. Instead: ParentBasedSampler everywhere, from a shared template.
  • Mistake: Assuming 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.
  • Mistake: Different services exporting to different backends. Why it is wrong: each backend shows half the trace. Instead: one backend, or a Collector fanning out.
  • Mistake: Reading clock-skew gaps as broken propagation. Why it is wrong: the parent/child ids are correct; only timestamps disagree. Instead: check ids, and fix time sync separately.
  • Mistake: Fixing breaks without a regression test. Why it is wrong: the next new service or gateway policy breaks it again. Instead: a cross-service propagation test plus a broken-trace ratio metric.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Service Bus consumers starting new traces Why: Checks they can implement inject/extract and links for messaging
    How to answer

    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.

  2. When: Candidate mentions orphan spans from sampling Why: Checks their understanding of parent-based, ratio and tail sampling
    How to 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.

  3. When: Candidate uses KQL to find broken hops Why: Checks fluency with KQL for incident questions and following a trace id
    How to answer

    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.

🛠 Real-world problems: how you handle them

Checkout traces broken at the gateway and a background channel
Situation
A retail platform [about 20 .NET 10 services on AKS behind Azure API Management] relied on Application Insights for incident diagnosis. During a pricing incident, on-call couldn't follow checkout requests past the gateway or into the order-export worker.
Signals
The end-to-end transaction view showed API requests ending at the APIM call with no downstream server span. Export jobs appeared as separate root operations. An orphan-count KQL query showed [38%] of checkout traces broken.
Investigation
Ran the orphan and root-percentage KQL queries to rank breaks by service and route: pricing (all requests via APIM) and the export worker topped the list. Logged inbound headers at pricing and saw no traceparent; the APIM policy used send-request to rebuild the call without copying headers. Read the export code: work went through a Channel<T> consumed by a BackgroundService, so Activity.Current was empty. Also found two services using a non-parent-based 50% sampler, producing orphans.
Resolution
Immediately added traceparent and tracestate forwarding to the APIM policy. Then carried ActivityContext in the channel items (links for jobs delayed more than a minute), and moved every service to the shared telemetry extension with ParentBasedSampler. Broken traces dropped under [2%] within the sprint.
Prevention
An integration test pushes a request through two services, a queue and the worker and asserts one trace id. A dashboard tile shows the broken-trace ratio per service, with an alert at > 10% for an hour sent to the owning team's channel and a runbook listing the usual causes. Gateway policy reviews check header forwarding.

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

↩ Usually asked after

More in Tracing

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me