Building Multi-Tenancy Patterns

1. Understanding Tenant Isolation Strategies

StrategyIsolationCost
Pool (shared)LowestLowest
Bridge (schema)MediumMedium
Silo (DB/instance)HighestHighest
HybridBig tenants → silo, small → pool

2. Implementing Shared Database with Tenant ID

Example: Postgres Row-Level Security

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
  USING (tenant_id = current_setting('app.tenant_id')::uuid);

-- per request
SET app.tenant_id = '...';
SELECT * FROM orders;  -- filtered automatically
ProCon
Cheapest, easy opsRisk of leakage if tenant filter forgotten
Dense packingNoisy neighbors

3. Implementing Database per Tenant

PropertyDetail
Strong isolationCrash blast radius = 1 tenant
Per-tenant backup/restoreEasy DR for one tenant
CostHigh at scale (1000s of DBs)
Connection routingTenant → DSN map; per-request datasource

4. Implementing Schema per Tenant

PropertyDetail
Postgres schemasOne DB, many namespaces
RoutingSET search_path TO tenant_xyz
MigrationsApply to each schema (tooling burden)
Limit~ thousands of schemas before catalog bloat

5. Implementing Tenant Context Propagation

MechanismDetail
JWT claimtenant_id in token
HTTP headerX-Tenant-Id
Server contextThreadLocal / context.Context (Go)
Tracing baggagePropagate cross-service

6. Implementing Resource Quotas and Limits

ResourceMechanism
API callsPer-tenant rate limiter
StorageQuota in app + DB-level (Postgres tablespace)
ComputeK8s ResourceQuota per namespace
ConcurrencyBulkhead per tenant

7. Handling Tenant Data Isolation

LayerPractice
DBRLS, separate DB/schema
CacheKey prefix: t:<id>:...
QueueTenant in message header; per-tenant topics for big ones
EncryptionPer-tenant DEK (BYOK option)

8. Implementing Tenant Configuration

MechanismDetail
Override layerDefault → tenant override
Storagetenant_settings table; cache
Feature flagsTargeted by tenant id

9. Understanding Noisy Neighbor Problem

MitigationDetail
Per-tenant rate limitCap requests/sec
BulkheadSeparate thread pools / connections
Fair schedulingWeighted round-robin
Promote heavy tenantMove to dedicated silo

10. Implementing Tenant-Specific Features

ApproachDetail
Feature flags by tenantPlan-tier targeting
Plan / entitlement serviceAuthoritative source
UI gatingHide unavailable features
Backend enforceAlways re-check server-side