Modern applications often use messaging systems to communicate between independent services. Instead of calling another service directly through HTTP, an application publishes a message to a broker such as RabbitMQ, Azure Service Bus, Kafka, or another messaging platform. A consumer receives the message and performs additional processing.
This architecture improves scalability and reduces direct dependencies between services. However, it also makes troubleshooting more difficult. A single business operation may pass through an API, a message broker, multiple consumers, background workers, and external services.
Distributed tracing helps developers follow this execution flow. It connects individual operations through trace identifiers and parent-child relationships. But tracing becomes incomplete when context is not transferred through messaging boundaries.
.NET provides built-in distributed tracing capabilities through System.Diagnostics.Activity. OpenTelemetry provides standard context propagation mechanisms that can carry trace information through message headers and properties.
In this article, we will explore how trace context propagation works, implement it in .NET messaging applications, and understand how to connect producer and consumer activities using W3C Trace Context and OpenTelemetry.
Understanding Distributed Tracing
Distributed tracing is a way to follow a request as it travels across multiple services and processes.
Consider an e-commerce application where a customer places an order. The request may follow this sequence:
The API receives an order request.
The order service validates the request.
The order service publishes an event to a message broker.
The inventory consumer updates stock information.
The payment consumer processes the payment.
The notification consumer sends a confirmation.
Each service performs a separate operation, but all operations belong to the same business workflow.
Without distributed tracing, developers may see separate log entries from each service without knowing how they are connected.
Distributed tracing assigns a trace ID to the overall operation and a span ID to each individual operation. These identifiers help monitoring systems reconstruct the execution flow.
<AsyncImage query="distributed tracing microservices message broker producer consumer trace spans architecture diagram" aspectRatio="16:9" width="100%"/>
For example, the API request and message consumer can share the same trace ID while using different span IDs. This allows developers to see how much time the request spent in the API, message broker, and consumer.
What Is Trace Context Propagation?
Trace context propagation is the process of transferring tracing information from one service or process to another.
When an application calls another service through HTTP, tracing libraries can automatically inject trace information into HTTP headers.
Messaging systems work differently. They transport messages through broker-specific properties, headers, or metadata fields.
For example, a producer might publish a message containing:
traceparent:
00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
The consumer extracts this information and uses it as the parent context for its own activity.
The trace ID remains consistent, but the consumer creates a new span ID for its processing operation.
This is important because the consumer may execute seconds or minutes after the producer has completed its work. The trace context connects both operations even though they do not run within the same process or execution thread.
Understanding W3C Trace Context
The W3C Trace Context specification defines a standard format for transferring tracing information between distributed applications.
It primarily uses two fields:
traceparent
The traceparent field identifies the position of an operation within a distributed trace.
A typical value looks like this:
00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
It contains four parts:
Part | Description |
|---|
Version | Identifies the trace context format version |
Trace ID | Identifies the complete distributed trace |
Parent ID | Identifies the operation that created the current context |
Trace flags | Contains tracing flags, including the sampled flag |
The trace ID is 16 bytes, represented by 32 hexadecimal characters. The parent ID is 8 bytes, represented by 16 hexadecimal characters.
tracestate
The tracestate field carries additional vendor-specific tracing information.
For example:
congo=t61rcWkgMzE,rojo=00f067aa0ba902b7
It is optional and can contain information used by different tracing providers.
.NET and OpenTelemetry support W3C Trace Context propagation, making it possible to connect services that use different programming languages and monitoring platforms.
Understanding Activity and ActivityContext in .NET
.NET implements distributed tracing through the System.Diagnostics namespace.
The main types developers need to understand are Activity, ActivityContext, and ActivitySource.
Activity
An Activity represents an individual operation within a distributed trace.
For example, publishing an order event or processing a payment message can each have a separate activity.
using System.Diagnostics;
using var activity = new Activity("ProcessOrder");
activity.Start();
Console.WriteLine(activity.TraceId);
Console.WriteLine(activity.SpanId);
An activity contains information such as its trace ID, span ID, parent ID, duration, and tags.
ActivityContext
ActivityContext represents the context required to connect an activity to an existing distributed trace.
It includes:
A consumer can extract an ActivityContext from message metadata and use it when starting a new activity.
ActivitySource
ActivitySource is the recommended API for creating activities that participate in .NET diagnostic tracing.
Create a shared source:
using System.Diagnostics;
public static class MessagingDiagnostics
{
public static readonly ActivitySource ActivitySource =
new("OrderMessaging");
}
The activity source can be used by producers and consumers to create meaningful spans.
Configuring OpenTelemetry in a .NET Application
OpenTelemetry provides APIs and instrumentation for collecting distributed traces and exporting them to observability platforms.
Install the required packages:
dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
Configure tracing in Program.cs:
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry()
.ConfigureResource(resource =>
resource.AddService("OrderService"))
.WithTracing(tracing =>
{
tracing
.AddSource("OrderMessaging")
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddOtlpExporter();
});
var app = builder.Build();
app.MapGet("/", () => "Order service is running");
app.Run();
This configuration registers the application's custom activity source, instruments incoming ASP.NET Core requests and outgoing HTTP calls, and exports trace data using OTLP.
The OTLP exporter requires a compatible OpenTelemetry collector or backend endpoint. Configure the endpoint and authentication according to the deployment environment.
For a messaging application, the producer and consumer processes must both configure their tracing providers to listen to the activity source and export the resulting activities.
Propagating Trace Context Through Message Headers
A messaging broker does not automatically understand every tracing implementation. The application must transfer the trace context through the broker's message metadata.
OpenTelemetry provides a TextMapPropagator abstraction for this purpose.
The propagator injects the current context into a carrier and extracts it from the carrier on the receiving side.
A simple dictionary can represent message headers in a demonstration.
Creating a message header carrier
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Context.Propagation;
public static class TraceContextHelper
{
private static readonly TextMapPropagator Propagator =
Propagators.DefaultTextMapPropagator;
public static void Inject(
ActivityContext context,
IDictionary<string, string> headers)
{
var propagationContext = new PropagationContext(
context,
context.TraceState);
Propagator.Inject(
propagationContext,
headers,
(carrier, key, value) =>
{
carrier[key] = value;
});
}
public static ActivityContext Extract(
IDictionary<string, string> headers)
{
var propagationContext = Propagator.Extract(
default,
headers,
(carrier, key) =>
{
return carrier.TryGetValue(key, out var value)
? new[] { value }
: Array.Empty<string>();
});
return propagationContext.ActivityContext;
}
}
The injection method serializes the current context into the message headers.
The extraction method reads the propagated information and reconstructs the ActivityContext.
The default OpenTelemetry propagator uses W3C Trace Context when configured with the standard default behavior.
The carrier is deliberately represented as a dictionary here. In a real application, adapt these methods to the messaging platform's native header or property collection.
Injecting Trace Context in a Message Producer
The producer creates an activity when publishing a message. It then injects the activity context into the outgoing message headers.
For example:
using System.Diagnostics;
public class OrderEventProducer
{
public async Task PublishAsync(
OrderCreatedEvent orderEvent)
{
using var activity =
MessagingDiagnostics.ActivitySource.StartActivity(
"Publish OrderCreated");
var headers = new Dictionary<string, string>();
if (activity is not null)
{
TraceContextHelper.Inject(
activity.Context,
headers);
}
var message = new BrokerMessage
{
Body = JsonSerializer.Serialize(orderEvent),
Headers = headers
};
await _messageBroker.PublishAsync(message);
}
}
The example uses an application-specific BrokerMessage and _messageBroker abstraction. Their implementation depends on the messaging platform.
When the activity is created, .NET establishes its parent from the current activity context if one exists. If the producer is handling an HTTP request, the message-publishing activity becomes a child of that request activity.
The trace context is then copied into the message headers before publishing.
If the activity source has no active listener, StartActivity may return null. In that case, no activity context is available to inject. Production tracing configuration should ensure that the source is registered when tracing is enabled.
Extracting Trace Context in a Message Consumer
The consumer reads the trace context from the message headers and creates a new activity using the extracted context as its remote parent.
using System.Diagnostics;
public class OrderEventConsumer
{
public async Task ProcessAsync(BrokerMessage message)
{
var parentContext =
TraceContextHelper.Extract(message.Headers);
using var activity =
MessagingDiagnostics.ActivitySource.StartActivity(
"Process OrderCreated",
ActivityKind.Consumer,
parentContext);
var orderEvent =
JsonSerializer.Deserialize<OrderCreatedEvent>(
message.Body);
if (orderEvent is null)
{
throw new InvalidOperationException(
"Invalid order message.");
}
await ProcessOrderAsync(orderEvent);
}
private Task ProcessOrderAsync(
OrderCreatedEvent orderEvent)
{
Console.WriteLine(
$"Processing order {orderEvent.OrderId}");
return Task.CompletedTask;
}
}
The consumer extracts the parent context and starts a new activity.
The new activity receives a new span ID but keeps the original trace ID. This creates a parent-child relationship between the producer and consumer activities.
The ActivityKind.Consumer value identifies the activity as a message-consuming operation.
If the incoming message does not contain valid trace context, extraction returns a default context. The consumer can still create a new root activity.
Configuring W3C Trace Context Explicitly
.NET uses W3C Trace Context as the default activity ID format in modern .NET versions.
However, applications that require consistent behavior across multiple processes can explicitly configure the format early in application startup:
using System.Diagnostics;
Activity.DefaultIdFormat = ActivityIdFormat.W3C;
Activity.ForceDefaultIdFormat = true;
This configuration should be applied before activities are created.
Using the W3C format makes trace identifiers compatible with the standard traceparent and tracestate fields.
Avoid mixing the older hierarchical activity ID format with W3C trace context in systems that require consistent cross-service propagation.
Handling Multiple Consumers and Parallel Processing
A single message can trigger several independent operations.
For example, an order-created event may be processed by inventory, payment, and notification consumers.
All three consumers should preserve the original trace ID, but each consumer should create its own activity.
The resulting trace may look like this:
Order API
|
+-- Publish Order Event
|
+-- Inventory Consumer
|
+-- Payment Consumer
|
+-- Notification Consumer
Each consumer can be represented by a separate span connected to the original publishing operation.
When a consumer starts additional work, the new activity should normally be created using the extracted message context.
For messaging systems where one message triggers multiple independent operations, parent-child relationships may not always describe the complete business relationship. OpenTelemetry also supports span links, which can connect activities to one or more related contexts without making them direct children.
Span links are especially useful for batch processing, fan-in operations, and workflows that combine messages from multiple traces.
Propagating Context Across Different Messaging Platforms
The exact way trace context is stored depends on the messaging technology.
Messaging platform | Typical propagation mechanism |
|---|
RabbitMQ | Message headers |
Azure Service Bus | Application properties |
Apache Kafka | Record headers |
Amazon SQS | Message attributes |
NATS | Message headers |
The general process remains the same:
Create or identify the current activity.
Inject its context into the outgoing message metadata.
Publish the message.
Extract the context when the message is received.
Create a consumer activity using the extracted context.
Export the activities to the tracing backend.
Some messaging libraries provide built-in OpenTelemetry instrumentation that performs this propagation automatically. Check the instrumentation documentation for the selected broker before implementing manual propagation.
Avoid injecting the same trace context twice or creating conflicting tracing headers.
Common Mistakes in Message Trace Propagation
Mistake | Impact | Recommended solution |
|---|
Not injecting context | Producer and consumer traces become disconnected | Inject context into message metadata |
Not extracting context | Consumer creates an unrelated trace | Extract the parent context before processing |
Creating a new root activity | Breaks the parent-child relationship | Start the consumer activity using the extracted context |
Using different propagation formats | Different services may not understand the context | Use W3C Trace Context consistently |
Overwriting message headers | Existing trace information can be lost | Preserve relevant metadata and update only required fields |
Ignoring batch processing | Relationships between multiple source messages are lost | Consider span links |
Not registering ActivitySource | Custom activities may not be collected | Register the source with OpenTelemetry |
Treating trace IDs as security tokens | Creates incorrect trust assumptions | Never use tracing identifiers for authentication or authorization |
Security and Performance Considerations
Trace context is diagnostic information, not authentication information.
An application should not trust a trace ID as proof that a message came from a particular service. Attackers may be able to create or modify tracing headers if they can publish messages.
Messaging systems must still use proper authentication, authorization, and transport security.
The tracestate field may contain vendor-specific information. Avoid placing personal information, credentials, access tokens, or sensitive business data in it.
Trace context also adds metadata to every message. Although the overhead is generally small, high-throughput messaging systems should monitor message size and serialization costs.
Sampling is another important consideration. A trace may be marked as sampled or not sampled. The sampled flag is a recording hint, not a guarantee that every downstream system will retain the trace.
Applications should also avoid creating excessive spans for extremely frequent operations. Use appropriate sampling and instrumentation boundaries to balance observability with performance.
Best Practices for Production .NET Applications
Use ActivitySource to create application-level tracing activities.
Use ActivityContext to represent and transfer trace context.
Prefer OpenTelemetry propagators instead of manually parsing W3C headers.
Inject trace context into broker-specific message metadata.
Extract context before starting consumer activities.
Use W3C Trace Context consistently across services.
Register every custom activity source with the OpenTelemetry provider.
Use span links for batch processing and operations with multiple parents.
Avoid putting sensitive information in tracestate.
Keep trace propagation separate from authentication and authorization.
Use built-in messaging instrumentation when it already handles propagation.
Monitor trace coverage, sampling, and message-processing duration.
Advantages and Disadvantages
Advantages
Connects producer and consumer operations across service boundaries.
Makes asynchronous workflows easier to troubleshoot.
Helps identify delays in message processing.
Supports interoperability through W3C Trace Context.
Works across different programming languages and messaging platforms.
Integrates with OpenTelemetry and modern monitoring systems.
Disadvantages
Requires context injection and extraction when instrumentation does not provide it automatically.
Adds metadata to messages.
Requires consistent configuration across services.
Sampling can result in incomplete traces.
Batch and fan-in processing require more careful relationship modeling.
Trace context alone does not provide message authentication or delivery guarantees.
Conclusion
Trace context propagation is essential for understanding asynchronous workflows in distributed .NET applications. Without it, producer and consumer operations may appear as unrelated activities, making it difficult to investigate delays and failures across messaging boundaries.
.NET provides Activity, ActivityContext, and ActivitySource for creating and managing tracing operations. OpenTelemetry provides standardized propagators that transfer W3C Trace Context through message metadata.
By injecting context in producers and extracting it in consumers, developers can connect messaging operations to the original request and follow business workflows across multiple services.
For production applications, combine consistent trace propagation with appropriate sampling, secure messaging, message-level observability, and span links for complex workflows. This creates a more complete view of application behavior and makes distributed systems easier to monitor and troubleshoot.
Join the conversation! Your thoughts help the community grow.