Video in progress
What is wrong with this filter, and how does it show up in prod?
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws ServletException, IOException {
String userId = currentUserId(req); // null if anonymous
if (userId != null) {
MDC.put("userId", userId);
}
chain.doFilter(req, res);
}
The MDC isn't being cleared. Tomcat threads are reused, so the userId carries over to the next request, and the logs of a guest user show someone else's ID.
📖 Answer
The problem has two layers.
The first: there is no MDC.remove. The MDC works on a ThreadLocal, and Tomcat runs requests in a pool of around 200 threads. User A's request ran on thread exec-12, and userId=1001 stayed behind. Then an anonymous request came to exec-12: the if didn't fire, and the old value stayed. In the log, the anonymous request is written under userId=1001.
The second: if chain.doFilter throws an exception, any cleanup code added without a finally doesn't run.
When debugging this is very misleading: you get the false picture "user 1001 logged in from 3 places at the same time". In an audit or security review, it's a serious mistake.
The correct version:
try {
if (userId != null) {
MDC.put("userId", userId);
}
chain.doFilter(req, res);
} finally {
MDC.remove("userId");
}
MDC.clear() works too, but it also wipes values set by other filters, so it is safer to remove the key you set yourself. SLF4J 2 has MDC.putCloseable, which you can use with try-with-resources.
Sign up to mark studied questions and save your progress.