Prompt
How do I set up multi-tenant architecture for a SaaS product?
Latest observation
Setting up multi-tenant architecture for a SaaS product usually comes down to how you isolate tenant data, how you route requests, and how you scale and operate the system safely.
1) Start with the tenancy model
There are three common approaches:
A. Shared database, shared schema
- All tenants use the same tables.
- Each row has a
tenant_id. - Pros: cheapest, easiest to operate, easiest to scale early.
- Cons: highest risk of data leakage if queries are wrong; harder per-tenant backups/migrations.
B. Shared database, separate schema per tenant
- Same database server, but each tenant gets its own schema.
- Pros: better isolation than shared schema; easier tenant-specific migrations than row-level separation.
- Cons: more operational complexity; can get messy with many tenants.
C. Separate database per tenant
- Each tenant gets its own database.
- Pros: strongest isolation, easier compliance and data residency, simpler tenant-level restore/export.
- Cons: expensive, harder to manage at large scale, more operational overhead.
Rule of thumb
- Early stage / many small tenants: shared schema with
tenant_id - Enterprise / compliance-heavy: separate database per tenant
- Middle ground: shared app, separate schema or database for premium tenants
2) Enforce tenant isolation everywhere
No matter the model, tenant isolation must be enforced in:
- API authentication/authorization
- Database queries
- Caching
- File/object storage
- Background jobs
- Search/indexing
- Analytics/logging
Key principle
Never trust the client to tell you the tenant without verifying it.
Use tenant context from:
- authenticated user identity
- org/team membership
- request subdomain or custom domain
- signed JWT claims or session data
3) Design tenant identification
Common ways to identify the tenant:
Subdomain
tenant1.yourapp.com- Easy and clean for SaaS
- Good for routing and branding
Custom domain
app.tenant.com- Great for customer-facing apps and enterprise branding
- Requires domain verification and certificate handling
URL path
yourapp.com/t/tenant1- Simple to implement
- Less elegant, but works well for internal/admin tools
JWT/session claim
- Store
tenant_idin the auth token after login - Helpful for API requests
- Still validate membership server-side
4) Model your data for tenancy
If using shared schema, add tenant_id to all tenant-owned tables.
Example:
tenantsusersmembershipsprojectsinvoices
Typical relationships:
userscan belong to multiple tenants through amembershipstable- all business tables include
tenant_id
Important
- Add indexes like
(tenant_id, id)or(tenant_id, created_at) - Use foreign keys where possible
- Consider composite unique constraints, e.g.:
UNIQUE (tenant_id, email)UNIQUE (tenant_id, slug)
5) Prevent data leaks by default
This is one of the biggest risks in multi-tenancy.
Best practices
- Use a data access layer or ORM scopes that automatically include
tenant_id - Add database-level row security if supported
- Write tests that ensure cross-tenant access is impossible
- Avoid raw SQL unless carefully reviewed
- Never cache tenantless values if they are tenant-specific
Helpful pattern
Always resolve the tenant first, then run all business logic in a tenant-scoped context.
6) Handle authentication and authorization separately
These are different concerns:
Authentication
Who is the user?
Authorization
What tenant and permissions do they have?
Use:
- user identity
- tenant membership
- role-based access control (RBAC)
- possibly attribute-based access control (ABAC) for advanced cases
Example roles:
- Owner
- Admin
- Member
- Viewer
7) Make background jobs tenant-aware
Background jobs often cause leaks if tenant context is not included.
Pass:
tenant_iduser_idif relevant- permission or ownership context if needed
Also ensure:
- job retries preserve tenant context
- scheduled jobs are scoped correctly
- exports, emails, and webhooks run under the right tenant
8) Think about storage and integrations
File storage
Prefix object keys by tenant:
tenant_123/invoices/file.pdf
Search
Either:
- shared index with
tenant_idfilter - separate index per tenant for large or sensitive customers
Webhooks/API integrations
Store integration credentials per tenant and isolate callback handling.
9) Plan for provisioning and lifecycle
You need flows for:
- tenant creation
- user invitation
- plan upgrades/downgrades
- suspension/deactivation
- deletion/data export
Common provisioning steps:
- create tenant record
- create default roles/settings
- assign owner user
- provision tenant resources if needed
- send onboarding email
10) Consider compliance and enterprise requirements
If you need:
- SOC 2
- HIPAA
- GDPR
- data residency
- customer-specific encryption keys
Then you may need:
- separate databases or clusters
- tenant-specific encryption
- audit logs
- backup/restore per tenant
- stricter access controls
11) Observability and auditing
Log tenant context in:
- application logs
- metrics
- traces
- audit events
But avoid logging sensitive tenant data.
This helps with:
- debugging
- billing
- incident response
- per-tenant usage analysis
12) A practical recommended architecture for most SaaS apps
For many startups, a good starting architecture is:
- Shared app layer
- Shared database
tenant_idon all tenant-owned tables- Tenant-scoped ORM/data access
- Subdomain-based tenant routing
- RBAC membership table
- Tenant-aware background jobs
- Tenant-prefixed object storage
- Strict automated tests for isolation
This gives a good balance of cost, speed, and scalability.
13) Example table design
tenants
- id
- name
- slug
- plan
- created_at
users
- id
- email
- password_hash
- created_at
memberships
- id
- tenant_id
- user_id
- role
- created_at
projects
- id
- tenant_id
- name
- created_at
14) Common mistakes to avoid
- forgetting
tenant_idin one table - relying only on frontend filtering
- using global caches without tenant keys
- letting admins access all tenants by accident
- mixing system tables and tenant data carelessly
- not testing cross-tenant access
- building migrations that lock all tenants at once
15) Migration strategy if you already have a single-tenant app
If you’re converting an existing app:
- add
tenant_idandtenantstable - backfill existing records into a default tenant
- update queries to scope by tenant
- add membership/auth logic
- test isolation thoroughly
- migrate storage/jobs/search
- gradually enable new tenant onboarding
If you want, I can also give you:
- a reference architecture diagram,
- a database schema example, or
- a step-by-step implementation for a specific stack like Node.js, Django, Rails, .NET, or Spring Boot.