Daniel Cohen·
Multi-tenant design using Postgres RLS so a cross-tenant leak is impossible at the DB level
Designs a scalable multi-tenant SaaS platform with tenant isolation strategies, data partitioning, onboarding automation, and tier-based feature management.
Multi-Tenant SaaS Architecture Design
You are a SaaS Architect who built multi-tenant platforms serving thousands of enterprise customers. Design a multi-tenant SaaS architecture.
**SaaS Domain**: {{saas_domain}} (CRM, project management, analytics, marketing automation, HR platform)
**Tenant Isolation Level**: {{tenant_isolation_level}} (shared everything, shared DB separate schema, database-per-tenant, full isolation)
**Target Customer Profile**: {{target_customer_profile}} (SMB self-serve, enterprise sales-led, regulated industries)
**Customization Needs**: {{customization_needs}} (white-labeling, custom fields, custom workflows, integrations per tenant)
Design the complete multi-tenant architecture:
1. **Tenant Isolation Strategy** - Compare isolation models with trade-offs: cost, security, operational complexity, tenant migration ease
2. **Data Architecture** - Shared database with tenant_id column, schema-per-tenant, or database-per-tenant with connection routing
3. **Tenant Identification** - Subdomain-based (tenant.saas.com), path-based (/tenant/resource), header-based, JWT claim-based routing
4. **Authentication & Authorization** - Tenant-aware auth, role-based access per tenant, tenant admin vs org admin vs user roles
5. **Onboarding Flow** - Automated tenant provisioning (database, schema, default config), welcome email, guided setup wizard
6. **Tenant Configuration** - Feature flags per tenant, custom branding/white-labeling, locale/timezone, email domain configuration
7. **Resource Quotas** - Per-tenant limits (storage, API calls, users, compute) with enforcement and upgrade prompts
8. **Database Connection Pooling** - Schema search path switching, connection pool per tenant vs shared pool with SET statements
9. **Cross-Tenant Operations** - Analytics aggregation across tenants (with privacy), super-admin operations, tenant migration tools
10. **Tenant-Aware Caching** - Cache key namespacing, per-tenant cache invalidation, shared vs tenant-specific cached data
11. **Backup & Restore** - Per-tenant backup granularity, point-in-time recovery scope, tenant export/import functionality
12. **Operational Tools** - Tenant health dashboard, per-tenant metrics, tenant-specific alerting, support impersonation
13. **Compliance & Security** - Data residency per tenant, GDPR tenant data deletion, audit logs per tenant, encryption scope
Include the tenant resolution middleware pseudocode and database schema design for tenant isolation.
Ergebnisse
Multi-tenant SaaS design for a **project-management** product (SMB self-serve → enterprise). Recommended isolation: **shared DB, shared schema, `tenant_id` column** with Postgres Row-Level Security — cheapest to operate, and RLS makes cross-tenant leaks a database-level impossibility, not an application discipline.
**Tenant resolution middleware**
```typescript
// Subdomain → tenant, then pin the RLS variable for the whole request
async function resolveTenant(req, res, next) {
const sub = req.hostname.split(".")[0]; // acme.app.com → "acme"
const tenant = await tenants.bySlug(sub);
if (!tenant) return res.status(404).send("Unknown workspace");
req.tenantId = tenant.id;
await db.execute(sql`SET LOCAL app.tenant_id = ${tenant.id}`); // RLS enforces it
next();
}
```
**Schema + RLS policy:**
```sql
CREATE TABLE project (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id uuid NOT NULL,
name text NOT NULL
);
ALTER TABLE project ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON project
USING (tenant_id = current_setting('app.tenant_id')::uuid);
```
**Why RLS over per-schema/per-DB:** for thousands of SMB tenants, a schema-per-tenant explodes migration and connection-pool cost. Enterprise tenants that demand hard isolation get promoted to a dedicated DB via the same routing layer — a config flag, no rewrite. **Quotas** (users, storage, API calls) are enforced per tenant with upgrade prompts. **Caching** namespaces keys by `tenant_id`. **Onboarding** auto-provisions config + seed data and fires the welcome flow. GDPR deletion is a single tenant-scoped cascade.
Modell: Claude Opus 4
48 Likes17 SavesScore: 41
3 Kommentare
Marco Rossi·
Works in TS strict mode with no complaints, which is rare.
Tobias Keller·
The rollback path is what makes this safe to actually run. Good call.
Priya Nair·
The system design details here are spot on.