BBackend CourseLeroy Labs
0/0
Search the course

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.

● expertSperoTek (in dev)Report-Manager-2

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_id automatically 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

SperoTek (in dev)shared/domain/TenantEntity · shared/config/TenantIdentifierConfig · accesscontrol/web/TenantResolutionFilter · TenantIsolationContractIT · decision D-13

Five layers of isolation:

  1. The route carries the tenant: /api/v1/companies/{companyId}/....
  2. The filter verifies membership (or a company API token) and sets TenantContext with that company’s permissions, clearing it in finally.
  3. Hibernate @TenantId auto-filters every entity query.
  4. The database has UNIQUE (company_id, id) plus composite FKs, so cross-tenant references are impossible.
  5. 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”.

Report-Manager-2ReportUnit tree · ReportSubmissionSpecs.isAccessibleBy

RM 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.

  • 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 companyId in 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.

Check yourself

1. Which queries does Hibernate @TenantId NOT filter automatically?
2. Cheapest model for 10,000 small tenants?
3. Why clear TenantContext in finally?