Careeroza
Multi-tenancy Strategies
One App, Many Customers
A SaaS product (Zoho, Freshworks, Shopify) serves many companies, called tenants, from one deployment. ShopEase is turning into "ShopEase for Business": every brand gets its own store. Each tenant must see only its own data. There are three standard designs:
| Strategy | How | Isolation | Cost / effort |
|---|---|---|---|
| Discriminator (shared schema) | tenant_id column on every table | lowest: one missing condition leaks data | cheapest; easy to add tenants |
| Schema per tenant | same database, schema brand_a, brand_b | medium | migrations run per schema |
| Database per tenant | separate database (or server) per tenant | highest; easy per-tenant backup/restore | most expensive; many connection pools |
How Hibernate Supports Each
request ──► TenantFilter reads "X-Tenant-Id" / subdomain / JWT claim
│ TenantContext.set("brand-a")
▼
Hibernate asks CurrentTenantIdentifierResolver → "brand-a"
│
┌───────────┼─────────────────────────────┬──────────────────────────────┐
▼ ▼ ▼
DISCRIMINATOR SCHEMA DATABASE
@TenantId field → adds MultiTenantConnectionProvider MultiTenantConnectionProvider
"where tenant_id = 'brand-a'" sets schema on the connection returns a connection from
to every query, sets it on insert (SET search_path / USE) brand-a's own DataSourceExercise
Exercise: A hospital software vendor must give each hospital its own backups and must be able to delete one hospital's data completely when the contract ends. Which strategy fits, and why?
Show answer
Database per tenant (or at least schema per tenant).
- Backups/restores and full deletion are per database: drop the database and it is gone.
- Strong isolation suits medical data regulations.
A shared schema with tenant_id would need careful DELETE ... WHERE tenant_id = ?
across every table and cannot give a hospital a separate backup.