Implementing Multi-Tenancy Data Models

1. Using Separate Databases per Tenant

ProsCons
Strong isolationHigh operational overhead
Per-tenant backup/restoreMigrations × N DBs
Easy data exportResource waste for small tenants
Best forEnterprise/regulated tenants

2. Using Separate Schemas per Tenant

ProsCons
Logical isolation within one DBSchema explosion (1000s)
search_path switch per requestCatalog bloat
Per-schema backupCross-tenant queries harder
Best for10–100 tenants

3. Using Shared Schema with Tenant ID

ProsCons
Single migration pathStronger isolation needed (RLS)
Efficient resource usageNoisy-neighbor risk
Easy cross-tenant analyticstenant_id must be on every index/query
Best forSaaS scale (1000s of tenants)

Example: Shared Schema

CREATE TABLE invoices (
  tenant_id BIGINT NOT NULL,
  id        BIGSERIAL,
  amount    NUMERIC(10,2),
  PRIMARY KEY (tenant_id, id)
) PARTITION BY HASH (tenant_id);
CREATE INDEX ON invoices(tenant_id, created_at DESC);

4. Implementing Row-Level Isolation

MechanismDetail
RLS policyFilter on current_setting('app.tenant_id')
Set per connectionSET app.tenant_id = '42';
Force RLSEven table owner respects policy
Defense in depthApp-side filter + DB RLS

5. Designing Tenant-Specific Configurations

StorageUse
tenant_config tableKey-value or JSONB
Feature flagsPer-tenant overrides
Resource quotasLimits per tenant (rows, storage)
Region pintenant.region for data residency

6. Modeling Shared Reference Data

ApproachDetail
Global tableNo tenant_id — read by all (e.g., country list)
Tenant overrideOptional tenant-specific row
ReplicationCopy reference data to per-tenant DBs
FDWForeign table to shared registry

7. Implementing Tenant Data Partitioning

StrategyDetail
HASH(tenant_id)Even distribution
LIST(tenant_id)Pin big tenants to dedicated partition
Citus (PG)Distributed tables sharded by tenant
IndexingAlways lead with tenant_id

8. Designing for Tenant Scalability

ConcernMitigation
Noisy neighborRate limits, query timeouts, resource governors
Power tenantsPromote to dedicated DB/shard
Onboard / offboardAutomated provision & export
Per-tenant metricsTrack usage for billing + ops

9. Handling Cross-Tenant Queries

UseApproach
Internal analyticsBypass RLS with elevated role
AggregationsPre-computed in OLAP warehouse
Avoid in tenant APIStrict tenant scoping
AuditLog all cross-tenant access

10. Ensuring Tenant Data Security

ControlDetail
RLS (mandatory)Defense in depth
Per-tenant encryption keysBYOK / KMS context
Audit per tenantTrace who accessed what
Backup isolationRestore per-tenant without leaking
Data residencyRegion-pinned storage