Scrivio Interview library
LeadershipPrincipal7 min read · updated 12 November 2026

Your multi-tenant platform has used thread-bound context and custom scopes for tenant data for ten years. With virtual threads and more async code, how would you rethink tenant context handling?

Thread-bound tenant context has always needed explicit propagation across thread pools, async calls and reactive code, and more async work makes that gap bigger. Virtual threads keep ThreadLocal working but remove the value of per-thread caches, since each task tends to get its own thread, and Java's scoped values, final in Java 25, offer bounded, immutable context that suits tenant ids well. The clearest option remains passing the tenant id explicitly through service methods, so I would plan a gradual migration towards explicit ids and scoped values, guarded by tests for context leaks between tenants.

Why this question is asked

A platform that has relied on ThreadLocal tenant context and custom scopes for ten years has a lot of code that quietly assumes one thread handles one request from start to finish. That assumption is weakening: teams adopt virtual threads, CompletableFuture chains, reactive clients and messaging. Interviewers ask this at the most senior level because the answer is a strategy, not a code change: we need to judge what still works, what is risky, what the Java platform now offers, and how to migrate a large codebase safely. In this answer, we will look at what thread-bound context assumes, what virtual threads change, what scoped values offer, why explicit ids remain the clearest option, and how to plan the migration.

1What Thread-Bound Context Assumes

The old design sets the tenant id in a ThreadLocal when a request starts, custom scopes read it to pick per-tenant bean instances, and everything below reads it implicitly. This works when one thread runs the whole unit of work. Every time work moves to another thread, the context must be carried across explicitly: a TaskDecorator for executors, context propagation for Reactor, headers for messages. Anywhere that is forgotten, the code sees no tenant, or a stale tenant left on a pooled thread by earlier work. Ten years of growth usually means some boundaries are covered and some are not, and nobody has a complete list.

More async code multiplies those boundaries. A request that used to run on one thread may now fan out into five parallel calls, each on a different thread, and each a place where the tenant can be lost or leak.

2What Virtual Threads Change

Virtual threads, final since Java 21, are cheap threads managed by the JVM, so we can afford one per task. ThreadLocal still works on them exactly as before, so existing code keeps running. Two things change. First, per-thread caches lose their value. Code that stored expensive objects in a ThreadLocal so each pooled platform thread could reuse them, such as formatters, buffers or per-thread tenant caches, now creates them for every task, because each virtual thread usually runs one task and then ends. With a million virtual threads, those caches can also use a lot of memory, so we should find them and replace them with shared thread-safe objects or bounded caches.

Second, virtual threads encourage more concurrency inside a request, such as running several calls in parallel, and a new virtual thread does not inherit ordinary ThreadLocal values from the thread that started it. So adopting virtual threads tends to create more places where tenant context must be propagated, not fewer. Leaks between tenants through stale pooled threads become less likely, since virtual threads are not reused, but missing context becomes more likely.

3What Scoped Values Offer

Scoped values, a preview in Java 21 to 24 and final in Java 25 (check your Java version), are designed for exactly this kind of context. A ScopedValue is bound to a value for the duration of a call, is immutable inside it, and is automatically unbound when the call returns, so there is nothing to clear and nothing to leak. Child threads created by structured concurrency inherit the binding, which makes fan-out within a request safe; structured concurrency itself is still a preview API in Java 25. Ordinary executors do not inherit scoped values, so pools still need explicit hand-over.

Java
static final ScopedValue<TenantId> TENANT = ScopedValue.newInstance();
// Entry point (HTTP filter, Kafka adapter, job launcher)
ScopedValue.where(TENANT, TenantId.of("acme")).run(() -> orders.handle(request));
// Anywhere below, on this thread
TenantId t = TENANT.get(); // acme
boolean bound = TENANT.isBound(); // true inside run(), false after it returns
// After run() returns, TENANT.isBound() is false: no cleanup code, no stale tenant
Ways to carry tenant context
ApproachAsync safetyLeak riskVisibility in code
ThreadLocal + custom scopeneeds propagation everywherestale values on pooled threadshidden
ThreadLocal set/cleared at edgesneeds propagationlow if always clearedhidden
ScopedValue (Java 25)inherited by structured tasks onlynone after the scopehidden but bounded
Explicit tenant parameteralways worksnonevisible in signatures
Explicit ids are the clearest; scoped values are the best implicit option.

Notice the shape: the binding is a block, so it is impossible to forget to remove it, and code inside cannot change the tenant halfway through. Compared with ThreadLocal, that removes the two most common bugs, stale values and accidental overwrites.

4Why Explicit Tenant Ids Remain the Clearest Option

Passing the tenant id as a parameter through service methods works on every thread, in every async style, in reactive pipelines and across messages, with no propagation machinery at all. It makes every tenant-dependent method visible, which helps reviews and security audits, and it makes tests trivial. The cost is changing many signatures, and some cross-cutting code, such as logging, metrics and data source routing, genuinely benefits from implicit context. So a reasonable target state is explicit tenant ids in business code, and scoped values for the cross-cutting infrastructure that cannot easily take a parameter.

5Planning the Migration

A ten-year codebase cannot be rewritten at once, so we plan it in stages and measure progress. First, we inventory: every ThreadLocal holding tenant data, every custom scope, every thread boundary, and every per-thread cache, found with code search and static analysis. Second, we add safety nets before changing anything: tests that run concurrent requests for several tenants and assert no cross-tenant data, tests that run tasks for tenant A then tenant B on a single-thread executor, and the tenant id on every log line and audit record so leaks are detectable in production.

Third, we introduce a single tenant context API owned by the platform team, so that its implementation can move from ThreadLocal to ScopedValue in one place once services run on Java 25. Fourth, we replace custom tenant scopes with stateless singletons and registry beans, one bean at a time, and move business services to explicit tenant parameters, starting with the most security-sensitive paths such as data access and authorisation. Throughout, a build rule stops new direct ThreadLocal tenant access, and a dashboard tracks the remaining uses.

Step throughMigrating tenant context handling
  1. Inventory ThreadLocals, scopes, boundariesand per-thread caches
  2. Add leak tests and tenant in logssafety nets first
  3. One platform tenant context APIThreadLocal now, ScopedValue on Java 25
  4. Replace custom scopessingletons plus registry beans
  5. Explicit tenant ids in business codesecurity-sensitive paths first
  6. Direct ThreadLocal uses left?
    YesNext serviceNoDone; keep build rule

6 steps in order. Play them, or step through them one at a time.

Safety nets come before any change, and each step is measurable.

6Follow-up questions

Do virtual threads make ThreadLocal tenant context unsafe?

Not unsafe, since ThreadLocal works the same way on virtual threads. They make it less sufficient: new virtual threads started for parallel work do not see the parent's ThreadLocal values, and per-thread caches lose value. Stale tenant values on reused threads become less likely because virtual threads are not pooled, but code that still runs on platform thread pools keeps that risk.

Can we use scoped values with Spring today?

Yes, on Java 25 where they are final, by binding the value at entry points such as a servlet filter or a listener adapter and reading it in infrastructure code. Spring's own context propagation does not manage our scoped values for us, so hand-over to executors must be explicit, and frameworks may add support over time; check your Spring version.

How do you justify the migration cost to the business?

With risk and incidents: a cross-tenant data leak is one of the most serious failures a multi-tenant platform can have, and thread-bound context is a common cause. Showing that the safety-net tests found real leaks, or that async features are slowed by propagation bugs, usually makes the case. Doing it gradually, tied to normal feature work and Java upgrades, keeps the cost manageable.

7Conclusion

In this answer, we saw that ten years of ThreadLocal context and custom tenant scopes rely on one thread doing all the work, which more async code steadily breaks. Virtual threads keep ThreadLocal working but make per-thread caches pointless and add new boundaries, scoped values in Java 25 give bounded, immutable context that cannot leak, and explicit tenant ids remain the clearest option for business code. We planned a gradual migration: inventory, leak tests first, one platform context API, replacing scopes with singletons and registries, and explicit ids in the most sensitive paths.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start by being honest about what thread-bound context assumes: one thread runs the whole unit of work. Every async call, thread pool, reactive chain or message is a boundary where the tenant must be propagated explicitly, and after ten years some boundaries are covered and some are not.

Then, if they want more

More async code makes that worse. Virtual threads do not break ThreadLocal, it works the same, but per-thread caches lose their value because each task gets its own thread, and new virtual threads for parallel work do not inherit the context, so we need to find those caches and boundaries.

Java 25 makes scoped values final: the tenant is bound for a block of code, immutable inside it and gone afterwards, so there is nothing to clear and nothing to leak, and structured concurrency children inherit it. Still, the clearest option is passing the tenant id explicitly through service methods, because it works everywhere and is visible in reviews.

So my plan would be: inventory all ThreadLocals, scopes and boundaries; add leak tests and the tenant on every log line before changing anything; put tenant context behind one platform API that can switch to scoped values; replace custom scopes with stateless singletons and registry beans; and move business code to explicit ids, security-sensitive paths first, with a build rule and a dashboard to track progress.

About this answer

Last updated
12 November 2026
Versions it names
Java 25, Java 21
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.
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 "Your multi-tenant platform has used thread-bound context and custom scopes for tenant...": https://scrivio-interview-library.netlify.app/spring-boot/bean-scopes/1f7de4c8ef/