ASP.NET Core Interview Question #170

What is correlation ID and why is it useful?

Logging, Error Handling & Background Services Mid-Level Intermediate

Quick Interview Answer

A correlation ID is an identifier used to associate logs and operations that belong to the same request or distributed workflow.

Detailed Explanation

A correlation ID is an identifier used to associate logs and operations that belong to the same request or distributed workflow.

ASP.NET Core already exposes a request trace identifier, and distributed tracing systems use trace/span identifiers. Applications can also accept or generate a correlation identifier when integration requirements call for one.

Including the identifier in structured logs makes it much easier to reconstruct what happened across middleware, services, database operations, and downstream calls.

Code Example

app.Use(async (context, next) =>
{
    var correlationId =
        context.Request.Headers["X-Correlation-ID"].FirstOrDefault()
        ?? context.TraceIdentifier;

    using (logger.BeginScope(
        new Dictionary<string, object>
        {
            ["CorrelationId"] = correlationId
        }))
    {
        await next();
    }
});