IC Improve Code Recipes

Recipe 4.3 · C#

Correlation IDs Across Requests and Services

Problem

Under load, log lines from many requests interleave. A failure in the payment service shows up seconds after the web front end logged "checkout started," and nothing ties the two together. You end up matching timestamps by hand across two servers whose clocks disagree.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: an ID generated per call and passed by hand.
string requestId = Guid.NewGuid().ToString();
Logger.Write(requestId + " Checkout started");
_paymentClient.Charge(order, requestId); // every signature grows

The improved recipe

Accept or create one correlation ID per incoming request, push it into the logging scope, echo it in the response, and forward it on outgoing HTTP calls.

C#
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace ImproveCode.Logging;

public sealed class CorrelationIdMiddleware(
    RequestDelegate next,
    ILogger<CorrelationIdMiddleware> logger)
{
    public const string HeaderName = "X-Correlation-ID";

    public async Task InvokeAsync(HttpContext context)
    {
        string id = ReadOrCreate(context.Request);
        context.TraceIdentifier = id;

        context.Response.OnStarting(() =>
        {
            context.Response.Headers[HeaderName] = id;
            return Task.CompletedTask;
        });

        var scope = new Dictionary<string, object>
        {
            ["CorrelationId"] = id
        };

        using (logger.BeginScope(scope))
        {
            await next(context);
        }
    }

    private static string ReadOrCreate(HttpRequest request)
    {
        string? incoming = request.Headers[HeaderName];
        if (IsSafe(incoming))
        {
            return incoming!;
        }

        return Activity.Current?.TraceId.ToString()
            ?? System.Guid.NewGuid().ToString("N");
    }

    // Callers control the header, so accept only short, plain IDs.
    private static bool IsSafe(string? value) =>
        !string.IsNullOrEmpty(value)
        && value.Length <= 64
        && value.All(c => char.IsAsciiLetterOrDigit(c)
                          || c == '-' || c == '_');
}

public sealed class CorrelationIdHandler(
    IHttpContextAccessor accessor) : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken ct)
    {
        string? id = accessor.HttpContext?.TraceIdentifier;
        if (id is not null &&
            !request.Headers.Contains(CorrelationIdMiddleware.HeaderName))
        {
            request.Headers.Add(CorrelationIdMiddleware.HeaderName, id);
        }

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

public static class CorrelationIdExtensions
{
    public static IApplicationBuilder UseCorrelationId(
        this IApplicationBuilder app) =>
        app.UseMiddleware<CorrelationIdMiddleware>();
}

Registration, as a usage snippet in Program.cs:

C#
builder.Services.AddHttpContextAccessor();
builder.Services.AddTransient<CorrelationIdHandler>();
builder.Services.AddHttpClient<PaymentClient>()
    .AddHttpMessageHandler<CorrelationIdHandler>();

app.UseCorrelationId();      // before request logging
app.UseSerilogRequestLogging();

How it works

BeginScope with a dictionary attaches CorrelationId to every log event written anywhere in that request, by any class, without changing a single method signature. Serilog's Enrich.FromLogContext() (from Recipe 4.2) turns scope values into properties. The built-in console provider shows them too when IncludeScopes is on.

If the caller sent an ID, the middleware reuses it, so one ID follows a transaction from the browser through the API to the downstream service. If not, it uses the W3C trace ID from Activity.Current, which ASP.NET Core creates for every request and which distributed tracing tools already understand. A GUID is the last fallback.

The header is client input, so it gets validated. An attacker who can put 10 KB of text or a line break into your logs can forge log entries or blow up your log bill. Short, ASCII, letters, digits, dashes and underscores is enough for any real ID.

OnStarting sets the response header just before headers are sent, which works even when a later middleware short-circuits the request. Support staff can ask a user for the ID shown on an error page and find the whole request in seconds.

The DelegatingHandler forwards the ID on every call made through IHttpClientFactory, so the receiving service logs under the same ID.

Variations and pitfalls

  • Register the middleware early, before request logging and exception handling, so those log events carry the ID too.
  • Show the ID on your error page and in ProblemDetails responses (Chapter 5). "Send me the reference number" beats "what time did it happen?"
  • For background jobs there is no request. Open a scope per job run with a RunId (Recipe 4.6).
  • For message queues, put the ID in a message header when publishing and open a scope with it in the consumer.
  • If you adopt OpenTelemetry tracing end to end, the W3C traceparent header does this job for you. The middleware still helps for callers that are not instrumented.