Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

In a multi-tenant Spring Boot application using a shared database with a tenant_id column, how would you make sure every query is filtered by tenant?

We resolve the tenant once per request from the authenticated user's token in a filter and keep it in a request-scoped holder, then let the persistence layer add the tenant condition automatically, with Hibernate's @TenantId on a field in Hibernate 6 or a Hibernate filter, instead of trusting every developer to write it. PostgreSQL row-level security with a session variable set per connection or transaction is an alternative or an extra safety net. The tenant context must be cleared after each request, especially with thread pools, and tests should actively try to read another tenant's data.

Why this question is asked

In a shared-database SaaS application, every customer's rows sit in the same tables, separated only by a tenant_id column. One query that forgets WHERE tenant_id = ? shows one company's invoices to another, which is about the worst incident a B2B product can have. Interviewers ask this because the good answer is not be careful; it is to build the filter into the framework and the database so that forgetting is hard. In this answer, we will see how a leak happens, resolve the tenant safely, let Hibernate add the filter, add row-level security in PostgreSQL, clear the context correctly with thread pools, and write tests that try to break isolation.

1How a Tenant Leak Happens

Picture an orders table with a tenant_id column. A developer writes a repository method to find orders by status for a dashboard, and forgets the tenant condition. Nothing fails; the tests pass because the test database has one tenant. In production, the dashboard shows every tenant's orders.

Java
interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByStatus(String status); // no tenant condition: returns all tenants' orders
}
orderRepository.findByStatus("OPEN"); // tenant 7 sees 1,204 orders, its own are 31

The lesson is that isolation cannot depend on each query being written correctly. It must be applied automatically, in one place, for every query.

2Resolving the Tenant Once per Request

The tenant must come from something the user cannot forge. After Spring Security has authenticated the request, the token, for example a JWT with a tenant_id claim signed by our identity provider, tells us the tenant. We never take it from a plain request header or a URL parameter, because a client can change those.

A filter that runs after authentication reads the claim and stores it in a holder for the duration of the request. A ThreadLocal, a variable with a separate value per thread, is the usual choice, because in the classic servlet model one thread handles one request from start to finish. The finally block is the most important line: it clears the value when the request ends.

Java
public class TenantFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
Jwt jwt = (Jwt) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
TenantContext.set(Long.valueOf(jwt.getClaimAsString("tenant_id"))); // e.g. 7
try {
chain.doFilter(req, res);
} finally {
TenantContext.clear(); // always, even on errors
}
}
}

3Letting Hibernate Add the Tenant Condition

Hibernate 6 has built-in support for this pattern. We mark the tenant column in each entity with @TenantId and tell Hibernate how to find the current tenant by implementing CurrentTenantIdentifierResolver. Hibernate then adds the tenant restriction to queries for that entity and fills in the tenant id when we persist a new one, so findByStatus above becomes safe without any change.

Java
@Entity
class Order {
@Id @GeneratedValue Long id;
@TenantId Long tenantId; // set on insert, restricted on queries
String status;
}
@Component
class TenantResolver implements CurrentTenantIdentifierResolver<Long>, HibernatePropertiesCustomizer {
public Long resolveCurrentTenantIdentifier() { return TenantContext.getOrDefault(-1L); } // -1 matches no rows
public boolean validateExistingCurrentSessions() { return true; }
public void customize(Map<String, Object> props) {
props.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, this);
}
}
orderRepository.findByStatus("OPEN"); // ... where o.status = ? and o.tenant_id = ? -> 31 orders

Notice the default of -1 when no tenant is set, for example in a background job that forgot to set one. It matches no rows, so a mistake returns nothing rather than everything. Two limits are worth knowing. Native SQL queries are not rewritten, so they must include the condition themselves, and how lookups by id are covered has changed across Hibernate versions, so check your version; the tests in the last section are what prove it. Before Hibernate 6, or for more complex rules, a Hibernate @Filter with a tenant parameter, enabled on every session, gives a similar result.

4A Database Safety Net: Row-Level Security

For stronger protection, PostgreSQL can enforce isolation itself with row-level security, RLS. We enable it on the table and create a policy that only allows rows whose tenant_id equals a session setting. Even a hand-written native query, or a reporting tool connected as the application user, then cannot see other tenants' rows.

SQL
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY; -- applies to the table owner too
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id')::bigint);
-- at the start of every transaction, from the application
SELECT set_config('app.tenant_id', '7', true); -- true: local to this transaction
SELECT count(*) FROM orders; -- 31, only tenant 7
Step throughLayers that keep tenants apart
  1. Signed tokentenant_id claim from the identity provider
  2. Tenant filtersets TenantContext, clears it in finally
  3. Hibernate @TenantIdadds the tenant condition to entity queries
  4. PostgreSQL row-level securitypolicy on app.tenant_id, set per transaction
  5. Isolation teststry to read another tenant's data

5 layers, from the top down. Step through them one at a time.

Each layer catches mistakes the one above it can miss.

The third argument true makes the setting local to the transaction, which matters with a connection pool: when the connection goes back to the pool, the setting disappears, and the next borrower cannot inherit tenant 7. In Spring, we set it from a small aspect or connection hook at the start of each transaction. RLS and @TenantId together give two independent layers.

5Clearing the Context, Especially With Thread Pools

A ThreadLocal belongs to a thread, and servers reuse threads. Tomcat serves request after request on the same pool threads, so if we forget to clear the tenant, the next request on that thread may start with the previous tenant's id. That is why the filter clears in finally.

Thread pools inside the application need the same care in the other direction. Work handed to an @Async method or an executor runs on a different thread, which does not see the caller's ThreadLocal at all, or worse, sees a stale value left by an earlier task. A TaskDecorator copies the tenant into the worker thread and clears it afterwards.

Java
public class TenantTaskDecorator implements TaskDecorator {
public Runnable decorate(Runnable task) {
Long tenant = TenantContext.get(); // captured on the calling thread
return () -> {
TenantContext.set(tenant);
try { task.run(); } finally { TenantContext.clear(); }
};
}
}
// executor.setTaskDecorator(new TenantTaskDecorator());

6Tests That Try to Read Another Tenant's Data

Finally, we prove it. Integration tests, against a real PostgreSQL started with Testcontainers, create data as tenant A and then try every read path as tenant B: repository methods, REST endpoints, search and exports. A test that expects an empty result or a 404 is worth more than any code review, and it guards future queries too.

Java
@Test
void tenantBCannotSeeTenantAOrders() {
asTenant(1L, () -> orderRepository.save(new Order("OPEN")));
List<Order> seen = asTenant(2L, () -> orderRepository.findByStatus("OPEN"));
assertThat(seen).isEmpty(); // passes: filter applied
asTenant(2L, () -> mvc.perform(get("/orders/1")).andExpect(status().isNotFound()));
}

A useful extra check scans the codebase for native queries on tenant tables and fails the build if one lacks a tenant condition, unless RLS covers that table.

7Follow-up questions

Why return 404 instead of 403 when a user asks for another tenant's order?

Because 403 confirms that the order exists, which leaks information. To tenant B, tenant A's order should simply not exist.

What about background jobs that work across all tenants?

They should iterate over tenants explicitly and set the tenant context for each one, rather than running without a tenant. A small set of genuinely cross-tenant admin operations can use a separate, audited database role that bypasses RLS.

Do virtual threads change the ThreadLocal advice?

Virtual threads are not pooled, so a stale value is less likely, but work handed to other threads still loses the context, and clearing in finally is still good practice. Scoped values, finalised in Java 25, are designed for passing context like this safely.

8Conclusion

In this answer, we saw how one missing tenant condition leaks data, resolved the tenant from the signed token in a filter and kept it in a ThreadLocal cleared in finally, let Hibernate 6's @TenantId add the condition to every query with a safe default, added PostgreSQL row-level security with a transaction-local setting as a second layer, copied and cleared the context for thread pools with a TaskDecorator, and wrote tests that actively try to read another tenant's data.

What to say in the interviewAbout 80 seconds aloud

Open with

I would make the tenant filter automatic rather than relying on every query. First, a servlet filter that runs after Spring Security reads the tenant id from the signed token, never from a header the client controls, and stores it in a ThreadLocal tenant context, cleared in a finally block.

Then, if they want more

Then I would use Hibernate 6's @TenantId on the tenant column of each entity, with a CurrentTenantIdentifierResolver that reads the context. Hibernate adds the tenant restriction to queries and sets the tenant on insert. I would make the resolver return an impossible id when no tenant is set, so a mistake returns nothing instead of everything.

Native SQL is not covered, so that needs care. As a second layer I would enable PostgreSQL row-level security with a policy comparing tenant_id to a session setting, set with set_config local to each transaction, so pooled connections cannot carry the setting to the next borrower.

For thread pools and @Async, a TaskDecorator copies the tenant to the worker thread and clears it afterwards. And I would write integration tests with Testcontainers that create data as one tenant and try every read path as another, expecting nothing or a 404.

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 official documentation for the version you use. 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 "In a multi-tenant Spring Boot application using a shared database with a tenant_id...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/2f1e699e76/