Multi-Tenant SaaS Architecture: Complete Guide
Executive Summary
Multi-tenant SaaS architecture enables multiple customers (tenants) to share the same application instance while maintaining data isolation, security, and performance.
1. Architectural Patterns
Option A: Single Database, Shared Schema (BEST FOR STARTUPS)
All tenants share the same database and tables, distinguished by a tenant_id column.
Pros:
- Simplest to implement
- Best resource utilization
- Easy to scale horizontally
- Lowest operational overhead
Cons:
- Most vulnerable to data leakage
- Limited data isolation
- Complex backup/restore per tenant
Best For: SaaS with many small tenants (0-1000), startups
-- All tables include tenant_id
CREATE TABLE users (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL,
email VARCHAR(255),
INDEX idx_tenant_email (tenant_id, email)
);
-- EVERY query must filter by tenant_id
SELECT * FROM users WHERE tenant_id = 'abc-123';
Option B: Single Database, Separate Schemas
One database with separate schemas/namespaces per tenant.
Pros:
- Better data isolation
- Per-tenant customization possible
- Easier compliance
Cons:
- Limited by database schema count
- Migration complexity
- Higher operational overhead
Best For: Medium-sized tenants (100-500), industries with compliance
Option C: Separate Database per Tenant (FOR ENTERPRISE)
Each tenant gets their own dedicated database instance.
Pros:
- Maximum data isolation
- Best performance isolation
- Simplest compliance
- Independent scaling per tenant
Cons:
- Highest operational cost
- Complex connection pooling
- Resource underutilization
Best For: Enterprise/large tenants, high-security requirements
2. Tenant Resolution Strategies
Option 1: Subdomain-Based (Recommended for Public SaaS)
URL: tenant1.yourapp.com
↓
Extract: tenant1
↓
Store: req.tenantId = 'tenant1'
Best For: Public-facing SaaS platforms
Option 2: JWT/Token-Based (Recommended for APIs)
// Login response includes tenant info
{
"token": "eyJhbGci...",
"user": {
"id": "user-123",
"tenantId": "acme-corp"
}
}
Best For: API-first applications, mobile apps
Option 3: Custom Domain (Enterprise)
User visits: acme.com
↓
DNS CNAME → yourapp.com
↓
Lookup: which tenant owns acme.com?
Best For: Enterprise customers
3. Data Isolation & Security (CRITICAL)
Row-Level Security (RLS) - PostgreSQL
-- Step 1: Enable RLS
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
-- Step 2: Create isolation policy
CREATE POLICY tenant_isolation ON projects
USING (tenant_id = current_setting('app.current_tenant'));
// Set tenant context in middleware
app.use(async (req, res, next) => {
await db.query(`SET LOCAL app.current_tenant = $1`, [req.tenantId]);
next();
});
Query-Time Enforcement (ALWAYS DO THIS)
// ✅ CORRECT: Always filter by tenant_id
const projects = await db.query(
'SELECT * FROM projects WHERE tenant_id = ?',
[currentTenant.id]
);
// ❌ NEVER: Query without tenant filter
const projects = await db.query('SELECT * FROM projects'); // DANGER!
Application-Level Protection
// Middleware to protect ALL routes
function requireTenantAccess(req, res, next) {
const resourceTenantId = req.resource.tenant_id;
const userTenantId = req.user.tenant_id;
if (resourceTenantId !== userTenantId) {
return res.status(403).json({ error: 'Access denied' });
}
next();
}
Caching Strategy (SUPER IMPORTANT)
// ✅ CORRECT: Tenant-aware cache keys
const cacheKey = `tenant:${tenantId}:projects:${projectId}`;
// ❌ NEVER: Shared cache keys
const cacheKey = `project:${projectId}`; // DATA LEAK RISK!
// Always include tenant in cache operations
redis.get(`tenant:${req.user.tenantId}:data`);
redis.set(`tenant:${req.user.tenantId}:data`, data);
4. Multi-Tenant Authentication
User Identity Structure
{
"id": "user-123",
"email": "john@acme.com",
"tenant_id": "acme-corp",
"tenant_role": "admin"
}
Domain-Based Login
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const subdomain = extractSubdomain(req); // "acme" from acme.yourapp.com
// Verify user belongs to THIS tenant
const user = await db('users')
.where({ email, tenant_id: subdomain })
.first();
if (!user || !verifyPassword(password, user.password)) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Create session with tenant context
req.session.userId = user.id;
req.session.tenantId = subdomain;
res.json({ success: true, tenantId: subdomain });
});
JWT with Tenant Info
// Login endpoint
app.post('/login', async (req, res) => {
const { email, password, tenantId } = req.body;
const user = await db('users')
.where({ email, tenant_id: tenantId })
.first();
if (!user || !verifyPassword(password, user.password)) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// JWT includes tenant info
const token = jwt.sign(
{ userId: user.id, tenantId: user.tenant_id },
process.env.JWT_SECRET,
{ expiresIn: '24h' }
);
res.json({ token });
});
// Protected route middleware
function authenticateJWT(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) return res.status(401).json({ error: 'Invalid token' });
req.user = decoded;
next();
});
}
5. Scalability Considerations
Database Scaling
Read Replicas
[App Server]
↓
[Primary DB] ← Writes only
↓ Replication
[Replica 1] ← Reads
[Replica 2] ← Reads
// Route reads to replicas, writes to primary
const primaryPool = new Pool({ connectionString: PRIMARY_DB_URL });
const replicaPool = new Pool({ connectionString: REPLICA_DB_URL });
// Write operations
await primaryPool.query('INSERT INTO projects...');
// Read operations
const projects = await replicaPool.query(
'SELECT * FROM projects WHERE tenant_id = $1',
[tenantId]
);
Connection Pooling
const { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 20, // Max 20 concurrent connections
idleTimeoutMillis: 30000, // Close idle after 30s
connectionTimeoutMillis: 2000 // Timeout after 2s
});
Per-Tenant Connection Limits (Stop Noisy Neighbors)
const tenantPools = new Map();
function getTenantPool(tenantId, plan) {
if (!tenantPools.has(tenantId)) {
const limits = { free: 2, pro: 5, enterprise: 20 };
tenantPools.set(tenantId, new Pool({
connectionString: process.env.DATABASE_URL,
max: limits[plan] || 2
}));
}
return tenantPools.get(tenantId);
}
Application Scaling
Stateless Servers (Scale Horizontally)
// Session stored in Redis (not in server memory!)
app.use(session({
store: new RedisStore({ client: redis }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}));
// Add servers anytime - no session data lost!
Noisy Neighbor Prevention
// Rate Limiting Per Tenant
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
keyGenerator: (req) => req.user?.tenantId, // Key by tenant!
max: 1000, // 1000 requests
windowMs: 60 * 1000 // per minute
});
app.use(limiter);
// Resource Quotas
const tenantQuotas = {
free: { storage: '5GB', apiCalls: 10000 },
pro: { storage: '50GB', apiCalls: 100000 },
enterprise: { storage: 'unlimited', apiCalls: 'unlimited' }
};
Caching Layer
function cache(key, ttlSeconds, fetchFn) {
const cacheKey = `tenant:${tenantId}:${key}`;
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
const data = await fetchFn();
await redis.setex(cacheKey, ttlSeconds, JSON.stringify(data));
return data;
}
// Usage
const projects = await cache('projects', 300, () =>
db('projects').where({ tenant_id: tenantId })
);
Queue Workers
const Queue = require('bull');
const emailQueue = new Queue('email', { redis: { port: 6379 } });
// Add job with tenant context
await emailQueue.add('send-welcome', { userId, tenantId });
// Process (with tenant validation)
emailQueue.process(async (job) => {
const { userId, tenantId } = job.data;
// Always validate tenant!
const tenant = await db('tenants').where({ id: tenantId }).first();
if (!tenant) throw new Error('Invalid tenant');
await sendWelcomeEmail(userId);
});
6. Migration: Single-Tenant → Multi-Tenant
Phase 1: Database Changes (Week 1)
-- Add tenant_id to all tables
ALTER TABLE users ADD COLUMN tenant_id UUID;
ALTER TABLE projects ADD COLUMN tenant_id UUID;
ALTER TABLE tasks ADD COLUMN tenant_id UUID;
-- Add indexes (CRITICAL for performance!)
CREATE INDEX idx_users_tenant ON users(tenant_id);
CREATE INDEX idx_projects_tenant ON projects(tenant_id);
CREATE INDEX idx_tasks_tenant ON tasks(tenant_id);
-- Backfill existing data
UPDATE users SET tenant_id = 'your-tenant-id';
UPDATE projects SET tenant_id = 'your-tenant-id';
UPDATE tasks SET tenant_id = 'your-tenant-id';
-- Make it required
ALTER TABLE users ALTER COLUMN tenant_id SET NOT NULL;
Phase 2: Application Changes (Week 2)
// Add tenant resolution middleware
app.use((req, res, next) => {
req.tenantId = extractTenantId(req); // From subdomain/JWT/URL
next();
});
// Update ALL queries to include tenant filter
// BEFORE (dangerous!):
app.get('/projects', async (req, res) => {
const projects = await db('projects'); // ❌ NO TENANT FILTER!
res.json(projects);
});
// AFTER (safe):
app.get('/projects', async (req, res) => {
const projects = await db('projects')
.where({ tenant_id: req.tenantId }); // ✅ ALWAYS FILTER!
res.json(projects);
});
Phase 3: Add Row-Level Security (Week 3)
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON projects
USING (tenant_id = current_setting('app.current_tenant'));
Phase 4: Testing (Week 4)
it('Prevents cross-tenant data access', async () => {
const tenantA = await createTenant('A');
const tenantB = await createTenant('B');
const projectB = await createProject('B Project', tenantB.id);
const response = await request(app)
.get(`/projects/${projectB.id}`)
.set('Authorization', `Bearer ${tenantAToken}`);
expect(response.status).toBe(403); // FORBIDDEN
});
Deployment Strategy
1. Deploy backwards-compatible code
(tenant_id nullable, both old and new code work)
↓
2. Monitor for errors (1 week)
↓
3. Make tenant_id NOT NULL
↓
4. Add row-level security (optional, later)
7. Monitoring & Observability
Tenant-Aware Metrics
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log({
timestamp: new Date().toISOString(),
tenant_id: req.user?.tenantId,
user_id: req.user?.id,
method: req.method,
path: req.path,
status: res.statusCode,
duration_ms: duration
});
metrics.record({
tenant: req.user?.tenantId,
status: res.statusCode,
duration
});
});
next();
});
Key Metrics to Track
Per-Tenant:
- Request rate (req/min)
- Error rate (%)
- Database query time (ms)
- Cache hit rate (%)
- Storage usage (MB)
- Active users
System-Wide:
- Noisy neighbor detection
- Resource utilization
- Cost per tenant
Structured Logging
{
"timestamp": "2024-01-15T10:00:00Z",
"tenant_id": "abc-123",
"user_id": "user-456",
"level": "INFO",
"message": "User accessed dashboard",
"request_id": "req-789",
"method": "GET",
"path": "/dashboard",
"status": 200,
"duration_ms": 45
}
8. Security Best Practices
Data Protection
- TLS 1.3 for data in transit
- AES-256 for data at rest
- Tenant-specific encryption keys (advanced)
Access Control
Principle of Least Privilege:
- Tenant can only access THEIR data
- Users only access their tenant's data
- No cross-tenant queries EVER
- Row-level security policies
- tenant_id in ALL queries
- No cross-tenant joins allowed
Audit Logging
{
timestamp: "2024-01-15T10:00:00Z",
tenant_id: "abc-123",
user_id: "user-456",
action: "DELETE_PROJECT",
resource_type: "project",
resource_id: "proj-789",
ip_address: "203.0.113.42",
outcome: "SUCCESS",
before_state: { name: "Old Project" },
after_state: null
}
9. Compliance
GDPR
- Data portability per tenant
- Right to deletion
- Data processing agreements
- EU data residency options
- Encryption at rest and in transit
SOC 2
- Access controls
- Change management
- Monitoring and alerting
- Incident response
- Regular security audits
HIPAA
- Business Associate Agreements (BAA) per tenant
- Enhanced encryption
- Access audit trails
- Data segmentation per tenant
- 7-year retention policies
Data Residency
{
"tenant_id": "eu-customer",
"data_residency": "eu-west-1",
"encryption_key_region": "eu-west-1"
}
10. Implementation Roadmap
Phase 1: Foundation (Weeks 1-2) ✅ MUST DO
- Add tenant_id to ALL tables
- Create indexes on tenant_id
- Create tenant resolution middleware
- Implement tenant context
- Update ALL queries with tenant filter
- Test isolation
Phase 2: Security (Weeks 3-4) ✅ CRITICAL
- Tenant-aware authorization
- Row-level security
- Tenant-aware caching
- Isolation tests
- Security audit
- Audit logging
Phase 3: Features (Weeks 5-6) ✅ IMPORTANT
- Tenant management UI
- Onboarding workflow
- Billing integration
- Tenant configuration
- Feature flags
- Custom domains
Phase 4: Scale (Weeks 7-8) ✅ PERFORMANCE
- Connection pooling
- Redis caching
- Rate limiting
- Read replicas
- Load balancer
- Performance testing
Phase 5: Monitoring (Weeks 9-10) ✅ OBSERVABILITY
- Tenant metrics
- Per-tenant alerting
- Audit log dashboard
- Cost tracking
- Error tracking
- Performance monitoring
11. Common Pitfalls & Solutions
❌ Pitfall 1: Missing Tenant Filter = DATA BREACH
// ❌ DANGER: No tenant filter!
const users = await db.raw('SELECT * FROM users WHERE email = ?', [email]);
// ✅ SAFE: Always filter by tenant_id
const users = await db('users')
.where({
tenant_id: req.user.tenantId, // ← ALWAYS HERE
email: email
});
Prevention:
- Use query builder that auto-adds tenant filter
- Code review: "Is tenant_id in where clause?"
- Automated tests on all queries
❌ Pitfall 2: Cross-Tenant Joins
-- ❌ DANGER: Missing tenant_id in JOIN!
SELECT * FROM orders o
JOIN users u ON o.user_id = u.id -- Missing tenant_id!
WHERE o.tenant_id = ?
-- ✅ SAFE: Always join on tenant_id too
SELECT * FROM orders o
JOIN users u ON o.user_id = u.id AND o.tenant_id = u.tenant_id
WHERE o.tenant_id = ?
Prevention:
- Query builder adds tenant_id to all joins
- Lint rules for joins
- Code review checklist
❌ Pitfall 3: Cache Contamination
// ❌ DANGER: Cache shared across tenants!
const cacheKey = `user:${userId}`;
const cached = await redis.get(cacheKey);
// Tenant A gets Tenant B's cached data!
// ✅ SAFE: Tenant-aware cache keys
const cacheKey = `tenant:${tenantId}:user:${userId}`;
const cached = await redis.get(cacheKey);
// Each tenant has separate cache!
Prevention:
- Cache wrapper prepends tenant_id
- Lint rules for cache keys
- Multi-tenant testing
❌ Pitfall 4: Background Jobs Without Tenant
// ❌ DANGER: Job has no tenant context!
queue.add('send-email', { userId: 123 });
// Worker doesn't know which tenant!
// ✅ SAFE: Always include tenant in job data
queue.add('send-email', {
userId: 123,
tenantId: req.user.tenantId // ← ALWAYS HERE
});
// Worker validates tenant
worker.process(async (job) => {
const { userId, tenantId } = job.data;
const tenant = await db('tenants').where({ id: tenantId }).first();
if (!tenant) throw new Error('Invalid tenant');
const user = await db('users')
.where({ id: userId, tenant_id: tenantId })
.first();
await sendEmail(user.email);
});
Prevention:
- Queue requires tenant_id
- Worker validates tenant
- Alert on missing tenant_id
❌ Pitfall 5: No Row-Level Security
// ❌ DANGER: App-level check can be bypassed
app.get('/projects/:id', async (req, res) => {
const project = await db('projects').where({ id: req.params.id }).first();
// What if someone calls this directly??
if (project.tenant_id !== req.user.tenant_id) {
return res.status(403); // Too late, data already queried!
}
res.json(project);
});
// ✅ SAFE: Row-Level Security (Database enforced!)
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON projects
USING (tenant_id = current_setting('app.current_tenant'));
// ✅ ALSO: Application check (defense in depth)
app.get('/projects/:id', async (req, res) => {
const project = await db('projects')
.where({
id: req.params.id,
tenant_id: req.user.tenant_id // Still filter in app!
})
.first();
if (!project) return res.status(404).json({ error: 'Not found' });
res.json(project);
});
Prevention:
- Enable RLS on all tables
- Defense in depth (app + db)
- Regular security audits
12. Backup Strategies
Shared Schema: Point-in-Time Recovery (PITR)
# Enable WAL archiving
# postgresql.conf:
archive_mode = on
archive_command = 'cp %p /backup/wal/%f'
# Restore to any point in time
Per-Tenant Extraction
# Backup one tenant
pg_dump saas_db \
--data-only \
--where="tenant_id = 'abc-123'" \
> tenant_backup.sql
Separate Database: Simple
# One database per tenant = one backup per tenant
pg_dump tenant_abc_db > backup.sql
Best Practices
- Test restores regularly
- 3-2-1 rule: 3 copies, 2 media, 1 offsite
- Automate everything
- Encrypt sensitive backups
- Document recovery procedure
- Monitor backup status
13. Decision Matrix
| Factor | Shared Schema | Separate Schema | Separate DB |
|---|---|---|---|
| Cost | $ (Low) | $$ (Medium) | $$$ (High) |
| Isolation | Low | Medium | High |
| Compliance | Hard | Moderate | Easy |
| Scaling | Easy | Moderate | Complex |
| Backup | Complex | Moderate | Easy |
| Best For | Startups | Mid-market | Enterprise |
Recommendation: Start with Shared Schema, evolve as needed.
14. Key Takeaways
- Start Simple: Begin with shared schema, evolve as needed
- Isolate Relentlessly: Every query, every cache, every job
- Plan for Scale: Connection pooling, sharding, caching
- Security First: Row-level security, audit logs, encryption
- Monitor Everything: Per-tenant metrics and alerts
- Test Thoroughly: Isolation testing, load testing
- Evolve Gradually: Add complexity as needed, not all at once
15. Emergency Checklist
If You Suspect a Data Breach
- ✋ STOP all data access immediately
- 🔍 Identify affected tenants
- 📊 Audit all queries without tenant filters
- 🔐 Disable compromised accounts
- 📝 Document everything
- 🗣️ Notify affected customers
- 🔧 Fix the root cause
- ✅ Test thoroughly before restoring
16. Quick Reference
Must-Have Security
- All tables have tenant_id
- All queries filter by tenant_id
- Row-level security enabled
- Tenant-aware middleware
- No cross-tenant joins
- Tenant-aware caching
- Audit logging enabled
- Rate limiting per tenant
- Encryption (TLS + at rest)
- Regular security audits
Implementation Priority
Week 1-2: Foundation
✓ Add tenant_id to all tables
✓ Create tenant middleware
✓ Update queries with filters
Week 3-4: Security
✓ Implement authorization
✓ Add row-level security
✓ Security audit
Week 5-6: Features
✓ Tenant management UI
✓ Provisioning workflow
✓ Billing integration
Week 7-8: Scale
✓ Connection pooling
✓ Caching layer
✓ Rate limiting
Week 9-10: Monitoring
✓ Tenant metrics
✓ Per-tenant alerting
✓ Audit logging
17. Questions?
Common Questions:
- Which architecture pattern should I start with? → Shared Schema
- How do I implement row-level security? → PostgreSQL RLS
- What about multi-tenant authentication? → JWT with tenant info
- How do I handle tenant-specific customizations? → Configuration over code
- What are the best backup practices? → PITR or per-tenant backups
- How do I migrate from single-tenant? → Gradual, careful migration
- What about rate limiting and scaling? → Per-tenant limits, stateless servers
Need help? Check the full guide above or ask specific questions!
Last Updated: January 2024
Version: 1.0