Multi-Tenant Architecture Expert
Design and implement multi-tenant SaaS systems with proper data isolation, tenant context propagation, and noisy neighbor prevention.
Activation Triggers
Activate on: "multi-tenant", "tenant isolation", "RLS", "shared database", "SaaS architecture", "tenant context", "data isolation", "noisy neighbor", "tenant onboarding"
NOT for: Connection pool sizing → database-connection-pool-manager | API gateway tenant routing → api-gateway-reverse-proxy-expert | Authorization framework → relevant auth skill
Quick Start
- Choose isolation model — shared DB with RLS (cost-efficient), schema-per-tenant (moderate), DB-per-tenant (maximum isolation)
- Propagate tenant context — extract from JWT/header, set in middleware, available throughout request lifecycle
- Enforce at database level — Row-Level Security policies in PostgreSQL, not just application-level WHERE clauses
- Scope everything — caches, queues, file storage, logs must all include tenant ID
- Prevent noisy neighbors — per-tenant rate limits, connection limits, and resource quotas
Core Capabilities
| Domain |
Technologies |
| Database RLS |
PostgreSQL RLS, Supabase RLS, Neon branch-per-tenant |
| Schema Isolation |
PostgreSQL schemas, schema_search_path |
| Tenant Context |
AsyncLocalStorage (Node), cls-hooked, middleware injection |
| ORMs |
Prisma multi-schema, Drizzle with RLS, TypeORM tenant scope |
| Infrastructure |
Kubernetes namespaces, AWS Organizations, tenant-aware CDN |
Architecture Patterns
Shared Database with PostgreSQL RLS
-- Enable RLS on all tenant tables
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
-- Policy: tenants see only their own data
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.current_tenant')::uuid);
-- Set tenant context per request (from middleware)
SET LOCAL app.current_tenant = 'tenant-uuid-here';
-- All queries now automatically filtered
SELECT * FROM orders; -- only returns current tenant's orders
Tenant Context Middleware (Node.js)
import { AsyncLocalStorage } from 'node:async_hooks';
interface TenantContext { tenantId: string; plan: 'free' | 'pro' | 'enterprise'; }
const tenantStore = new AsyncLocalStorage<TenantContext>();
// Middleware: extract tenant from JWT and propagate
function tenantMiddleware(req: Request, res: Response, next: NextFunction) {
const tenantId = req.auth?.tenantId; // from JWT
if (!tenantId) return res.status(403).json({ error: 'Tenant required' });
const ctx: TenantContext = { tenantId, plan: req.auth.plan };
tenantStore.run(ctx, () => {
// Set PostgreSQL session variable for RLS
req.db.query(`SET LOCAL app.current_tenant = $1`, [tenantId]);
next();
});
}
// Anywhere in the stack:
export function getCurrentTenant(): TenantContext {
const ctx = tenantStore.getStore();
if (!ctx) throw new Error('No tenant context — called outside request?');
return ctx;
}
Isolation Model Decision Matrix
Shared DB + RLS Schema/Tenant DB/Tenant
Cost per tenant Lowest Medium Highest
Data isolation Row-level Schema-level Full
Compliance Moderate Good Best
Migration effort Single migration Per-schema Per-database
Max tenants 10,000+ 1,000 100
Cross-tenant query Easy Possible Hard
Noisy neighbor Risk (mitigate) Moderate None
Anti-Patterns
- Application-only isolation — relying on WHERE clauses without RLS means a single bug leaks data across tenants
- Tenant ID in URLs —
/api/tenant-123/orders lets users guess other tenant IDs; use JWT claims instead
- Global caches — cache keys MUST include tenant ID;
cache:orders:123 is wrong, cache:tenant-abc:orders:123 is right
- Shared connection limits — one tenant running heavy queries starves others; enforce per-tenant connection/query limits
- Tenant-unaware logging — every log line must include tenant ID for debugging and audit compliance
Quality Checklist
1---2license: Apache-2.03name: multi-tenant-architecture-expert4description: "Tenant isolation, row-level security, shared/siloed schema patterns for SaaS platforms. Activate on: multi-tenant, tenant isolation, RLS, shared database, SaaS architecture, tenant context, data isolation. NOT for: connection pooling (use database-connection-pool-manager), API gateway routing (use api-gateway-reverse-proxy-expert)."5allowed-tools: Read,Write,Edit,Bash(npm:*,npx:*,psql:*)6category: Backend & Infrastructure7tags:8 - multi-tenant9 - saas10 - rls11 - tenant-isolation12 - postgres13pairs-with:14 - skill: database-connection-pool-manager15 reason: Pool segmentation per tenant or shared pool tuning16 - skill: api-rate-limiting-throttling-expert17 reason: Per-tenant rate limits prevent noisy neighbors18 - skill: cache-strategy-invalidation-expert19 reason: Cache keys must be tenant-scoped20metadata:21 source: https://skillmd.com/skills/curiositech/multi-tenant-architecture-expert22---2324# Multi-Tenant Architecture Expert2526Design and implement multi-tenant SaaS systems with proper data isolation, tenant context propagation, and noisy neighbor prevention.2728## Activation Triggers2930**Activate on:** "multi-tenant", "tenant isolation", "RLS", "shared database", "SaaS architecture", "tenant context", "data isolation", "noisy neighbor", "tenant onboarding"3132**NOT for:** Connection pool sizing → `database-connection-pool-manager` | API gateway tenant routing → `api-gateway-reverse-proxy-expert` | Authorization framework → relevant auth skill3334## Quick Start35361. **Choose isolation model** — shared DB with RLS (cost-efficient), schema-per-tenant (moderate), DB-per-tenant (maximum isolation)372. **Propagate tenant context** — extract from JWT/header, set in middleware, available throughout request lifecycle383. **Enforce at database level** — Row-Level Security policies in PostgreSQL, not just application-level WHERE clauses394. **Scope everything** — caches, queues, file storage, logs must all include tenant ID405. **Prevent noisy neighbors** — per-tenant rate limits, connection limits, and resource quotas4142## Core Capabilities4344| Domain | Technologies |45|--------|-------------|46| **Database RLS** | PostgreSQL RLS, Supabase RLS, Neon branch-per-tenant |47| **Schema Isolation** | PostgreSQL schemas, schema_search_path |48| **Tenant Context** | AsyncLocalStorage (Node), cls-hooked, middleware injection |49| **ORMs** | Prisma multi-schema, Drizzle with RLS, TypeORM tenant scope |50| **Infrastructure** | Kubernetes namespaces, AWS Organizations, tenant-aware CDN |5152## Architecture Patterns5354### Shared Database with PostgreSQL RLS5556```sql57-- Enable RLS on all tenant tables58ALTER TABLE orders ENABLE ROW LEVEL SECURITY;5960-- Policy: tenants see only their own data61CREATE POLICY tenant_isolation ON orders62 USING (tenant_id = current_setting('app.current_tenant')::uuid);6364-- Set tenant context per request (from middleware)65SET LOCAL app.current_tenant = 'tenant-uuid-here';6667-- All queries now automatically filtered68SELECT * FROM orders; -- only returns current tenant's orders69```7071### Tenant Context Middleware (Node.js)7273```typescript74import { AsyncLocalStorage } from 'node:async_hooks';7576interface TenantContext { tenantId: string; plan: 'free' | 'pro' | 'enterprise'; }77const tenantStore = new AsyncLocalStorage<TenantContext>();7879// Middleware: extract tenant from JWT and propagate80function tenantMiddleware(req: Request, res: Response, next: NextFunction) {81 const tenantId = req.auth?.tenantId; // from JWT82 if (!tenantId) return res.status(403).json({ error: 'Tenant required' });8384 const ctx: TenantContext = { tenantId, plan: req.auth.plan };85 tenantStore.run(ctx, () => {86 // Set PostgreSQL session variable for RLS87 req.db.query(`SET LOCAL app.current_tenant = $1`, [tenantId]);88 next();89 });90}9192// Anywhere in the stack:93export function getCurrentTenant(): TenantContext {94 const ctx = tenantStore.getStore();95 if (!ctx) throw new Error('No tenant context — called outside request?');96 return ctx;97}98```99100### Isolation Model Decision Matrix101102```103 Shared DB + RLS Schema/Tenant DB/Tenant104Cost per tenant Lowest Medium Highest105Data isolation Row-level Schema-level Full106Compliance Moderate Good Best107Migration effort Single migration Per-schema Per-database108Max tenants 10,000+ 1,000 100109Cross-tenant query Easy Possible Hard110Noisy neighbor Risk (mitigate) Moderate None111```112113## Anti-Patterns1141151. **Application-only isolation** — relying on WHERE clauses without RLS means a single bug leaks data across tenants1162. **Tenant ID in URLs** — `/api/tenant-123/orders` lets users guess other tenant IDs; use JWT claims instead1173. **Global caches** — cache keys MUST include tenant ID; `cache:orders:123` is wrong, `cache:tenant-abc:orders:123` is right1184. **Shared connection limits** — one tenant running heavy queries starves others; enforce per-tenant connection/query limits1195. **Tenant-unaware logging** — every log line must include tenant ID for debugging and audit compliance120121## Quality Checklist122123- [ ] RLS enabled on ALL tenant-scoped tables (not just application-level filtering)124- [ ] Tenant context propagated via AsyncLocalStorage (not global state)125- [ ] Cache keys prefixed with tenant ID126- [ ] Per-tenant rate limits configured127- [ ] Tenant ID included in all structured log entries128- [ ] Cross-tenant data access impossible even with direct SQL129- [ ] Tenant onboarding automated (schema creation, seed data, billing)130- [ ] Data export/deletion per tenant for GDPR compliance131- [ ] Noisy neighbor monitoring: per-tenant query time and resource usage132- [ ] Integration tests verify RLS prevents cross-tenant access