Video in progress
Why does the requestId written to MDC in this filter also show up in other users' logs?
@Component
class RequestIdFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws ServletException, IOException {
String id = req.getHeader("X-Request-Id");
if (id != null) {
MDC.put("requestId", id);
}
chain.doFilter(req, res);
MDC.remove("requestId");
}
}
Tomcat threads are reused from a pool, and MDC is a ThreadLocal. There's no MDC.remove in a finally, so when an exception happens the value stays on the thread; if the next request comes without the header, logs are written with the old requestId.
📖 Answer
Two mistakes reinforce each other:
- If
chain.doFilterthrows an exception,MDC.removeis never reached, so the value stays on the thread. - When there's no header, nothing is written to MDC, meaning the old value isn't overwritten. As a result, another user's request is logged with the previous requestId, which sends incident analysis in completely the wrong direction.
The right version:
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws ServletException, IOException {
String id = Optional.ofNullable(req.getHeader("X-Request-Id"))
.filter(h -> h.length() <= 64)
.orElseGet(() -> UUID.randomUUID().toString());
MDC.put("requestId", id);
res.setHeader("X-Request-Id", id);
try {
chain.doFilter(req, res);
} finally {
MDC.remove("requestId");
}
}
This rule applies to every ThreadLocal: the tenant context, the current language, your own "request context" classes. Wherever there's a thread pool, the code that did a set must clean up in a finally. An uncleaned ThreadLocal isn't only a data mix-up; on redeploy it also causes a classloader leak.
In async code (@Async, CompletableFuture) MDC doesn't carry over to the new thread by itself; you copy it with a TaskDecorator. If Micrometer Tracing is wired in, it puts traceId into MDC and clears it itself, so you may not need your own filter.
Sign up to mark studied questions and save your progress.