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

📚 Interview question

Show me how you add custom spans and attributes to a .NET 10 service and propagate the trace context through Azure Service Bus messages so the consumer's work appears in the same trace. Cover Producer and Consumer spans, injecting and extracting the context, messaging semantic conventions, and when to use span links instead of parent/child.

Covers writing custom spans with ActivitySource, injecting and extracting W3C trace context through Service Bus application properties, Producer/Consumer span kinds, messaging semantic conventions, span links for batches, and the Azure SDK's experimental tracing flag.

Mid-Level Coding Intermediate azure-service-bus context-propagation distributed-tracing messaging observability opentelemetry

🎯 Key points

  • HTTP is automatic (HttpClient writes traceparent, ASP.NET Core reads it); messaging needs the context carried in the message
  • Producer span around send, Consumer span around processing (ActivityKind.Producer/Consumer)
  • Inject with Propagators.DefaultTextMapPropagator into ApplicationProperties (traceparent, tracestate, baggage); extract on receive and pass the ActivityContext as parent, since Activity.Current is empty in the processor callback
  • Azure SDK messaging spans are experimental: Azure.Experimental.EnableActivitySource plus AddSource("Azure.Messaging.ServiceBus.*"); keep explicit propagation as the contract
  • Service Bus SDK writes Diagnostic-Id in traceparent format on send
  • Semantic conventions: messaging.system=servicebus, messaging.destination.name, messaging.operation.type, messaging.message.id
  • Use ActivityLink for batches or delayed processing; links cost a little more to store and not every backend renders them well
  • Verify end to end in Jaeger or Application Insights; never put message bodies or personal data in tags or baggage

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"HTTP propagation is free in .NET because HttpClient writes traceparent and ASP.NET Core reads it. Messaging isn't, unless the client library does it, so I make the context part of the message. On the producer side I start an activity with ActivityKind.Producer, then use OpenTelemetry's Propagators.DefaultTextMapPropagator.Inject to write the W3C headers into ServiceBusMessage.ApplicationProperties. On the consumer side, in the ServiceBusProcessor handler, I Extract from the received message's properties and start an ActivityKind.Consumer activity with that context as its parent. Everything the handler does after that, EF Core queries, HTTP calls, shows up under the same trace id.

The Azure SDK helps but I don't rely on it alone: it stamps a Diagnostic-Id property in traceparent format, and it can emit its own send and process spans, but for messaging that is still behind the Azure.Experimental.EnableActivitySource switch. I turn it on and add AddSource("Azure.Messaging.ServiceBus.*"), and I keep explicit injection so the contract doesn't depend on an experimental feature. For example, at [company] we had [an order pipeline] where the trace stopped at the queue; after adding this, a failed fulfilment showed the original checkout request, the publish, and the consumer's [SQL deadlock] in one view, and our time to diagnose [dropped from about an hour to a few minutes].

The mistake I see is making the consumer a child of the producer when the message is processed much later or in a batch. A message retried from the dead-letter queue three days later would stretch the trace across three days. In those cases I start a new trace and add an ActivityLink to the producer's context: the backend still connects them, but each trace stays a sensible size. Parent for 'part of the same request', link for 'caused by, but separate'."


What goes where

Side Span kind Context step Key tags
Producer Producer Inject into ApplicationProperties messaging.system, messaging.destination.name, messaging.operation.type=send, messaging.message.id
Consumer Consumer Extract from ApplicationProperties same, with messaging.operation.type=process, plus delivery count

Parent or link?

Situation Use
One message, processed within seconds, part of the user's request Parent/child
One span processes a batch of 50 messages Links to each message's context
Scheduled or delayed message, dead-letter replay New trace with a link
Fan-out to many consumers Each consumer as a child (or link if delayed)

Production example

An order pipeline published OrderPlaced to a Service Bus topic consumed by three services. Before propagation, each consumer started its own trace and correlating a failure took roughly 45 minutes of KQL. After injecting traceparent and adding Consumer spans, one end-to-end transaction view showed the request, the publish and all three consumers, and median diagnosis time for fulfilment incidents fell to under 10 minutes.

🔍 What the interviewer is checking

Checks that the candidate can make traces survive an asynchronous hop with correct span kinds, semantic conventions and parent-vs-link judgement.

Green flags

  • Uses Inject/Extract with ApplicationProperties
  • Producer/Consumer kinds and messaging semantic conventions
  • Knows the Azure SDK messaging tracing is experimental
  • Explains when to use span links

Red flags

  • "Tracing works through queues automatically"
  • Passes a custom correlation id instead of the trace context
  • Puts personal data in baggage

📚 Learn in depth

1. Why messaging breaks the chain

HTTP:   API --traceparent header--> API         (done for you)
Queue:  API --message--> [broker] --> consumer  (only if someone writes the context into the message)

The broker doesn't know about tracing. The context has to travel as message metadata, which in Service Bus means ApplicationProperties (AMQP application properties).

2. Propagators

OpenTelemetry defines a TextMapPropagator that turns a context into string key/value pairs and back. When you build the OpenTelemetry SDK, Propagators.DefaultTextMapPropagator becomes a composite of TraceContext (traceparent, tracestate) and Baggage (baggage). The propagator doesn't care what the carrier is; you give it a setter and getter delegate. .NET also has a runtime-level DistributedContextPropagator.Current used by HttpClient; for messaging code, the OpenTelemetry propagator is the usual choice.

3. What the Azure SDK does

  • On send, the Service Bus client adds a Diagnostic-Id application property in W3C traceparent format (from Activity.Current).
  • With the experimental switch on (AppContext.SetSwitch("Azure.Experimental.EnableActivitySource", true) or the AZURE_EXPERIMENTAL_ENABLE_ACTIVITY_SOURCE=true variable), it emits ServiceBusSender.Send, ServiceBusProcessor.ProcessMessage and similar spans from sources under Azure.Messaging.ServiceBus.
  • Status as of late 2026: the messaging tracing is still marked experimental, so behaviour can change between versions. Check the SDK changelog before relying on it.

If you write traceparent yourself as well, extract traceparent first and fall back to Diagnostic-Id.

4. Span links

A link says "this span is related to that span context" without making it the parent. OpenTelemetry messaging conventions recommend links for batch receive and for processing that is decoupled in time. In .NET you pass IEnumerable<ActivityLink> to StartActivity. Links must be supplied at creation time so samplers can consider them (Activity.AddLink exists in .NET 9+ but is less useful for sampling).

5. Retries and delivery count

Each redelivery creates a new Consumer span with the same parent; tag messaging.servicebus.message.delivery_count so you can see retries in the trace. Dead-lettering should set the span status to Error with the reason.

6. Privacy

Baggage is propagated in clear text to every downstream service and often to third parties. Never put personal information, tokens or tenant secrets in baggage or tags. Under the Privacy Act APP 11 you are responsible for wherever that data ends up, including your tracing vendor.

Try it yourself

  1. Run the Service Bus emulator in Docker and send a message without propagation; confirm two separate traces in Jaeger.
  2. Add Inject/Extract and confirm one trace.
  3. Turn on the Azure experimental switch and compare the SDK's spans with yours.
  4. Process a batch of 20 messages in one span with links; view the links in Jaeger.
  5. Throw in the handler so the message is redelivered 3 times and find the three Consumer spans.

💻 Code

Producer and consumer with explicit W3C propagation through Service Bus application properties.

// Messaging/OrderMessagingTelemetry.cs
namespace Contoso.Orders.Messaging;

using System.Diagnostics;
using System.Text.Json;
using Azure.Messaging.ServiceBus;
using OpenTelemetry;
using OpenTelemetry.Context.Propagation;

public static class OrderMessagingTelemetry
{
    public const string SourceName = "Contoso.Orders.Messaging";
    public static readonly ActivitySource Source = new(SourceName);
    public static TextMapPropagator Propagator => Propagators.DefaultTextMapPropagator; // TraceContext + Baggage
}

public sealed record OrderPlaced(Guid OrderId, decimal Total);

public sealed class OrderPublisher(ServiceBusSender sender)
{
    public async Task PublishAsync(OrderPlaced evt, CancellationToken ct)
    {
        using var activity = OrderMessagingTelemetry.Source.StartActivity(
            $"send {sender.EntityPath}", ActivityKind.Producer);

        var message = new ServiceBusMessage(JsonSerializer.SerializeToUtf8Bytes(evt))
        {
            MessageId = evt.OrderId.ToString() // also enables duplicate detection
        };

        activity?.SetTag("messaging.system", "servicebus");
        activity?.SetTag("messaging.destination.name", sender.EntityPath);
        activity?.SetTag("messaging.operation.type", "send");
        activity?.SetTag("messaging.message.id", message.MessageId);

        // Write traceparent/tracestate/baggage into the message so the consumer can continue the trace.
        var context = activity?.Context ?? Activity.Current?.Context ?? default;
        OrderMessagingTelemetry.Propagator.Inject(
            new PropagationContext(context, Baggage.Current),
            message.ApplicationProperties,
            static (props, key, value) => props[key] = value);

        await sender.SendMessageAsync(message, ct);
    }
}
// Messaging/OrderPlacedHandler.cs
namespace Contoso.Orders.Messaging;

using System.Diagnostics;
using Azure.Messaging.ServiceBus;
using OpenTelemetry;
using OpenTelemetry.Context.Propagation;

public sealed class OrderPlacedHandler(ILogger<OrderPlacedHandler> logger)
{
    public async Task HandleAsync(ProcessMessageEventArgs args)
    {
        var msg = args.Message;

        var parent = OrderMessagingTelemetry.Propagator.Extract(
            default, msg.ApplicationProperties, static (props, key) =>
                props.TryGetValue(key, out var v) && v is string s ? [s] : []);
        Baggage.Current = parent.Baggage;

        // Recent message: continue the producer's trace as a child.
        using var activity = OrderMessagingTelemetry.Source.StartActivity(
            $"process {args.EntityPath}", ActivityKind.Consumer, parent.ActivityContext);

        activity?.SetTag("messaging.system", "servicebus");
        activity?.SetTag("messaging.destination.name", args.EntityPath);
        activity?.SetTag("messaging.operation.type", "process");
        activity?.SetTag("messaging.message.id", msg.MessageId);
        activity?.SetTag("messaging.servicebus.message.delivery_count", msg.DeliveryCount);

        try
        {
            logger.LogInformation("Processing order message {MessageId}", msg.MessageId); // log carries the trace id
            // ... handle, EF Core and HTTP spans become children here ...
            await args.CompleteMessageAsync(msg, args.CancellationToken);
        }
        catch (Exception ex)
        {
            activity?.AddException(ex);
            activity?.SetStatus(ActivityStatusCode.Error, ex.GetType().Name);
            throw; // processor abandons; delivery count increments
        }
    }

    // Batch or delayed processing: new trace, linked to each producer context.
    public static Activity? StartBatchActivity(IReadOnlyList<ServiceBusReceivedMessage> batch)
    {
        var links = batch.Select(m => new ActivityLink(OrderMessagingTelemetry.Propagator.Extract(
            default, m.ApplicationProperties, static (p, k) =>
                p.TryGetValue(k, out var v) && v is string s ? [s] : []).ActivityContext));

        return OrderMessagingTelemetry.Source.StartActivity(
            ActivityKind.Consumer, parentContext: default, links: links, name: "process batch");
    }
}
// Program.cs
AppContext.SetSwitch("Azure.Experimental.EnableActivitySource", true); // Azure SDK messaging spans (experimental)

builder.Services.AddOpenTelemetry()
    .WithTracing(t => t
        .AddSource(OrderMessagingTelemetry.SourceName)
        .AddSource("Azure.Messaging.ServiceBus.*")
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddOtlpExporter());

⚠ Common mistakes

  • Mistake: Assuming Service Bus propagates traces the way HttpClient does. Why it is wrong: the SDK's messaging spans are experimental and off by default, so traces stop at the queue. Instead: inject and extract explicitly, and optionally enable the switch.
  • Mistake: Extracting the context but not passing it to StartActivity. Why it is wrong: the consumer span parents to Activity.Current (usually none), starting a new trace. Instead: pass parent.ActivityContext as parentContext.
  • Mistake: Using ActivityKind.Internal for send and process. Why it is wrong: backends use Producer/Consumer to draw the messaging hop and compute queue time. Instead: Producer on send, Consumer on process.
  • Mistake: Making a dead-letter replay a child of the original request. Why it is wrong: the trace spans days and distorts duration views. Instead: new trace with an ActivityLink.
  • Mistake: Putting customer emails or the message body in tags or baggage. Why it is wrong: tags are retained in the tracing backend and baggage is sent to every downstream service. Instead: ids and bounded values only.
  • Mistake: Forgetting AddSource for the messaging source. Why it is wrong: no listener means StartActivity returns null and nothing is recorded. Instead: register every custom and SDK source.
  • Mistake: Not recording the exception or status on failure. Why it is wrong: the trace looks healthy while the message is being retried. Instead: AddException and SetStatus(Error) before rethrowing.

🏛 Senior insight: trade-offs

Make propagation a property of your messaging abstraction, not of each handler: one publisher wrapper injects, one processor wrapper extracts and starts the Consumer span. Libraries like MassTransit and NServiceBus already do this and emit OpenTelemetry spans; if you use them, register their sources instead of writing your own. Measure success by the share of consumer spans with a non-empty parent or link, which you can query.

Option When it fits Cost When not to
Explicit inject/extract (this example) Raw Azure SDK clients Small wrapper code You already use MassTransit/NServiceBus
Azure SDK experimental tracing Quick visibility of SDK operations Experimental, may change As your only propagation contract
Messaging framework instrumentation MassTransit, NServiceBus, Wolverine Framework dependency Thin services with one queue

🔗 Follow-ups the interviewer may ask

  1. When: Candidate writes a ServiceBusProcessor handler Why: Checks complete/abandon/dead-letter, concurrency and shutdown handling in the consumer
    How to answer

    I host a ServiceBusProcessor in a BackgroundService, with ServiceBusClient as a singleton using DefaultAzureCredential. I set AutoCompleteMessages = false and settle explicitly:

    • Complete after the database commit, which gives at-least-once delivery.
    • Abandon (or just throw) on transient errors so DeliveryCount rises and the broker redelivers; after MaxDeliveryCount it dead-letters automatically.
    • Dead-letter immediately on permanent errors such as an unparseable body, with a reason.

    MaxConcurrentCalls is sized to the downstream, PrefetchCount is kept small, and MaxAutoLockRenewalDuration is longer than the slowest handler. On shutdown I call StopProcessingAsync and honour args.CancellationToken. Because duplicates still happen, the handler is idempotent on MessageId. The trade-off: more concurrency means more throughput but more pressure on the database.

  2. When: Candidate mentions traceparent and correlation Why: Checks how log correlation relates to trace propagation
    How to answer

    Two mechanisms work together.

    • Log scopes: using (logger.BeginScope(new Dictionary<string, object> { ["OrderId"] = id })) adds properties to every log inside the block, flowing across await via AsyncLocal. ASP.NET Core already opens a scope per request with RequestId and RequestPath.
    • Distributed tracing: each request runs inside an Activity whose trace id comes from the incoming W3C traceparent header or is created new. With ActivityTrackingOptions (on by default in the Generic Host) every log carries TraceId and SpanId. HttpClient propagates traceparent automatically; message queues need it copied into message properties (the Azure Service Bus SDK does this).

    So the trace id is your correlation id; add business ids as properties. The trade-off: custom correlation headers are easy but don't interoperate with tracing tools.

  3. When: Candidate mentions delivery count, retries or dead-lettering Why: Checks they can diagnose poison messages and backlogs
    How to answer

    First I work out which problem I have:

    • Poison messages: a few messages always fail.
    • A failing dependency: every message fails.
    • Slow consumers: nothing fails, they just can't keep up.

    To tell them apart I use Service Bus metrics (incoming, completed, abandoned, dead-lettered), the DLQ's DeadLetterReason and DeadLetterErrorDescription, DeliveryCount, and traces grouped by exception.

    Poison messages loop when handlers catch and abandon forever, re-publish failures as new messages, or MaxDeliveryCount is huge. The fix: dead-letter permanent failures immediately, fix the handler or data, then resubmit from the DLQ in batches to an idempotent consumer. Scale consumers only up to the downstream's limit. To prevent it: alerts on oldest message age and DLQ count, plus a poison-message test. The trade-off: dead-lettering early keeps the queue flowing, but someone must own the DLQ.

🛠 Real-world problems: how you handle them

Order fulfilment failures untraceable past the Service Bus topic
Situation
An order platform [about 20,000 orders a day] published OrderPlaced to a Service Bus topic with three subscribers (fulfilment, invoicing, notifications). Fulfilment failures were reported by the warehouse hours later, and nobody could tie them to the original checkout.
Signals
Application Insights showed the checkout request ending at the Service Bus send dependency. Fulfilment exceptions appeared as separate operations with new operation_Ids. On-call spent [about 45 minutes] per incident joining them by order id in KQL.
Investigation
Checked the received messages' ApplicationProperties in Service Bus Explorer: Diagnostic-Id was present but the consumer never read it. Confirmed in the code that the processor handler started no activity, so EF Core spans parented to nothing. Ran a KQL query counting fulfilment requests with an empty operation_ParentId: 100%.
Resolution
Short term, added the order id as a span tag on both sides so on-call could pivot. Then added a publisher wrapper that injects traceparent and a processor wrapper that extracts it and starts a Consumer span; enabled the Azure SDK experimental switch for extra visibility. Delayed retries from the dead-letter queue used links instead of parents.
Prevention
An integration test with the Service Bus emulator asserts the consumer span shares the producer's trace id. A weekly KQL check reports the percentage of consumer operations without a parent or link. The messaging ADR now requires propagation in any new publisher.

How to tell it (STAR)

**S:** At [company], our fulfilment failures couldn't be connected to the customer's checkout because traces stopped at the Service Bus topic. **T:** I owned making the asynchronous path traceable end to end. **A:** I confirmed the consumers ignored the context the SDK sent, built a small publisher and processor wrapper that injects and extracts W3C trace context with Producer and Consumer spans, used links for dead-letter replays, and added an emulator test. **R:** One trace now shows checkout through all [three] consumers, and median diagnosis time for fulfilment incidents dropped from [about 45] to under [10] minutes.

↩ Usually asked after

More in Tracing

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me