Prompt
How do I set up a multi-tenant SaaS architecture with customer data isolation?
Latest observation
A solid multi-tenant SaaS setup usually comes down to choosing where tenants share infrastructure and how you enforce isolation at every layer: auth, app logic, database, storage, and operations.
1) Pick a tenancy model
Common options:
A. Shared app + shared database
- One application serving all customers.
- One database, with each row tagged by
tenant_id. - Lowest cost and simplest ops.
- Best for early-stage SaaS or many small tenants.
Isolation: application checks + database constraints + often Row-Level Security (RLS).
B. Shared app + separate database per tenant
- Same codebase, but each customer gets its own database.
- Stronger isolation and simpler compliance story.
- More operational overhead.
Isolation: mostly by physical/logical separation at the DB level.
C. Shared app + separate schema per tenant
- One database, multiple schemas.
- Middle ground between A and B.
- Can be harder to manage at scale.
D. Separate app + separate infra per tenant
- Best isolation, highest cost.
- Usually only for enterprise or regulated customers.
2) Recommended default architecture
For most SaaS products, start with:
- Single app
- Single database
- Shared tables with
tenant_id - Row-Level Security (RLS) if using Postgres
- Object storage paths or buckets per tenant
- Tenant-aware auth and authorization
- Per-tenant encryption strategy for sensitive data
This gives you a good balance of scale, cost, and isolation.
3) Enforce tenant identity everywhere
Every request should resolve to a tenant context early.
Typical flow:
- User signs in.
- Auth token includes user identity and tenant membership.
- Middleware resolves current tenant from:
- subdomain (
acme.example.com) - path (
example.com/acme) - header/claim from token
- subdomain (
- App stores
tenant_idin request context. - Every DB query is scoped to that tenant.
Important rule:
Never trust client-supplied tenant_id alone.
Derive tenant context from authenticated session/token and server-side membership checks.
4) Database isolation patterns
Shared tables
Use tenant-scoped tables like:
CREATE TABLE projects (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL,
name TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
Always include tenant filters
SELECT * FROM projects
WHERE tenant_id = $1 AND id = $2;
Add constraints
- Composite unique keys:
UNIQUE (tenant_id, name)
- Foreign keys should include tenant boundaries where appropriate.
Use Row-Level Security if possible
In Postgres, RLS helps ensure the database itself blocks cross-tenant access.
Example idea:
- App sets a session variable like
app.current_tenant_id - RLS policy only allows rows matching that tenant
This is one of the strongest protections against accidental leakage.
5) Application-level safeguards
Even with RLS, keep app-level defenses:
- Centralize tenant resolution
- Build repository/data access layers that auto-apply tenant filters
- Avoid raw SQL scattered throughout the codebase
- Add tests for tenant leakage
- Make admin/debug endpoints tenant-aware
- Validate tenant membership before reads/writes
6) Separate sensitive resources by tenant
Object storage
For files, logs, exports, etc.:
- Prefix by tenant:
s3://bucket/tenant-a/... - Or use separate buckets for high-isolation customers
Caches
- Namespace cache keys with tenant ID
- Example:
tenant:{tenant_id}:session:{id}
Search indexes
- Include tenant field in documents
- Filter by tenant at query time
- Consider separate indexes for larger or enterprise tenants
Queues / jobs
- Include tenant ID in job payload
- Ensure workers set tenant context before processing
7) Identity and access control
You typically need:
- Org/tenant membership
- User roles within tenant
- Optional global roles for platform admins
Example hierarchy:
- Platform admin
- Tenant admin
- Member
- Read-only
Make authorization checks explicit:
- “Can this user access this resource within this tenant?”
- “Can this role perform this action?”
8) Encryption and key management
For stronger tenant isolation:
- Encrypt data at rest
- Consider per-tenant encryption keys for sensitive fields or blobs
- Use a KMS/HSM-backed envelope encryption approach
- Rotate keys per tenant if needed
This is especially useful for enterprise/compliance requirements.
9) Operational isolation
Even in a shared system:
- Tag logs, metrics, and traces with
tenant_id - Protect against noisy-neighbor issues with rate limits and quotas
- Use per-tenant usage tracking and billing
- Throttle abusive tenants without affecting others
For larger tenants, you can offer “dedicated” deployment tiers later.
10) Testing and verification
To avoid data leaks:
- Write tests that create two tenants and assert no cross-access
- Run security tests against every endpoint
- Verify background jobs don’t lose tenant context
- Review migrations carefully for tenant-scoped data
- Audit logs for unauthorized access attempts
11) Common mistakes to avoid
- Forgetting tenant filters in one query
- Using only client-side tenant selection
- Storing tenant ID in mutable client state only
- Sharing file paths without tenant prefixes
- Background jobs running without tenant context
- Admin features bypassing isolation unintentionally
- Missing tests for cross-tenant access
12) Practical starting blueprint
If you want a good first version:
- Auth: JWT/session with tenant membership claims
- Routing: subdomain-based tenant selection
- App: middleware sets
current_tenant - DB: shared Postgres tables +
tenant_id+ RLS - Files: tenant-prefixed object storage paths
- Cache/Queue: tenant-scoped keys and job context
- Ops: tenant-tagged observability + rate limits
If you want, I can also provide:
- a reference architecture diagram,
- a Postgres RLS example, or
- a Node/Express or Django implementation pattern.