Skip to content

Step 09 — Trace a request across the outbox ​

What you'll do: add OpenTelemetry to both services, carry the trace context through the outbox table and a message header, and see one trace from POST /orders to the shipment in the Aspire dashboard.

The problem: a broken trace ​

Distributed tracing follows one operation across services. Each step is a span (a named, timed piece of work); spans that belong together share a trace id. Over HTTP, .NET passes the trace id along automatically in the traceparent header.

The outbox breaks that chain twice. The request that saves the order ends before the publisher runs, on another thread, maybe in another instance. And the message goes through RabbitMQ, which knows nothing about traces. Without help you get three unrelated traces: the request, the publish, and the consumer.

The fix is context propagation by hand: store the trace context in the outbox row, send it as a message header, and start the next span from it on the other side.

Steps ​

  1. Add the packages to Directory.Packages.props:

    xml
    <PackageVersion Include="Npgsql.OpenTelemetry" Version="10.0.4" />
    <PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.21.0" />
    <PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.21.0" />
    <PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.21.0" />

    Reference all four from Orders.Api.csproj, and all but the ASP.NET Core one from Shipping.Worker.csproj.

  2. Add the Aspire dashboard to docker-compose.yml. It is a standalone container that receives OpenTelemetry data and shows traces, logs and metrics; you do not need .NET Aspire in your projects to use it.

    yaml
    aspire-dashboard:
      image: mcr.microsoft.com/dotnet/aspire-dashboard:13.6.5
      environment:
        DASHBOARD__FRONTEND__AUTHMODE: Unsecured # no login token: fine on your own machine, never on a server
      ports:
        - "18888:18888" # dashboard UI
        - "4317:18889"  # OTLP over gRPC, where the apps send traces and logs
    bash
    docker compose up -d --wait
  3. Store the trace context in the outbox. In OutboxMessage.cs:

    csharp
    public string? TraceParent { get; init; }
    
    public static OutboxMessage Create<T>(string type, T payload, DateTimeOffset occurredAt) => new()
    {
        // ...
        TraceParent = Activity.Current?.Id,
    };

    In .NET a span is an Activity. Activity.Current is the span of the HTTP request, and its Id is the W3C traceparent string, such as 00-aa7a886c53d0cd80c2b4b5f986842a97-c3f443353f1a2d3e-03 (version, trace id, span id, flags). Limit the column to 55 characters in OrdersDbContext.cs and add a migration:

    bash
    dotnet ef migrations add AddOutboxTraceParent --project src/Orders.Api --output-dir Data/Migrations
  4. Start a producer span per message in OutboxPublisher.cs, with the stored context as its parent, and send its id as a header. The ActivitySource lives in OutboxTelemetry.cs.

    csharp
    ActivityContext.TryParse(message.TraceParent, traceState: null, out var parent);
    using var activity = OutboxTelemetry.Source.StartActivity($"{message.Type} publish", ActivityKind.Producer, parent);
    activity?.SetTag("messaging.system", "rabbitmq");
    activity?.SetTag("messaging.destination.name", exchange);
    activity?.SetTag("messaging.message.id", message.Id.ToString());
    
    var properties = new BasicProperties
    {
        // ...
        Headers = activity?.Id is { } traceParent ? new Dictionary<string, object?> { ["traceparent"] = traceParent } : null,
    };
  5. Start a consumer span from that header in OrderPlacedConsumer.cs (source in InboxTelemetry.cs):

    csharp
    using var activity = InboxTelemetry.Source.StartActivity(
        $"{delivery.RoutingKey} process", ActivityKind.Consumer, ParentContext(delivery));
    csharp
    private static ActivityContext ParentContext(BasicDeliverEventArgs delivery)
    {
        // RabbitMQ.Client delivers string header values as UTF-8 bytes.
        var traceParent = delivery.BasicProperties.Headers?.TryGetValue("traceparent", out var value) == true && value is byte[] bytes
            ? Encoding.UTF8.GetString(bytes)
            : null;
        return ActivityContext.TryParse(traceParent, traceState: null, out var context) ? context : default;
    }

    Failures set activity?.SetStatus(ActivityStatusCode.Error, ...) so they show in red.

  6. Turn on OpenTelemetry in the API's Program.cs:

    csharp
    builder.Logging.AddOpenTelemetry(logging =>
    {
        logging.IncludeFormattedMessage = true;
        logging.IncludeScopes = true;
    });
    builder.Services.AddOpenTelemetry()
        .ConfigureResource(resource => resource.AddService(builder.Environment.ApplicationName))
        .WithTracing(tracing => tracing
            .AddAspNetCoreInstrumentation()
            .AddNpgsql()
            .AddSource(OutboxTelemetry.SourceName))
        .UseOtlpExporter();

    and only trace SQL that is part of something bigger, so the publisher's poll every second does not create a trace of its own:

    csharp
    .UseNpgsql(
        builder.Configuration.GetConnectionString("Orders") ?? throw ...,
        npgsql => npgsql.ConfigureDataSource(dataSource => dataSource
            .ConfigureTracing(tracing => tracing.ConfigureCommandFilter(_ => Activity.Current is not null))))

    The worker's Program.cs does the same, with AddSource(InboxTelemetry.SourceName) and without the ASP.NET Core instrumentation.

  7. Point both apps at the dashboard in their appsettings.json (API, worker):

    json
    "OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4317",

Check it works ​

bash
dotnet build OutboxInbox.slnx -warnaserror
dotnet run --project src/Shipping.Worker
dotnet run --project src/Orders.Api
curl -X POST localhost:5080/orders -H 'content-type: application/json' \
  -d '{"customerEmail":"alex@contoso.com","items":[{"sku":"BOOK-1","quantity":2},{"sku":"MUG-7","quantity":1}]}'

The outbox row now carries the trace context:

bash
docker compose exec postgres psql -U postgres -d orders -tAc \
  "select trace_parent from outbox_messages order by occurred_at desc limit 1"
00-aa7a886c53d0cd80c2b4b5f986842a97-c3f443353f1a2d3e-03

Open http://localhost:18888/traces. There is one trace named Orders.Api: POST /orders/ with spans from both resources, Orders.Api and Shipping.Worker. Open it (your span counts can differ by one: a CONNECT span appears only when the connection pool opens a new connection):

The Aspire dashboard shows one trace: POST /orders in Orders.Api with its database calls, then the RabbitMQ publish to the orders exchange, then the Shipping.Worker processing span on shipping.order-placed with its two inbox queries

Read it from top to bottom: the HTTP request and its INSERT of the order and outbox row; about a second later (the polling interval) the publish to the orders exchange; then the worker's processing span with the inbox check and the insert of the inbox row and shipment. The dashboard shows messaging spans as MSG rabbitmq <destination>, from the messaging.* tags.

Structured logs in the dashboard shows the log lines of both services; click a trace id there to jump to the trace.

Why it works ​

OpenTelemetry is the vendor-neutral standard for traces, metrics and logs. The apps send data over OTLP (the OpenTelemetry protocol) to a collector or backend. Here that is the Aspire dashboard; in production it could be Azure Monitor, Grafana, Jaeger or Honeycomb, with no code change, only a different OTEL_EXPORTER_OTLP_ENDPOINT.

ActivitySource and ActivityKind. .NET implements OpenTelemetry spans with System.Diagnostics.Activity. An ActivitySource creates them; AddSource(...) tells the SDK to listen to it. ActivityKind.Producer and Consumer mark the two ends of a message, which tools use to draw the hop between services.

Three hops of context. The request's context goes into the trace_parent column (a hop through the database), the publisher's span id goes into the traceparent message header (a hop through the broker), and the consumer parses it back. Each side calls StartActivity with an explicit parent, so the spans join the original trace even though they run much later and elsewhere.

Parent or link. This guide makes the publish span a child of the request, which gives one readable tree. When one publish carries many requests' messages, or a consumer handles a batch, OpenTelemetry suggests span links instead, which connect traces without nesting them.

Why filter SQL tracing. Without the command filter, every poll of the outbox (once per second per instance) and every startup query would be a trace with a single span, burying the useful ones. With it, SQL is traced only inside a request or a message span. The filter covers commands, not connection opens: while PostgreSQL is down, each failed poll still shows up as a one-span CONNECT orders trace. That is useful during an outage; if you would rather not see it, add .EnablePhysicalOpenTracing(false) to the same ConfigureTracing call.

MIT licensed. Every step is a commit: git checkout step-01.