Quick revision
The short answer
A custom tenant scope hides the tenant in thread-bound state, which breaks in async code unless the context is propagated everywhere, and it creates a copy of each scoped bean per tenant, so memory grows with the number of tenants and nobody is sure when those instances should die. In most cases stateless singletons that take the tenant id as a parameter or read it from a context object are simpler, and per-tenant resources such as data sources belong in an explicit registry bean keyed by tenant id. A custom scope is justified only if many beans really need per-tenant state.
What to remember
In this answer, we evaluated a custom tenant scope. It hides the tenant in thread-bound state, so async code fails or, worse, uses another tenant's instance unless context is propagated everywhere; it multiplies scoped beans by the number of tenants and needs an invented lifetime policy. Stateless singletons that take the tenant id explicitly, plus a registry bean for real per-tenant resources such as data sources, are simpler and safer, and a scope is justified only when many beans need per-tenant state and the other conditions hold.
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.
A custom tenant scope hides the tenant in thread-bound state, which breaks in async code unless the context is propagated everywhere, and it creates a copy of each scoped bean per tenant, so memory grows with the number of tenants and nobody is sure when those instances should die. In most cases stateless singletons that take the tenant id as a parameter or read it from a context object are simpler, and per-tenant resources such as data sources belong in an explicit registry bean keyed by tenant id. A custom scope is justified only if many beans really need per-tenant state.
Why this question is asked
Multi-tenant systems constantly need per-tenant things: a configuration, a data source, a rate limiter, a cache. A custom Spring scope that gives each tenant its own instance of some beans looks elegant, because the code keeps injecting ordinary beans and the right instance appears by magic. Interviewers ask us to evaluate the proposal because the answer shows whether we can see the hidden costs of magic in concurrency, memory and lifecycle. In this answer, we will see how the proposed scope would work, examine its problems, look at two alternatives, and finally decide when a scope is worth it.
1How the Proposed Tenant Scope Would Work
The team would implement Spring's Scope interface. Its get() method reads the current tenant id from a ThreadLocal, set by a web filter at the start of each request, and returns the instance of the bean stored for that tenant, creating it the first time. Beans such as TenantConfig, PricingRules or a TenantCache would be declared with @Scope("tenant") and a scoped proxy, so singletons can inject them and each call is routed to the current tenant's instance.
It is worth noting what problem this solves: some beans need state that differs per tenant, and the team wants to avoid passing the tenant id around. Both goals are reasonable; the question is the price.
2Problem 1: Hidden Thread-Bound State
The scope works only if the tenant is bound to the thread when the proxy is called. That is true in a request thread after the filter has run. It is false on an @Async thread, in a CompletableFuture stage, in a Kafka listener, in a scheduled job, in a parallel stream and in reactive code. In each of those places, either the call fails because no tenant is bound, or, worse, a pooled thread still holds a tenant from earlier work, and the call silently uses another tenant's instance. In a multi-tenant system, that is a data leak.
We can propagate the tenant across every boundary with task decorators, context propagation libraries and message headers, and we would need to do that anyway. But the scope makes the dependency invisible: a reader of PricingService sees an injected PricingRules and has no idea it depends on thread state, so new async code breaks it without anyone noticing.
3Problem 2: Memory and Unclear Lifetime
A tenant scope keeps one instance of every scoped bean for every tenant that has been seen. With 5 scoped beans and 2,000 tenants, that is 10,000 instances. If one of them is a cache of 2 MB, the cache alone needs 4 GB per application instance, most of it for tenants who were active once last week. And when should a tenant's instances be destroyed? A request scope ends with the request and a session scope with the session, but a tenant never ends. The scope must invent a policy, such as eviction after idle time, and then handle the case where an instance is evicted while a request is still using it, and run destruction callbacks for resources it holds.
| Concern | Custom tenant scope | Parameter or context | Registry bean |
|---|---|---|---|
| Tenant visible in code | no | yes (parameter) | yes (lookup by id) |
| Works in async code | only with propagation | parameter: always | always, id passed |
| Memory per tenant | every scoped bean | none | only real resources |
| Lifetime policy | must be invented | not needed | explicit eviction |
| Testing | needs scope set up | plain unit tests | fake registry |
4Alternative 1: Stateless Singletons With an Explicit Tenant
Most per-tenant behaviour is really per-tenant data. Pricing rules, feature flags and limits are values that can be looked up by tenant id. So the services stay ordinary stateless singletons and receive the tenant id as a method parameter, or read it from a small framework-neutral context object set at each entry point. The data they need comes from a store or a cache keyed by tenant id.
Notice that the memory problem becomes an ordinary cache sizing problem, with a bounded cache such as Caffeine with a maximum size and expiry, and the async problem disappears for anything that receives the tenant as a parameter.
5Alternative 2: A Registry for Per-Tenant Resources
Some things really are per-tenant resources: a database connection pool per tenant for database-per-tenant isolation, an HTTP client with tenant-specific credentials, a rate limiter. For these, an explicit registry bean is clearer than a scope. It is a singleton that maps tenant id to the resource, creates resources on demand, evicts idle ones, and closes them properly. Spring's AbstractRoutingDataSource is a ready-made example for data sources, routing each connection request to a target data source by a lookup key that we derive from the current tenant.
The registry makes the important things explicit: which resources are per tenant, how many exist, when they are closed, and how a tenant id reaches them. It is also easy to monitor, for example by exposing the number of open pools as a metric.
6When a Custom Scope Is Justified
A tenant scope can be justified when many beans, not two or three, really hold per-tenant state that cannot be expressed as data in a keyed store, when the code base already propagates tenant context reliably across every thread boundary, and when the number of tenants is small and fixed, so memory and lifetime are not open questions. Even then, the scope should fail loudly when no tenant is bound, and tests should cover async paths. In most systems none of these conditions hold, so I would recommend explicit tenant ids with a registry for real resources.
7Follow-up questions
How would you route database connections per tenant?
With AbstractRoutingDataSource, overriding determineCurrentLookupKey() to return the tenant id from the current context, and a map of target data sources per tenant, or with Hibernate's multi-tenancy support, which asks a CurrentTenantIdentifierResolver for the tenant and a MultiTenantConnectionProvider for connections. Both still depend on the tenant being known on the current thread, so the entry points must set it.
Is ThreadLocal tenant context always bad?
No. A ThreadLocal set and cleared by each entry point adapter is a common and reasonable way to carry cross-cutting context, such as tenant for logging or routing. The problem is hiding beans' identity behind it, and forgetting propagation at thread boundaries. Clearing it in a finally block and propagating it with a task decorator are the minimum.
How would you test for cross-tenant leaks?
Run concurrent requests for several tenants and assert each response contains only that tenant's data, and run async tasks on a single-thread executor for tenant A followed by tenant B, asserting B never sees A's context. Adding the tenant id to every log line and audit record also helps detect leaks in production.
8Conclusion
In this answer, we evaluated a custom tenant scope. It hides the tenant in thread-bound state, so async code fails or, worse, uses another tenant's instance unless context is propagated everywhere; it multiplies scoped beans by the number of tenants and needs an invented lifetime policy. Stateless singletons that take the tenant id explicitly, plus a registry bean for real per-tenant resources such as data sources, are simpler and safer, and a scope is justified only when many beans need per-tenant state and the other conditions hold.
Open with
I would push back on the tenant scope in most cases. It makes the code look simple, but it hides the tenant in thread-bound state: the scope's get reads a ThreadLocal, so it works on the request thread and breaks on @Async threads, CompletableFutures, Kafka listeners or scheduled jobs.
Then, if they want more
Either there is no tenant and it fails, or a pooled thread still has an old tenant and we silently use another tenant's instance, which is a data leak.
It also multiplies memory: every scoped bean exists once per tenant, so 5 beans and 2,000 tenants is 10,000 instances, and there is no natural end of life for a tenant, so we would have to invent eviction and cleanup.
My alternatives are, first, stateless singletons that take the tenant id as a parameter or read it from a neutral context object, with per-tenant data in a bounded cache keyed by tenant.
Second, for real per-tenant resources like data sources or clients, an explicit registry bean that maps tenant id to the resource and handles creation, eviction and closing; AbstractRoutingDataSource is an example.
I would only accept a custom scope if many beans truly hold per-tenant state, the tenant count is small and the context is already propagated everywhere, and I would still require tests for async paths.
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
- Spring Framework reference, Core technologies
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 team proposes a custom 'tenant' scope so that each tenant gets its own instance of...": https://scrivio-interview-library.netlify.app/spring-boot/bean-scopes/94f2a4aaaa/