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.
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.
"HTTP propagation is free in .NET because
HttpClientwritestraceparentand 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 withActivityKind.Producer, then use OpenTelemetry'sPropagators.DefaultTextMapPropagator.Injectto write the W3C headers intoServiceBusMessage.ApplicationProperties. On the consumer side, in theServiceBusProcessorhandler, IExtractfrom the received message's properties and start anActivityKind.Consumeractivity 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-Idproperty intraceparentformat, and it can emit its own send and process spans, but for messaging that is still behind theAzure.Experimental.EnableActivitySourceswitch. I turn it on and addAddSource("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
ActivityLinkto 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'."
| 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 |
| 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) |
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.
Checks that the candidate can make traces survive an asynchronous hop with correct span kinds, semantic conventions and parent-vs-link judgement.
Green flags
Inject/Extract with ApplicationPropertiesRed flags
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).
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.
Diagnostic-Id application property in W3C traceparent format (from Activity.Current).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.If you write traceparent yourself as well, extract traceparent first and fall back to Diagnostic-Id.
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).
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.
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.
Inject/Extract and confirm one trace.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());
StartActivity. Why it is wrong: the consumer span parents to Activity.Current (usually none), starting a new trace. Instead: pass parent.ActivityContext as parentContext.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.ActivityLink.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.AddException and SetStatus(Error) before rethrowing.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 |
I host a ServiceBusProcessor in a BackgroundService, with ServiceBusClient as a singleton using DefaultAzureCredential. I set AutoCompleteMessages = false and settle explicitly:
DeliveryCount rises and the broker redelivers; after MaxDeliveryCount it dead-letters automatically.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.
Two mechanisms work together.
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.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.
First I work out which problem I have:
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.
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.
Last updated 23 Nov 2026.