Introduction
Building a multi-tenant SaaS application requires careful planning around data isolation, security, and scalability. When multiple customers share the same application instance, ensuring that tenant data remains strictly segregated is the primary architectural challenge.
In this article, we will explore how to implement a robust multi-tenant architecture using Spring Boot. We will cover database isolation patterns, request-scoped tenant context propagation, and authorization strategies.
Tenant Isolation Strategies
Before writing any code, you must decide on your data isolation strategy. There are three common patterns in multi-tenant architecture:
- Database-per-tenant: Complete physical separation. Maximum security, higher infrastructure cost.
- Schema-per-tenant: Shared database, separate schemas. A good balance of isolation and resource efficiency.
- Shared database with tenant discriminator: All tenants share tables, distinguished by a
tenant_idcolumn. Lowest cost, highest implementation complexity.
For this guide, we will focus on the schema-per-tenant approach using PostgreSQL and Hibernate, which offers a strong isolation boundary without the overhead of managing thousands of database instances.
flowchart A["Incoming Request"] --> B["Tenant Resolution Filter"] B --> C["Tenant Context Holder"] C --> D["Hibernate Connection Provider"] D --> E["Target Database Schema"] Resolving and Propagating Tenant Context
The first step in handling a multi-tenant request is identifying the tenant. This is typically done via a subdomain (e.g., tenant1.app.com) or an HTTP header (X-Tenant-ID).
We capture this identifier using a Spring Web Filter and store it in a thread-safe ThreadLocal wrapper called TenantContext.
public final class TenantContext { private static final ThreadLocal<String> CURRENT_TENANT = new ThreadLocal<>(); public static void setCurrentTenant(String tenantId) { CURRENT_TENANT.set(tenantId); } public static String getCurrentTenant() { return CURRENT_TENANT.get(); } public static void clear() { CURRENT_TENANT.remove(); } } Next, implement a OncePerRequestFilter to intercept incoming HTTP requests, extract the tenant identifier, and populate the context.
@Component public class TenantFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String tenantId = request.getHeader("X-Tenant-ID"); if (tenantId != null && !tenantId.isEmpty()) { TenantContext.setCurrentTenant(tenantId); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write("X-Tenant-ID header is missing"); return; } try { filterChain.doFilter(request, response); } finally { TenantContext.clear(); } } } Configuring Dynamic Schema Routing with Hibernate
To route database queries to the correct PostgreSQL schema dynamically, we implement a custom MultiTenantConnectionProvider and a CurrentTenantIdentifierResolver.
@Component public class CurrentTenantIdentifierResolverImpl implements CurrentTenantIdentifierResolver { @Override public String resolveCurrentTenantIdentifier() { String tenant = TenantContext.getCurrentTenant(); return tenant != null ? tenant : "public"; } @Override public boolean validateExistingCurrentSessions() { return true; } } When executing queries, Hibernate consults the resolver to determine which schema context to apply to the active database connection.
Authorization and Security Considerations
Tenant isolation at the database layer is not enough. You must also ensure that users cannot access resources belonging to other tenants through application endpoints, even if they guess or manipulate identifiers.
Integrate tenant checks into your Spring Security configuration or method-level security expressions:
@PreAuthorize("@tenantSecurity.hasAccess(#tenantId, principal)") public List<Document> getDocuments(String tenantId) { // fetch documents safely return [add result]; } Common Pitfalls to Avoid
- Leaking ThreadLocal State: Always clear your
TenantContextin afinallyblock or filter cleanup phase. Failing to do so in a thread-pool environment (like Tomcat) will cause cross-tenant data leaks. - Background Jobs and Async Processing:
ThreadLocalvariables do not propagate automatically to new threads. When using@AsyncorCompletableFuture, explicitly copy the tenant context to the asynchronous task. - Global Caching: Ensure caches like Redis are properly namespaced with the
tenant_idto prevent data collision between tenants.
Conclusion
Designing a multi-tenant architecture in Spring Boot requires diligence around context propagation and connection management. By implementing schema-per-tenant isolation and strict request filtering, you can build a secure, scalable SaaS foundation.
For further reading, consult the Spring framework documentation on multi-tenancy.
