Quick revision
The short answer
We write a OncePerRequestFilter that reads the X-Correlation-Id header or generates a new id, calls MDC.put("correlationId", id) before chain.doFilter(), and calls MDC.remove("correlationId") in a finally block. The log pattern then prints it with %X{correlationId}, or structured logging includes the MDC automatically, and we return the id in a response header so clients can report it. If the service uses Micrometer Tracing, traceId and spanId are already in the MDC and we may not need our own id at all.
What to remember
In this answer, we wrote a OncePerRequestFilter that reads X-Correlation-Id or generates a UUID, validates it, puts it into the MDC before chain.doFilter() and removes it in a finally block. We printed it with %X{correlationId} in the console pattern or got it as a field from structured logging, returned it in a response header so clients can report it, and tested both the setting and the clearing. Finally, we saw that Micrometer Tracing already puts traceId and spanId into the MDC, which often makes the trace id the correlation id.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We write a OncePerRequestFilter that reads the X-Correlation-Id header or generates a new id, calls MDC.put("correlationId", id) before chain.doFilter(), and calls MDC.remove("correlationId") in a finally block. The log pattern then prints it with %X{correlationId}, or structured logging includes the MDC automatically, and we return the id in a response header so clients can report it. If the service uses Micrometer Tracing, traceId and spanId are already in the MDC and we may not need our own id at all.
Why this question is asked
When a customer says "my order failed at 10:42", we need to find every log line of that one request among thousands of others from the same minute. A correlation id written on every line makes that a single search. Interviewers ask this as a small coding task because it checks three things at once: whether we know where a request enters a Spring MVC application, whether we understand that the MDC is tied to a thread, and whether we remember to clean up. In this answer, we will recap what the MDC is, write the filter, put the id into the log pattern, return it to the client, test it, and see where Micrometer Tracing already does this for us.
1A Quick Recap of the MDC
MDC stands for Mapped Diagnostic Context. It is a small map of strings that SLF4J keeps per thread. Whatever we put into it is available to every log statement that runs on that thread afterwards, without passing it as a parameter. Logback and Log4j2 can print MDC values in the pattern, and Spring Boot's structured logging formats include them as fields.
In a classic Spring MVC application, one request is handled by one thread from Tomcat's pool from start to finish. So if we put the id into the MDC when the request arrives, every log line written while handling that request carries it. But the thread goes back to the pool afterwards and serves the next request. If we forget to remove the value, the next request on that thread starts with the previous request's id, which is worse than having no id at all.
2Writing the Filter
A servlet filter is the right place because it runs before the DispatcherServlet and therefore before every controller, interceptor and exception handler. OncePerRequestFilter, a Spring base class, guarantees that our code runs only once per request even when the request is forwarded or dispatched again internally, for example to an error page.
7 messages in order. Play them, or step through them one at a time.
Let us go through the important lines. We trust an incoming header so that an id created by a gateway or by another service is kept across hops, but we validate it first. The reason is that the value goes straight into our logs: a client could otherwise send a 10 KB header or one with line breaks to forge fake log lines. Anything that does not look like a short id is replaced by a fresh UUID.
We set the response header before calling the chain, because once the controller starts writing the body, the response may be committed and headers can no longer be added. And the remove() call sits in a finally block, so it runs whether the request succeeds, throws an exception or times out. Notice that we remove our one key instead of calling MDC.clear(), so we do not wipe values that other filters, such as tracing, have put there.
3Printing the Id on Every Log Line
Putting the id into the MDC does nothing visible until the log format prints it. With Spring Boot's default Logback setup, we can add it to the pattern through a property. With structured logging (available since Boot 3.4), the MDC is included as fields automatically.
The :-none part is a default value: lines written outside any request, such as start-up messages or scheduled jobs, print none instead of an empty pair of brackets. Structured JSON is the better choice when logs go to a platform such as Elasticsearch or Loki, because correlationId becomes a real field we can filter on instead of a piece of text we have to parse.
4Testing That It Is Set and Cleared
A small test proves both halves: the id appears in the response, and the MDC is empty after the request.
The lambda stands in for the rest of the chain and records what the MDC held while the request was being processed. The last assertion is the one that catches the classic bug of a missing finally block.
5When Micrometer Tracing Already Does It
If the application has Micrometer Tracing on the classpath, for example micrometer-tracing-bridge-brave or micrometer-tracing-bridge-otel with Spring Boot Actuator, tracing already creates a trace id for each request, or continues one from the incoming W3C traceparent header, and puts traceId and spanId into the MDC. Recent Boot versions also add them to the default log pattern through the correlation pattern setting (check your version for the exact property and format).
In that case a separate correlation id is often redundant: the trace id is the correlation id, and it also links our logs to the trace view. Teams still keep X-Correlation-Id when external clients or older systems already send it, and then it is reasonable to log both. Also remember that the MDC only follows the thread. Work handed to @Async methods, CompletableFuture or a message listener does not carry it automatically, which is a topic of its own.
6Follow-up questions
Why OncePerRequestFilter instead of a HandlerInterceptor?
A HandlerInterceptor runs inside the DispatcherServlet, after other filters such as Spring Security have already run and possibly logged. It also does not see requests that never reach a controller. A filter at the highest precedence covers the whole request, including security decisions and error dispatches, and OncePerRequestFilter makes sure it runs once even when the request is forwarded internally.
What happens if we forget MDC.remove()?
The thread goes back to Tomcat's pool with the old value still in its MDC. The next request on that thread normally overwrites it in our filter, but any code that logs before our filter, or any request that skips it, prints the previous request's id. Investigations then join unrelated requests, which is worse than having no id.
Should we trust the correlation id the client sends?
We keep it, because it lets one id follow a request across a gateway and several services, but we validate it: limit the length, allow only safe characters, and generate a new one otherwise. The value goes into logs and response headers, so an unchecked header could inject fake log lines or bloat every line.
7Conclusion
In this answer, we wrote a OncePerRequestFilter that reads X-Correlation-Id or generates a UUID, validates it, puts it into the MDC before chain.doFilter() and removes it in a finally block. We printed it with %X{correlationId} in the console pattern or got it as a field from structured logging, returned it in a response header so clients can report it, and tested both the setting and the clearing. Finally, we saw that Micrometer Tracing already puts traceId and spanId into the MDC, which often makes the trace id the correlation id.
Open with
I would put it in a servlet filter, because that is the first thing a request touches, before security, controllers and error handling. I would extend OncePerRequestFilter so it runs once even on forwards and error dispatches, and give it the highest precedence.
Then, if they want more
In doFilterInternal, I read the X-Correlation-Id header; if it is missing or does not look like a short safe id, I generate a UUID. Then I call MDC.put with the key correlationId, set the same value as a response header so the client can quote it in a support ticket, and call chain.doFilter inside a try block.
In the finally block I call MDC.remove for my key. The finally matters because Tomcat threads are pooled, and a leftover value would show up on the next request served by that thread. To make it visible, I add %X{correlationId} to logging.pattern.console, or with structured logging in Boot 3.4 and later the MDC is included as a JSON field automatically.
I would test it with MockHttpServletRequest: the id is visible inside the chain, returned in the header, and gone afterwards. And I would mention that with Micrometer Tracing, traceId and spanId are already in the MDC, so often the trace id is the correlation id.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Boot reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Add a correlation id to every log line of a request in a Spring MVC application. Show...": https://scrivio-interview-library.netlify.app/spring-boot/boot-logging/5b122ff6ed/