← Foundations path
.NETFoundations 25 / 37Reported by candidates

Correlation ID and trace ID

“What is a correlation ID, and how do you add one to every log line and error response?”

One id per request, on every log line and in the error the user sees, so support can find the whole story in seconds.

See it

1/5The portal sends a request with its own id in the X-Correlation-ID header: c-81f2.

In plain words

A busy API writes thousands of log lines a minute, from many requests at once, all mixed together. When a dealer reports "I got an error at 10:42", support can't tell which lines belong to that one request. A correlation id fixes this: one id per request, written on every log line the request produces and sent back in the response. The user, or the portal, shows the id in the error message; support pastes it into the log search and sees only that request's lines. If the portal already made an id, the API reuses it from a request header (often X-Correlation-ID), so one id follows the call through every service. Separately, .NET has a built-in id, the trace id. It comes from W3C Trace Context (W3C is the web standards body): the id arrives in a traceparent header, or is created, and .NET passes it on to the next service on outgoing HTTP calls by itself. files every line under it as operation_Id. Many teams use the trace id alone; others add their own correlation id because a client or an old system already sends one. Note the shapes: the traceId in a ProblemDetails is the full text 00-<32 hex>-<16 hex>-<flags> (the flags are usually -01 in production), while operation_Id is only the 32-hex middle part, so support searches with that part.

Say it in the interview

In the lending API

The middleware, run on .NET 10. Cut down: a real one also limits the id's length and characters (last follow-up). Program.cs shows where it sits; the middleware file is the detail, so the walk goes back to the start there. Tap Next line to follow c-81f2.

Lending.sln · where these 2 files sit
  • src/Api/
    • Middleware/
Diagram · step 1The portal sends a request with its own id in the X-Correlation-ID header: c-81f2.
Program.cs · line 2 · 1 of 2Adds the correlation middleware. It goes first, before the exception handler, so its scope still covers the error log line.

What they ask next

Interviewers check that you can explain every line. Tap a question to open it.

Traps

Read more: Logging in .NET: log scopes · W3C Trace Context · Application Insights: telemetry correlation