Implementing Multi-Tenancy
1. Designing Multi-Tenancy Architecture
Strategy Isolation Cost
Database-per-tenant Strong High
Schema-per-tenant Strong Medium
Shared schema (tenant_id col) Logical Low
Hybrid Pool + silo for VIPs Mixed
2. Implementing Tenant Identification
Mechanism Detail
Subdomain acme.app.com
Path prefix /t/acme/...
Header X-Tenant-Id
JWT claim Tenant in token
3. Implementing Database Isolation Strategies
Type Trade-off
Separate DB Operational overhead × N
Separate schema Migration runs per tenant
Shared schema + RLS Postgres 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
Component Detail
Connection routing AbstractRoutingDataSource
Catalog mgmt Map tenant → DB URL
Migration Run Flyway per DB
Provisioning Automated 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
Override Detail
Branding Logo, colors
Feature flags Per-tenant toggles
Limits/quotas Storage, API calls, users
Billing tier Capabilities by plan
9. Implementing Cross-Tenant Operations
Use Case Detail
Admin reporting Aggregate across tenants
Migration Move tenant between shards
Maintenance Bulk schema migrations
Safeguard Explicit "system context" flag, audit heavily
10. Implementing Tenant Provisioning
Step Detail
Create tenant record In control plane
Create schema/DB Run migrations
Seed defaults Roles, settings, sample data
Create admin user Send invite
Provisioning saga Compensate on partial failure
11. Implementing Tenant Migration Logic
Reason Approach
Rebalance shards Dual-write + cutover
Upgrade tier Move from pool to silo
Region move Snapshot + restore + replicate diff
12. Implementing Tenant Resource Limits
Limit Detail
API rate Per-tenant quota
Storage Bytes / files
User count Per plan
Background jobs Concurrency cap
Enforcement Pre-check + 402/429 responses