Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a servlet filter in Spring Boot that adds a request id to the MDC for logging and removes it afterwards.

We extend Spring's OncePerRequestFilter and override doFilterInternal: read the incoming X-Request-Id header or generate a UUID, call MDC.put("requestId", id), set the id on the response header, and call filterChain.doFilter(request, response) inside a try block whose finally removes the MDC entry, because the container reuses threads and a leftover id would be logged for the next request. We register the filter as a @Component with an order before Spring Security, or with a FilterRegistrationBean when we need to control the order and URL patterns.

Why this question is asked

When a production problem is reported, the first thing we want is every log line for that one request, across every class it passed through. A request id in the logging context gives us exactly that, and it is one of the most common filters written in Spring Boot services. Interviewers ask for it because a short filter shows whether we understand thread reuse, the filter chain and response headers. In this answer, we will recap the MDC, write the filter, see the bug that appears without finally, register and order the filter, and add the id to the response.

1A Quick Recap of the MDC

MDC, Mapped Diagnostic Context, is a feature of SLF4J and its logging back ends such as Logback and Log4j 2. It is a map of key-value pairs attached to the current thread. Anything we put into it can be printed by the log pattern on every log line written by that thread, without passing the value to each log call.

Because the MDC is stored per thread, it fits the servlet model, where one request runs on one worker thread from start to end. But the container reuses those threads for later requests, which is the detail the finally block exists for.

2Writing the Filter

OncePerRequestFilter is a Spring base class that guarantees the filter runs only once per request, even when the request is forwarded or included internally. We override doFilterInternal.

Java
@Component
@Order(Ordered.HIGHEST_PRECEDENCE) // before Spring Security, so rejected requests get an id too
public class RequestIdFilter extends OncePerRequestFilter {
static final String HEADER = "X-Request-Id";
static final String MDC_KEY = "requestId";
private static final Pattern SAFE = Pattern.compile("[A-Za-z0-9-]{1,64}");
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String incoming = request.getHeader(HEADER);
String id = (incoming != null && SAFE.matcher(incoming).matches())
? incoming // keep the caller's id: one id across services
: UUID.randomUUID().toString(); // 3f2b9c1e-...
MDC.put(MDC_KEY, id);
response.setHeader(HEADER, id); // set before the body is written
try {
filterChain.doFilter(request, response);
} finally {
MDC.remove(MDC_KEY); // the thread goes back to the pool clean
}
}
}

Notice three choices. We accept an incoming id so that a request passing through several services keeps one id, but only if it matches a safe pattern, because a header is user input and an attacker could otherwise inject line breaks or huge values into our logs. 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 removal is in finally, so it happens even when the request throws.

3Showing the Id in the Logs

The MDC value appears only if the log pattern asks for it. With Spring Boot's default Logback setup, the simplest change is the level part of the pattern, which Boot exposes as a property.

Properties
# application.properties
logging.pattern.level=%5p [%X{requestId:-}]
# Output for one request:
# INFO [3f2b9c1e-8a7d-4c1b-9e2f-1d0a6b5c4e3f] 4242 --- [nio-8080-exec-3] c.e.OrderController : listing orders
# INFO [3f2b9c1e-8a7d-4c1b-9e2f-1d0a6b5c4e3f] 4242 --- [nio-8080-exec-3] c.e.OrderService : 12 orders found

%X{requestId} reads the key from the MDC, and :- gives an empty default for log lines outside a request, such as startup messages. In JSON logging setups, MDC entries are usually included as fields automatically.

4What Goes Wrong Without finally

If we wrote MDC.remove after doFilter without a finally block, any exception thrown by the controller would skip the removal. The worker thread would return to the pool still holding that request's id. The next request on the same thread that does not set an id, for example a request served by a path the filter skips, or log lines from code that runs on that thread before our filter, would be logged with the old request's id. Two unrelated requests then look like one in the logs, which is worse than having no id at all.

Step throughWhy the id must be removed in finally
Worker threadRequestIdFilterController
request A arrives
MDC.put(requestId, A)
chain.doFilter
throws an exception
finally: MDC.remove(requestId)
thread returns to the pool, MDC empty
request B arrives on the same thread: gets its own id

7 messages in order. Play them, or step through them one at a time.

Without finally, the exception skips the removal and B's early log lines carry A's id.

5Registering and Ordering the Filter

Spring Boot registers any Filter bean with the embedded container automatically, mapped to all URLs. The @Order annotation controls where it runs; Spring Security's filter sits at -100 by default, so HIGHEST_PRECEDENCE puts our filter before it, and even a 401 from security gets logged with an id.

When we need more control, such as limiting the filter to /api/* or setting an explicit order without an annotation, we declare a FilterRegistrationBean instead, and drop @Component from the class so it is not registered twice.

Java
@Bean
FilterRegistrationBean<RequestIdFilter> requestIdFilter() {
FilterRegistrationBean<RequestIdFilter> reg = new FilterRegistrationBean<>(new RequestIdFilter());
reg.setOrder(Ordered.HIGHEST_PRECEDENCE);
reg.addUrlPatterns("/api/*");
return reg;
}

6Follow-up questions

What about work done on other threads, such as @Async methods?

The MDC is per thread, so a task submitted to an executor does not see the request's id. We copy it with a TaskDecorator: capture MDC.getCopyOfContextMap() on the request thread, set it with MDC.setContextMap in the task's thread before running, and clear it afterwards. Spring's ThreadPoolTaskExecutor accepts a TaskDecorator, and with Micrometer context propagation, tracing context can be propagated automatically across many async boundaries.

Should we use Micrometer Tracing instead?

For services that already use tracing, yes, or at least as well. With Micrometer Tracing on the classpath, Spring Boot puts traceId and spanId into the MDC for each request and propagates them to downstream calls through standard headers. A custom request id filter is still common when a business-facing id is wanted in responses.

How do we test the filter?

With MockMvc: perform a request with and without the X-Request-Id header and assert the response header, for example that a valid incoming id is echoed and an invalid one is replaced by a UUID. A unit test can also call doFilter with a mock chain that checks MDC.get("requestId") during the call and assert that it is null afterwards.

7Conclusion

In this answer, we wrote a request id filter by extending OncePerRequestFilter: it reads a validated X-Request-Id header or generates a UUID, puts it into the MDC, sets it on the response header before the body is written, calls the chain, and removes the MDC entry in finally so pooled threads do not carry it to the next request. We printed it with %X{requestId}, ordered the filter before Spring Security with @Order, and saw that FilterRegistrationBean gives control over order and URL patterns.

What to say in the interviewAbout 90 seconds aloud

Open with

I would extend Spring's OncePerRequestFilter so it runs once per request, and override doFilterInternal. First I read the X-Request-Id header; if it is present and matches a safe pattern, like letters, digits and dashes up to 64 characters, I keep it so the id follows the request across services, otherwise I generate a UUID.

Then, if they want more

Validating matters because the header is user input going into logs. Then I call MDC.put("requestId", id) and set the same id on the response header. I set the header before calling the chain, because once the controller writes the body the response can be committed and headers are ignored.

Then I call filterChain.doFilter inside try, and in finally I call MDC.remove("requestId"). The finally is essential, because the container reuses worker threads, and if an exception skipped the removal, the next request on that thread could log with the old id. To see it in logs, I add %X{requestId} to the pattern, for example with logging.pattern.level in Spring Boot.

For registration, the simplest is @Component with @Order(Ordered.HIGHEST_PRECEDENCE), which puts it before Spring Security at minus 100, so rejected requests get an id too. If I need URL patterns or explicit ordering, I use a FilterRegistrationBean and drop the @Component so it is not registered twice.

For async work I would copy the MDC with a TaskDecorator, and in services with Micrometer Tracing I would also rely on the traceId it puts into the MDC.

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
Jakarta EE specifications
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 "Write a servlet filter in Spring Boot that adds a request id to the MDC for logging and...": https://scrivio-interview-library.netlify.app/java/servlets/450787c496/