Video in progress

How do you choose data isolation for a multi-tenant SaaS: shared tables + tenant_id, a schema per tenant, or a separate database per tenant?

Shared tables / Schema per tenant / Database per tenant — Number of tenants: 100,000+ / hundreds to a few thousand / tens to hundreds; Isolation: logical / medium / strong; Migration: one / N times / N times; "Noisy neighbor": yes / yes (one server) / no; Exporting/deleting one tenant: hard / easy / easiest

📖 Answer

Shared tables Schema per tenant Database per tenant
Number of tenants 100,000+ hundreds to a few thousand tens to hundreds
Isolation logical medium strong
Migration one N times N times
"Noisy neighbor" yes yes (one server) no
Exporting/deleting one tenant hard easy easiest

With shared tables the biggest risk is a single forgotten WHERE tenant_id = ?, and another customer's data leaks out. So instead of trusting the code, I close this off at the DB level:

ALTER TABLE invoice ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoice
    USING (tenant_id = current_setting('app.tenant_id')::bigint);
-- at the start of every transaction:
SET LOCAL app.tenant_id = '42';

The application role must not be the table owner (or use FORCE ROW LEVEL SECURITY), otherwise the policy is bypassed. Indexes start with tenant_id.

With schema-per-tenant, Hibernate's multi-tenancy (CurrentTenantIdentifierResolver + MultiTenantConnectionProvider) is convenient, but 3000 schemas × 200 tables = 600 thousand tables in the catalog, and pg_dump and Flyway slow down.

In practice a hybrid is common: small customers in shared tables, and an enterprise customer (if the contract requires a separate database or region) in its own database. For that, I abstract the tenant → DataSource routing in one place from the start. The main questions for the decision are the compliance requirements, the size of the largest tenant, and the strength of the operations team.