Quick revision
The short answer
The most likely bug is that the filter clears the ThreadLocal after chain.doFilter() returns, but not in a finally block, so when a request throws, the clearing line is skipped and the tenant id stays on the pooled Tomcat thread. The next request served by that thread reads the stale tenant id. Async processing can cause the same symptom, because work handed to other threads does not see the ThreadLocal and code may fall back to a stale value. The fix is to set the value in a try, call remove() in finally, fail closed when the tenant is missing, and add a test that throws inside the filter chain and checks the next request.
What to remember
In this answer, we saw that Tomcat reuses worker threads, so a ThreadLocal value outlives the request that set it. A filter that clears the tenant after chain.doFilter() without finally leaves it behind whenever a request throws, and the next request on that thread can read it. Async code can show the same symptom when it falls back to a stale value. We fixed it with set in try and remove() in finally, made tenant reads fail closed, and wrote a test that throws in the chain and checks the next request.
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.
The most likely bug is that the filter clears the ThreadLocal after chain.doFilter() returns, but not in a finally block, so when a request throws, the clearing line is skipped and the tenant id stays on the pooled Tomcat thread. The next request served by that thread reads the stale tenant id. Async processing can cause the same symptom, because work handed to other threads does not see the ThreadLocal and code may fall back to a stale value. The fix is to set the value in a try, call remove() in finally, fail closed when the tenant is missing, and add a test that throws inside the filter chain and checks the next request.
Why this question is asked
A tenant id leaking between requests is not a performance bug, it is a data breach: one customer can see another's data. It appears occasionally, cannot be reproduced on demand, and usually passes every functional test, which is why it reaches production. Interviewers ask this question to see whether we can reason about thread reuse in a servlet container and spot the one missing keyword. In this answer, we will recap how Tomcat reuses threads, find the bug in the filter, look at the async variant, write the fix and a fail-closed check, and finish with a test that proves the fix.
1A Quick Recap: Thread Reuse in Tomcat
Tomcat, like other servlet containers, does not create a thread per request. It keeps a pool of worker threads, 200 by default in Spring Boot, and each request is handled by whichever thread is free. When the request finishes, the thread goes back to the pool and soon handles a completely different request, possibly from a different customer.
A ThreadLocal value belongs to the thread, not to the request. So anything set on a worker thread during one request is still there when the same thread picks up the next request, unless something removes it. A static ThreadLocal makes this easy to forget, because the variable looks like a global that is reset by our code.
2Finding the Bug in the Filter
Here is the kind of filter described in the question.
6 messages in order. Play them, or step through them one at a time.
The value belongs to the thread, and the thread outlives the request.
Notice that the clearing line is correct when everything works, which is why tests pass. It is only skipped when chain.doFilter() throws, which happens for the occasional failing request. The leaked value then waits on that one thread, and it causes harm only if a later request on the same thread does not overwrite it, for example one without the header, or a code path that reads the tenant before the filter runs. That is why the symptom is rare and random.
3Also Check Asynchronous Processing
The same symptom can come from work that runs on other threads. If a controller returns a CompletableFuture, uses @Async, or uses servlet async processing, part of the request runs on a different thread, where TENANT.get() returns that thread's value: null if nothing ever set it, or a stale tenant if a previous task on that pool thread leaked one. Code that falls back to a default, such as a cached last tenant, turns null into a wrong tenant.
So during the investigation we look for every place the tenant is read, and check which thread it runs on. Values must be passed explicitly to async work, or copied with a TaskDecorator that sets them on the worker and removes them afterwards.
4The Fix: try/finally and Fail Closed
We set the value, run the chain inside try, and remove the value in finally, so every path out of the filter clears it, including exceptions. And we make reads fail closed: if there is no tenant, we refuse the request instead of guessing.
Failing closed matters as much as finally. With it, even if some future code path forgets to bind the tenant, the result is an error, not another customer's data. In a real system the tenant should come from the authenticated identity, not a raw header, but the ThreadLocal discipline is the same. Spring Security's own context holder clears itself in a finally block for exactly this reason.
5Proving the Fix With a Test
A test should reproduce the exact sequence: a request that throws, then a request on the same thread. With MockMvc, requests run on the test thread, so two requests in a row naturally share one thread, which is exactly what we want here.
Depending on configuration, MockMvc may rethrow the controller's exception instead of returning 500; in that case the test catches it and continues. The key assertions stay the same: the value is gone and a request without a tenant is refused.
6Follow-up questions
Why is remove() better than set(null) here?
Both stop the leak of the tenant itself, but remove() deletes the map entry instead of keeping an entry with a null value. It is the documented way to end a ThreadLocal's use and avoids leaving entries behind on pool threads.
Would virtual threads remove the problem?
With one new virtual thread per request, a value left behind would not reach the next request, because threads are not reused. But async handoffs still lose the value, and relying on thread disposal instead of explicit cleanup is fragile. Scoped values, final in Java 25, bind a value for a scope and unbind it automatically, which removes this class of bug for code that can use them.
Where else should tenant context be checked?
At every async boundary, such as @Async methods, message listeners and scheduled jobs, and in database access, where a row-level security policy or a mandatory tenant filter gives a second layer of protection if the context is ever wrong.
7Conclusion
In this answer, we saw that Tomcat reuses worker threads, so a ThreadLocal value outlives the request that set it. A filter that clears the tenant after chain.doFilter() without finally leaves it behind whenever a request throws, and the next request on that thread can read it. Async code can show the same symptom when it falls back to a stale value. We fixed it with set in try and remove() in finally, made tenant reads fail closed, and wrote a test that throws in the chain and checks the next request.
Open with
My first suspect is the clearing code. Tomcat reuses its worker threads, and a ThreadLocal value belongs to the thread, not the request. If the filter calls chain.doFilter and then TENANT.remove on the next line, without a finally, any request that throws skips the remove.
Then, if they want more
The tenant id stays on that pooled thread, and the next request on the same thread that doesn't set its own value, say one without the header, or code that reads the tenant before the filter, sees the previous customer's tenant.
That explains why it's occasional: it needs a failure followed by the right kind of request on the same thread. I'd also check async processing, because work on @Async or CompletableFuture threads doesn't see the request thread's ThreadLocal, and if code falls back to some default or a stale pool-thread value, you get the same symptom.
The fix is to set the tenant, run the chain inside try, and call remove in finally. I'd also make reading the tenant fail closed: if it's missing, throw or return an error, never guess. And for async work, pass the tenant explicitly or use a TaskDecorator that sets and removes it.
Finally, I'd add a test that sends a request that throws, then a second request on the same thread without a tenant, and asserts the ThreadLocal is empty and the request is refused.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 25
- 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
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
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 "A servlet filter stores the current tenant id in a static ThreadLocal and clears it at...": https://scrivio-interview-library.netlify.app/java/threads/399c270707/