Multi-tenancy, from discriminator column to schema or DB per tenant
The three tenancy models and their trade-offs, Hibernate @TenantId, resolving the tenant from the URL, ThreadLocal context, composite FKs, tenant-isolation tests and Postgres Row-Level Security.
The three models
| Model | Isolation | Cost / ops | Scaling to many tenants | Per-tenant customisation |
|---|---|---|---|---|
Shared schema + tenant_id column (SperoTek) |
Logical, enforced in code and DB | Cheapest, one migration run | Excellent (millions) | Low |
| Schema per tenant | Stronger | N migration runs | Hundreds to thousands | Medium |
| Database per tenant | Strongest; noisy-neighbour-proof | Highest | Tens to hundreds | High; per-tenant backup and restore |
Hybrid approaches are common: shared tables for small customers, a dedicated DB for enterprise ones.
Shared schema with Hibernate @TenantId
@MappedSuperclass
public abstract class TenantEntity extends BaseEntity {
@TenantId
@Column(name = "company_id", nullable = false, updatable = false)
private UUID companyId;
}
@Component
class TenantIdentifierConfig implements CurrentTenantIdentifierResolver<UUID> {
public UUID resolveCurrentTenantIdentifier() {
return TenantContext.current().map(t -> t.companyId()).orElse(ROOT);
}
public boolean validateExistingCurrentSessions() { return true; }
}
With @TenantId, Hibernate:
- sets
company_idautomatically on insert, and - adds
WHERE company_id = ?to every entity query (find, JPQL, criteria).
You can’t forget the filter in JPA code. Native SQL and JdbcClient are not filtered automatically, so those must include company_id by hand.
Resolving the tenant
// /api/v1/companies/{companyId}/journals/...
class TenantResolutionFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) {
UUID companyId = extractFromPath(req);
Membership m = members.find(companyId, currentUserId())
.orElseThrow(() -> forbidden()); // must be a member (or valid API token)
TenantContext.set(new TenantContext.Tenant(companyId, m.permissions()));
try { chain.doFilter(req, res); }
finally { TenantContext.clear(); } // ALWAYS clear (pooled threads!)
}
}
In your project
shared/domain/TenantEntity · shared/config/TenantIdentifierConfig · accesscontrol/web/TenantResolutionFilter · TenantIsolationContractIT · decision D-13Five layers of isolation:
- The route carries the tenant:
/api/v1/companies/{companyId}/.... - The filter verifies membership (or a company API token) and sets
TenantContextwith that company’s permissions, clearing it infinally. - Hibernate
@TenantIdauto-filters every entity query. - The database has
UNIQUE (company_id, id)plus composite FKs, so cross-tenant references are impossible. - A contract test,
TenantIsolationContractIT, tries to read and write across companies and must fail.
The ROOT tenant (new UUID(0,0)) is unscoped, and its use is meant to stay inside accesscontrol, e.g. for listing “which companies am I a member of”.
ReportUnit tree · ReportSubmissionSpecs.isAccessibleByRM isn’t multi-tenant (one organisation), but it has intra-tenant partitioning by unit: data is filtered by the units a user may see. It’s the same pattern at a smaller scale.
Postgres Row-Level Security (a next step)
ALTER TABLE journal_entries ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON journal_entries
USING (company_id = current_setting('app.company_id')::uuid);
-- per transaction: SET LOCAL app.company_id = '...';
RLS adds a sixth layer that covers native SQL too. Note that it doesn’t apply to table owners or superusers unless you use FORCE ROW LEVEL SECURITY.
Related concepts you must know
- Noisy neighbours. One big tenant slows everyone down, so add per-tenant rate limits (SperoTek’s reporting tier) and query timeouts.
- Tenant-aware caching. Cache keys must include the tenant id.
- Tenant-aware async. Pass
companyIdin events; a ThreadLocal won’t follow to other threads. - Indexes lead with
company_id(indexes lesson). - Data export and deletion per tenant for GDPR and offboarding.