LESSON 7 OF 12

7. Correlation ID, Trace ID, and Log Context

Build middleware that accepts or generates an X-Correlation-ID and propagates it to response headers, Serilog LogContext, and downstream HttpClient calls. Explore the relationship between correlation, trace, and span identifiers.

45 dk 83

Introduction

In a distributed ASP.NET Core system, one request often crosses several services, databases, or external APIs. Searching only the local application logs is not enough to understand the complete journey of a user request. We need to identify which services handled it, which child operations were created, and which downstream calls were initiated.

This lesson separates three related but different identifiers: Correlation ID, Trace ID, and Span ID. A Correlation ID is an application-level key that can be used by support and business operations. A Trace ID identifies one end-to-end distributed trace. A Span ID identifies one operation or child operation inside that trace.

We will build middleware that reads an incoming X-Correlation-ID header and generates a new value when the header is missing or invalid. The middleware will add the value to the response header, place it in Serilog LogContext, and propagate it to another service through a typed HttpClient.

1. The conceptual foundation: three identifiers, three purposes

IdentifierPurposeExample
Correlation IDRelate requests for application support and operations01J8F7M6J3R4N8X2Q5Z1ABCD9E
Trace IDIdentify the complete distributed trace4bf92f3577b34da6a3ce929d0e0e4736
Span IDIdentify one operation or service step within a trace00f067aa0ba902b7

With W3C Trace Context, a TraceId is 16 bytes and a SpanId is 8 bytes. ASP.NET Core and HttpClient can automatically propagate this context through the traceparent header when the appropriate diagnostics and OpenTelemetry configuration are present. Therefore, a Correlation ID does not have to contain the same value as a TraceId.

For example, a customer support ticket may contain an X-Correlation-ID. The trace associated with that request can include retries, several service calls, or a new technical trace boundary. Instead of merging the two concepts, keep them as separate fields in log events.

2. Preparing the project

Assume that Serilog was configured in the previous lessons with Enrich.FromLogContext():

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .CreateLogger();

builder.Host.UseSerilog();

Without FromLogContext(), properties pushed with LogContext.PushProperty will not be written to log events. For downstream calls, define a typed client and a delegating handler:

builder.Services.AddTransient<CorrelationIdHandler>();
builder.Services.AddHttpClient<CatalogClient>(client =>
{
    client.BaseAddress = new Uri("https://localhost:7202");
})
.AddHttpMessageHandler<CorrelationIdHandler>();

3. Validating the Correlation ID

Do not automatically accept every header value sent by a client. Extremely long values, control characters, or unexpected formats can pollute logs and create header-processing problems. This example accepts values between 8 and 64 characters containing letters, digits, hyphens, and underscores. Adapt the rule to your organization’s standard.

using System.Text.RegularExpressions;

public static class CorrelationIdValidator
{
    private static readonly Regex Pattern = new(
        "^[A-Za-z0-9_-]{8,64}$",
        RegexOptions.Compiled | RegexOptions.CultureInvariant);

    public static bool IsValid(string? value)
        => !string.IsNullOrWhiteSpace(value) && Pattern.IsMatch(value);

    public static string Create()
        => Guid.NewGuid().ToString("N");
}

When an invalid value arrives, two common choices are to reject the request with HTTP 400 or ignore the value and generate a new Correlation ID. For observability, this lesson uses the second approach so that one malformed client value cannot break log correlation across the system.

4. Building the middleware

The middleware has the following responsibilities:

  1. Read the incoming X-Correlation-ID header.
  2. Validate it and generate a new value when it is missing or invalid.
  3. Place the Correlation ID in request and response context.
  4. Add the value to Serilog’s LogContext.
  5. Add Trace ID and Span ID to the log context when an active Activity exists.
  6. Set the response header and dispose context objects in reverse order when the request ends.
using System.Diagnostics;
using Serilog.Context;

public sealed class CorrelationIdMiddleware
{
    private const string HeaderName = "X-Correlation-ID";
    private readonly RequestDelegate _next;

    public CorrelationIdMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var incoming = context.Request.Headers[HeaderName].FirstOrDefault();
        var correlationId = CorrelationIdValidator.IsValid(incoming)
            ? incoming!
            : CorrelationIdValidator.Create();

        context.Items[HeaderName] = correlationId;
        context.Response.Headers[HeaderName] = correlationId;

        var activity = Activity.Current;
        var traceId = activity?.TraceId.ToString();
        var spanId = activity?.SpanId.ToString();

        using var correlationScope = LogContext.PushProperty(
            "CorrelationId", correlationId);
        using var traceScope = LogContext.PushProperty(
            "TraceId", traceId ?? "none");
        using var spanScope = LogContext.PushProperty(
            "SpanId", spanId ?? "none");

        await _next(context);
    }
}

Pipeline order matters. If this middleware runs before request logging, request log events can also contain the Correlation ID. The exact point at which the ASP.NET Core server Activity is available can vary with pipeline and hosting details, so production systems may also choose to add trace fields through a dedicated Serilog enricher or logging integration.

var app = builder.Build();

app.UseMiddleware<CorrelationIdMiddleware>();
app.UseSerilogRequestLogging();
app.UseHttpsRedirection();
app.MapControllers();

app.Run();

5. Propagating the value through HttpClient

HttpClient can automatically propagate W3C trace context, but the custom X-Correlation-ID header is the application’s responsibility. Treat the two propagation mechanisms separately: traceparent carries technical trace context, while X-Correlation-ID carries the application correlation key.

public sealed class CorrelationIdHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var correlationId = CorrelationIdAccessor.Current;

        if (!string.IsNullOrWhiteSpace(correlationId))
        {
            request.Headers.TryAddWithoutValidation(
                "X-Correlation-ID", correlationId);
        }

        return base.SendAsync(request, cancellationToken);
    }
}

public static class CorrelationIdAccessor
{
    private static readonly AsyncLocal<string?> Value = new();

    public static string? Current
    {
        get => Value.Value;
        set => Value.Value = value;
    }
}

The middleware can set the accessor for the duration of the request:

var previous = CorrelationIdAccessor.Current;
CorrelationIdAccessor.Current = correlationId;

try
{
    await _next(context);
}
finally
{
    CorrelationIdAccessor.Current = previous;
}

In a real project, the handler could instead read the value from HttpContext.Items. However, a handler is not always called inside an HTTP request. Background services and scheduled jobs need an explicit execution-context design rather than assuming that an HttpContext exists.

6. Observing TraceId and SpanId in practice

Log the active Activity in a controller to see all three identifiers on one operation:

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    private readonly ILogger<OrdersController> _logger;
    private readonly CatalogClient _catalogClient;

    public OrdersController(
        ILogger<OrdersController> logger,
        CatalogClient catalogClient)
    {
        _logger = logger;
        _catalogClient = catalogClient;
    }

    [HttpGet("{id:int}")]
    public async Task<IActionResult> Get(int id)
    {
        var activity = Activity.Current;

        _logger.LogInformation(
            "Order lookup started for {OrderId}. TraceId={TraceId}, SpanId={SpanId}",
            id,
            activity?.TraceId.ToString(),
            activity?.SpanId.ToString());

        var item = await _catalogClient.GetItemAsync(id);
        return Ok(item);
    }
}

The server span covers controller execution. The HttpClient call can create a separate child span under the same Trace ID. Therefore, the Trace ID remains the same while the Span ID changes. The Correlation ID also remains the same as an application-level key in both services.

7. Context isolation under concurrent requests

Serilog LogContext and AsyncLocal-based values flow with the execution context. This preserves the value across await, but storing request data in global mutable static fields is dangerous. The following test checks that two requests retain separate identifiers:

[Fact]
public async Task Parallel_requests_keep_separate_correlation_ids()
{
    var first = SendAsync("request-one");
    var second = SendAsync("request-two");

    await Task.WhenAll(first, second);

    Assert.Equal("request-one", first.Result);
    Assert.Equal("request-two", second.Result);
}

private static async Task<string?> SendAsync(string value)
{
    using var client = new HttpClient();
    using var request = new HttpRequestMessage(
        HttpMethod.Get,
        "https://localhost:7100/api/orders/1");
    request.Headers.Add("X-Correlation-ID", value);

    using var response = await client.SendAsync(request);
    return response.Headers.GetValues("X-Correlation-ID").Single();
}

The sample values must satisfy the validation rule in the real test; use values of at least eight characters. Also verify that the same value is visible in the downstream service, not only in the original response.

8. Common mistakes

  • Treating Correlation ID and Trace ID as the same: one belongs to application correlation and the other to distributed tracing.
  • Failing to dispose the context: if the result of LogContext.PushProperty is not disposed, properties can leak into later log events.
  • Using a static mutable variable: parallel requests may write one user’s ID into another request’s logs.
  • Logging an unvalidated header: long or control-character values can affect log quality and security.
  • Adding the HttpClient header in every controller: this creates duplication and missed call sites; use a delegating handler.
  • Confusing trace propagation with Correlation ID propagation: even when traceparent is automatic, the custom X-Correlation-ID header must be added separately.
  • Adding the response header only for successful responses: support teams need the same identifier when diagnosing failures.

9. Short practice exercise

Complete the following exercise:

  1. Add the middleware to the existing project and verify the X-Correlation-ID response header.
  2. Send requests with a missing value, a value shorter than eight characters, and a value containing unsupported characters.
  3. Confirm that a new valid ID is generated in each case.
  4. Send a valid ID and search for the same Correlation ID in the controller log, request log, and downstream service.
  5. Find the Trace ID for the request in Jaeger or another trace interface.
  6. Observe that the server span and HttpClient span have different Span IDs but the same Trace ID.
  7. Send at least ten concurrent requests and verify that no request carries another request’s Correlation ID.

Conclusion

In this lesson, we designed Correlation ID as an application-managed, readable context key for users and operations teams. We also saw that Trace ID and Span ID are technical identifiers managed by OpenTelemetry and W3C Trace Context. Using both approaches together makes log searches, trace inspection, and cross-service failure analysis much easier.

A robust implementation validates incoming values, generates a new ID when necessary, writes it to the response header, scopes LogContext correctly, and propagates the custom header through a delegating handler. In the next stage, we will evaluate this context together with OpenTelemetry logs, traces, and metrics in centralized observability systems.

Sources