Quick revision
The short answer
Extract the tenant id from the JWT in a filter, store it in a request-scoped holder and clear it when the request ends. Then let Hibernate apply it everywhere, with a @TenantId column and a CurrentTenantIdentifierResolver, or a Hibernate filter enabled for each session, so filtering is not left to individual queries. Guard against native queries, bulk updates and reports that bypass the automatic filter, tenant context that leaks between pooled threads or is lost in async tasks, and prove isolation with two-tenant tests, adding database row-level security as a safety net.
What to remember
In this answer, we captured the tenant from the JWT in a filter and cleared it in a finally block, let Hibernate 6 apply it automatically with @TenantId and a CurrentTenantIdentifierResolver, and saw the filter alternative and its limits. We reviewed native queries, bulk updates and reports that bypass automatic filtering, carried the tenant into async work with a TaskDecorator, proved isolation with two-tenant tests and added PostgreSQL row-level security as a safety net.
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.
Extract the tenant id from the JWT in a filter, store it in a request-scoped holder and clear it when the request ends. Then let Hibernate apply it everywhere, with a @TenantId column and a CurrentTenantIdentifierResolver, or a Hibernate filter enabled for each session, so filtering is not left to individual queries. Guard against native queries, bulk updates and reports that bypass the automatic filter, tenant context that leaks between pooled threads or is lost in async tasks, and prove isolation with two-tenant tests, adding database row-level security as a safety net.
Why this question is asked
In a shared-schema multi-tenant service, every customer's rows live in the same tables, separated only by a tenant_id column. That makes the service cheap to run, but it means one forgotten WHERE clause shows one customer's data to another, which is among the worst bugs a SaaS product can have. Interviewers ask this coding question to see whether we make isolation automatic and know where the automation stops. In this answer, we will capture the tenant from the token, apply it with Hibernate's @TenantId, look at the filter alternative, go through the queries that bypass it, handle threads and async work, and finish with tests and row-level security.
1Capturing the Tenant From the JWT
A JWT, JSON Web Token, is the signed token the client sends with each request. Spring Security validates it and exposes its claims through the Authentication. We read the tenant claim once per request and put it in a holder that the data layer can read. A ThreadLocal works for classic thread-per-request servers, as long as we always clear it, because servlet threads are pooled and the next request on the same thread must not inherit the previous tenant.
Notice the finally block. Without it, an exception in the request would leave acme on the thread, and an unauthenticated request served next by that thread could read acme's data. The filter must also run after Spring Security's authentication filter, so the Authentication is already set.
2Letting Hibernate Apply the Tenant Everywhere
Hibernate 6 has built-in support for a discriminator column. We mark the tenant field with @TenantId and give Hibernate a CurrentTenantIdentifierResolver that returns the current tenant. Hibernate then adds the tenant condition to the queries it generates for that entity, and fills the column automatically when we persist a new row.
Notice the fallback value. Returning null or an empty string could fail in surprising ways; returning a tenant id that owns no rows means a request without a tenant sees nothing, which is the safe failure. The alternative is a Hibernate filter, declared with @FilterDef and @Filter on the entity and enabled on each session with the tenant as a parameter, for example in an aspect around repository calls. Filters work on older Hibernate versions but must be enabled reliably, and they are not applied when an entity is loaded directly by id, so @TenantId is the better default on Hibernate 6 and 7.
3Queries That Bypass the Automatic Filter
Automatic filtering covers queries Hibernate generates from entities. Native SQL queries are passed to the database as written, so a @Query(nativeQuery = true) without a tenant condition returns every tenant's rows. Bulk updates and deletes, reporting queries through JdbcTemplate, and database views used by reports deserve the same suspicion; test how your Hibernate version treats each kind before relying on it.
So we review these explicitly. A simple rule helps: every native query and JdbcTemplate call on a tenant table must take the tenant as a parameter, and a test or a lint check searches for native queries on tenant tables that do not mention tenant_id.
4Threads, Async Work and Leaks
A ThreadLocal belongs to one thread. When a request hands work to @Async methods, a thread pool or a CompletableFuture, the worker thread has no tenant, or worse, the stale tenant of whatever task it ran before if someone forgot to clear it. So we copy the tenant explicitly. In Spring, a TaskDecorator on the executor captures the tenant on the calling thread and sets and clears it around the task on the worker thread.
On Java 25, ScopedValue is a cleaner fit for this kind of context: it is bound for a block of code, cannot be left behind, and is inherited by structured subtasks. Either way, the rule is the same: the tenant must be set on entry to any unit of work and removed on exit.
6 messages in order. Play them, or step through them one at a time.
Set on entry, clear on exit, on every thread that does tenant work.
5Testing Isolation and Adding a Safety Net
The most valuable test is simple: create data for two tenants, act as tenant A, and check that nothing of tenant B comes back, through every repository method, including native queries and async paths. Running it against a real PostgreSQL with Testcontainers makes sure the SQL is real.
As a final safety net, PostgreSQL row-level security can enforce the tenant in the database itself. A policy such as USING (tenant_id = current_setting('app.tenant_id')) is enabled on each tenant table, and the application sets app.tenant_id at the start of each transaction with SET LOCAL or set_config. Then even a native query that forgets the condition only sees the current tenant's rows. Note that table owners bypass RLS unless FORCE ROW LEVEL SECURITY is set, so the application should connect as a non-owner role.
6Follow-up questions
Why not just add tenantId to every repository method?
Because it relies on every developer remembering it in every query forever, and one mistake leaks data. Automatic filtering makes the safe behaviour the default; explicit parameters are kept only for the queries the automation cannot see.
What should happen if a request arrives without a tenant claim?
It should be rejected before reaching the data layer, for example with a 401 or 403 from the security configuration. The resolver's fallback to a tenant that owns no rows is a second line of defence, not the plan.
Can an admin user see several tenants?
Yes, but as an explicit, audited path: a separate admin service or role that switches the tenant context deliberately for each operation, rather than a way to turn the filter off globally.
7Conclusion
In this answer, we captured the tenant from the JWT in a filter and cleared it in a finally block, let Hibernate 6 apply it automatically with @TenantId and a CurrentTenantIdentifierResolver, and saw the filter alternative and its limits. We reviewed native queries, bulk updates and reports that bypass automatic filtering, carried the tenant into async work with a TaskDecorator, proved isolation with two-tenant tests and added PostgreSQL row-level security as a safety net.
Open with
I would make tenant filtering automatic and then guard the places where the automation stops. A filter that runs after Spring Security reads the tenant claim from the JWT and puts it in a TenantContext, and clears it in a finally block, because servlet threads are pooled and a leaked tenant would show one customer's data to the next request.
Then, if they want more
In the data layer I would use Hibernate 6's @TenantId on the entities with a CurrentTenantIdentifierResolver that reads the context, so Hibernate adds tenant_id to generated queries and sets it on insert; if there is no tenant, the resolver returns an id that owns no rows.
A Hibernate filter enabled per session is the alternative, but it is easier to forget and does not apply to loads by id. Then I review the bypasses: native queries, bulk updates and JdbcTemplate reports must take the tenant explicitly, with a check that flags native queries on tenant tables without tenant_id.
For async work I add a TaskDecorator that copies the tenant to the worker and clears it afterwards, or use ScopedValue on Java 25. Finally, I write tests with two tenants that check every repository method returns only the current tenant's rows, and add PostgreSQL row-level security as a safety net.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Hibernate 6, 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
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "In a shared-schema multi-tenant Spring Boot service, the tenant id comes from a JWT...": https://scrivio-interview-library.netlify.app/databases/database-scaling/2eb76b5fa8/