Implementing Multi-Tenancy

1. Designing Multi-Tenancy Architecture

StrategyIsolationCost
Database-per-tenantStrongHigh
Schema-per-tenantStrongMedium
Shared schema (tenant_id col)LogicalLow
HybridPool + silo for VIPsMixed

2. Implementing Tenant Identification

MechanismDetail
Subdomainacme.app.com
Path prefix/t/acme/...
HeaderX-Tenant-Id
JWT claimTenant in token

3. Implementing Database Isolation Strategies

TypeTrade-off
Separate DBOperational overhead × N
Separate schemaMigration runs per tenant
Shared schema + RLSPostgres row-level security

4. Implementing Schema Per Tenant

Example: Hibernate MultiTenantConnectionProvider

spring.jpa.properties.hibernate.multiTenancy=SCHEMA
spring.jpa.properties.hibernate.tenant_identifier_resolver=com.acme.TenantResolver
spring.jpa.properties.hibernate.multi_tenant_connection_provider=com.acme.SchemaProvider

5. Implementing Database Per Tenant

ComponentDetail
Connection routingAbstractRoutingDataSource
Catalog mgmtMap tenant → DB URL
MigrationRun Flyway per DB
ProvisioningAutomated DB creation

6. Implementing Shared Schema 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);
-- App sets per request:
SET LOCAL app.tenant_id = 'a1b2...';

7. Implementing Tenant Context Propagation

Example: Filter + ThreadLocal holder

public class TenantHolder {
    private static final ThreadLocal<UUID> CURRENT = new ThreadLocal<>();
    public static void set(UUID id) { CURRENT.set(id); }
    public static UUID get() { return CURRENT.get(); }
    public static void clear() { CURRENT.remove(); }
}
Warning: Always clear ThreadLocal in finally — pooled threads will leak tenant context otherwise.

8. Implementing Tenant-Specific Configuration

OverrideDetail
BrandingLogo, colors
Feature flagsPer-tenant toggles
Limits/quotasStorage, API calls, users
Billing tierCapabilities by plan

9. Implementing Cross-Tenant Operations

Use CaseDetail
Admin reportingAggregate across tenants
MigrationMove tenant between shards
MaintenanceBulk schema migrations
SafeguardExplicit "system context" flag, audit heavily

10. Implementing Tenant Provisioning

StepDetail
Create tenant recordIn control plane
Create schema/DBRun migrations
Seed defaultsRoles, settings, sample data
Create admin userSend invite
Provisioning sagaCompensate on partial failure

11. Implementing Tenant Migration Logic

ReasonApproach
Rebalance shardsDual-write + cutover
Upgrade tierMove from pool to silo
Region moveSnapshot + restore + replicate diff

12. Implementing Tenant Resource Limits

LimitDetail
API ratePer-tenant quota
StorageBytes / files
User countPer plan
Background jobsConcurrency cap
EnforcementPre-check + 402/429 responses