Multi-tenancy gets explained as a database design question — separate database, separate schema, or shared tables with a tenant_id. In practice, the hard part isn't the storage choice. It's making sure no query ever accidentally returns another tenant's rows.

This post is about the shared-schema approach in Spring Boot and Hibernate: how to wire it so that isolation is automatic, and the five places where the safety net has holes.

Why shared schema

Model Isolation Operational cost Migration cost
Database per tenant Strongest High Per-tenant
Schema per tenant Strong Medium-high Per-tenant
Shared schema, tenant_id Application-enforced Low Once

If you're a small team running your own product, the first two models mean your job is database operations: dozens of connections, dozens of migrations, per-tenant backups, per-tenant restores. The shared schema means one migration, one connection pool, one backup job.

The price is that isolation is now your code's responsibility. So make it automatic.

The four pieces

1. A tenant context carried by the request

public final class TenantContext { private static final ThreadLocal<Long> CURRENT = new ThreadLocal<>(); public static void set(Long tenantId) { CURRENT.set(tenantId); } public static Long get() { return CURRENT.get(); } public static void clear() { CURRENT.remove(); } } 

2. A filter that establishes it

@Component public class TenantContextFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { try { Long tenantId = resolveTenant(request); TenantContext.set(tenantId); chain.doFilter(request, response); } finally { TenantContext.clear(); // never skip this } } } 

Resolve the tenant from the authenticated user, not from a client-supplied header. A header is fine for a slug used in a public page URL, but it must never be the thing that decides which rows a logged-in user can read.

3. A Hibernate filter on every tenant-scoped entity

@Entity @FilterDef(name = "tenantFilter", parameters = @ParamDef(name = "tenantId", type = Long.class)) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class Booking { @Column(name = "tenant_id", nullable = false) private Long tenantId; } 

4. Something that turns the filter on

@Aspect @Component public class TenantFilterAspect { @PersistenceContext private EntityManager em; @Before("execution(* com.example.app..*Service.*(..))") public void enableTenantFilter() { Long tenantId = TenantContext.get(); if (tenantId == null) { return; // platform admin path, handled explicitly } Session session = em.unwrap(Session.class); session.enableFilter("tenantFilter").setParameter("tenantId", tenantId); } } 

That's the happy path. Now the parts that bit me.

Pitfall 1: unique constraints forget the tenant

The first real bug was a duplicate-key error that shouldn't have existed.

slug is unique per tenant. email is unique per tenant — the same person can be a customer of two shops. If the database has UNIQUE(email) instead of UNIQUE(tenant_id, email), the second shop's registration fails with a constraint violation that looks like a code bug.

Every unique index on a tenant-scoped table needs tenant_id as its first column. Go through them once, early, before you have data. Retrofitting this with production rows is a much worse afternoon.

Pitfall 2: @Async and @Scheduled lose the ThreadLocal

ThreadLocal is tied to the thread. The moment a task goes async, the tenant is gone — and the filter is not applied, so the query happily returns every tenant's rows or none at all.

Two options:

  • Pass the tenant id as an explicit parameter and set TenantContext inside the task, clearing it in a finally.
  • Use TaskDecorator to copy the value into the executor's thread before the task runs.

I used the first, because it makes the dependency visible in the method signature. For scheduled jobs that must process all tenants, I loop over tenants and set the context per iteration — clarity beats cleverness here.

Pitfall 3: native queries bypass the filter

Hibernate's @Filter applies to HQL and Criteria. @Query(nativeQuery = true), JdbcTemplate, and plain JDBC do not get it.

This matters when you reach for native SQL for a reason that seemed good at the time — bulk status updates, ON DUPLICATE KEY UPDATE, a TRUNCATE. Either add WHERE tenant_id = :tenantId by hand every time, or restrict native queries to a small set of audited repository methods that all take the tenant id as a required argument.

I learned this the hard way: a status update written as native SQL to avoid a Hibernate caching issue worked correctly, but only because the caller already had the right id. Nothing in the query enforced it.

Pitfall 4: the platform admin needs a documented bypass

Someone has to see all tenants: the platform panel that lists, suspends, and evicts tenants.

That means an explicit, narrow escape hatch — not "the filter is off when there's no tenant in context", which is the accidental version. The accidental version is how an unauthenticated request ends up reading everything.

What worked:

  • Public endpoints that resolve a tenant by slug set the context themselves, after validating the tenant's status.
  • Platform endpoints are on a separate path, require ROLE_PLATFORM_ADMIN, and are the only place allowed to query without a tenant filter.
  • Anything else with a null tenant context throws instead of silently returning unscoped data.

Pitfall 5: cross-tenant rules are not covered by row filters

Row filters protect reads and scoped writes. They don't protect business rules that span rows, such as "the same email can book only one appointment per day at this shop". Two concurrent requests can both pass the check before either writes.

Options, in increasing cost:

  1. Accept it. It's a low-frequency business-rule leak that a human can fix.
  2. Enforce with a unique index that encodes the rule.
  3. Serialize on a lock or use a transactional outbox.

I used an optimistic @Version on the booking row, which solves the same-slot race, and accepted the day-limit race as a rare, visible, manually correctable case. Being honest about which races you've solved and which you've accepted is more useful than assuming the filter covers everything.

When not to use this

If you have a handful of enterprise tenants with contractual data-residency requirements, or you need per-tenant restore of a single tenant's data, shared schema will hurt. Row-level backups restore everyone or nobody. That's a real limitation, not a documentation footnote.

For a self-hosted product where one operator runs one installation for many small shops, it's the right trade.

Summary

  • Resolve the tenant from auth, filter automatically, and clear the context in finally.
  • Put tenant_id first in every unique index.
  • Treat @Async, @Scheduled, and native SQL as known holes, and handle them explicitly.
  • Give the platform admin one named bypass, not a general "no tenant means no filter".
  • Decide which cross-row business rules you enforce and which you accept.

I'm building Skeduvo, a self-hosted booking and scheduling system that uses this exact model — one installation, unlimited tenants, full source code. The platform admin panel mentioned above is part of what's included.

Questions about the filter setup are welcome in the comments.