Implementing Multi-Tenancy Patterns

1. Database per Tenant Pattern

AspectDetail
IsolationHighest — separate DB per tenant
ProsStrong isolation; per-tenant backup/restore; per-tenant compliance
ConsOperational overhead; cost; schema migrations × N
Best ForEnterprise / regulated tenants

2. Schema per Tenant Pattern

AspectDetail
IsolationMedium — separate schema in same DB
ProsCheaper than DB-per-tenant; reasonable isolation
ConsConnection pool per schema; migration N times
RoutingSet search_path / current_schema per request

3. Shared Database Discriminator Pattern

AspectDetail
IsolationLowest — tenant_id column on every table
ProsCheapest; easy migrations; great density
ConsRisk of cross-tenant leak; noisy neighbor
RequiredRLS (row-level security) or always-applied filter

Example: Postgres RLS

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
  USING (tenant_id = current_setting('app.tenant_id')::uuid);
-- App: SET LOCAL app.tenant_id = '...' at request start

4. Tenant Isolation Pattern

LayerMechanism
ComputePer-tenant pod / namespace (silo) vs shared (pool)
NetworkNetworkPolicy per tenant
DataDB-per / schema-per / RLS
CacheKey prefix; per-tenant TTL/quota
IdentityTenant claim in JWT enforced server-side

5. Tenant Context Propagation Pattern

StepDetail
ExtractFrom subdomain / JWT claim / header at edge
StoreThreadLocal / request scope / OTel baggage
PropagateForward header to all downstream calls
ApplyDB filter, cache key prefix, authz check

6. Tenant-Based Routing Pattern

StrategyDetail
Subdomain{tenant}.app.com
Path/t/{tenant}/...
HeaderX-Tenant-ID
Routing LayerAPI gateway routes to tenant-specific cell/shard

7. Tenant Configuration Pattern

AspectDetail
StorageTenants table with config JSON; or config service
CachePer-tenant config cached at request start
ExamplesBranding, feature flags, plan limits, integrations

8. Per-Tenant Resource Quota Pattern

Quota TypeDetail
API RateRequests per minute by plan
StorageGB per tenant
ComputeCPU/mem (K8s LimitRange per namespace)
RecordsMax users / objects
EnforcementReject 429 / 402 with clear quota info

9. Tenant-Based Caching Pattern

PracticeDetail
Key Namespacingtenant:{id}:user:{uid}
Per-Tenant EvictionSCAN + DELETE on tenant prefix
QuotaCap memory per tenant
RiskForgetting prefix → cross-tenant leak
Warning: One missing tenant filter can leak data across tenants. Use RLS, decorators, and integration tests that explicitly assert isolation.

10. Tenant Onboarding Pattern

StepDetail
ProvisionCreate tenant record, schema/DB, namespace
SeedDefault config, admin user, sample data
VerifySmoke tests for tenant
NotifyWelcome flow; activation tracking
ToolsWorkflow engine (Temporal); Terraform per tenant