Video in progress
Compare the separate-schema, separate-database and `@TenantId` (discriminator) approaches to multi-tenancy in Hibernate 6.
@TenantId puts a tenant_id column in a single table and Hibernate does the filtering itself; it's cheap and suits many tenants, but isolation is the weakest. Separating by schema or database strengthens isolation, but migrations, connection pools and operational cost grow with the number of tenants.
📖 Answer
The discriminator approach in Hibernate 6:
@Entity
class Invoice {
@Id Long id;
@TenantId String tenantId; // set automatically on insert, a condition is added to queries
}
The current tenant is supplied through CurrentTenantIdentifierResolver (from the JWT, for example). One pool, one schema, one migration. It suits a SaaS with 10 thousand small customers.
The risks: forgetting the filter in native SQL and bulk queries means another tenant's data leaks out. That's why I add a second layer of protection with PostgreSQL row-level security. Indexes must start with tenant_id. One large tenant affects the whole table (a noisy neighbor).
Schema-per-tenant (MultiTenantConnectionProvider sets search_path when it hands out a connection):
- better isolation, and it's easy to back up and restore a single tenant;
- with 500+ schemas, a Flyway migration takes hours, and if it fails on one schema, what state are the others in?
- if the pool is shared, you must not forget to restore the schema when the connection is returned.
Database-per-tenant:
- the strongest isolation, for compliance requirements (data residency);
- a separate pool per tenant: 200 tenants × 10 connections will choke the databases;
- L2 cache keys must be separated by tenant.
I usually start with the discriminator and keep open the option of moving large customers, or ones with special requirements, to a separate database (a hybrid).
Sign up to mark studied questions and save your progress.