Design a MongoDB schema to handle multi-tenant SaaS applications.
Instruction: Explain your approach to designing a MongoDB schema for a Software as a Service (SaaS) application that must segregate data for multiple tenants securely and efficiently.
Updated
Official answer
Choose isolation from the tenants' security, scale, customization and recovery requirements. Separate databases can support distinct database-user permissions, but databases on one cluster still share infrastructure and some operational scope. Dedicated deployments provide stronger separation at greater cost. Shared collections are a conscious application-enforced isolation choice.
For shared collections, put tenantId on each tenant-owned document and derive the permitted tenant from authenticated server-side context. Never trust a request-supplied tenantId by itself. Scope reads, updates, deletes, bulk operations, joins, exports, caches and background jobs consistently. An index or document ACL field does not enforce this automatically.
Use compound indexes matching tenant-scoped access patterns. A unique business key generally needs tenantId in its uniqueness definition when uniqueness is per tenant. Include tenant identity in references and verify both sides belong to the same tenant. Plan migrations and backfills for missing tenant fields.
Test adversarial cross-tenant requests, guessed IDs, stale cache keys and administrative paths. Apply least privilege and minimize sensitive data in logs. For noisy neighbors, enforce resource limits and measure per-tenant workload; sharding solely by tenantId can leave a very large tenant concentrated on one shard.
Document which boundaries are database-enforced and which rely on application code. Choose stronger isolation when those application controls do not meet the requirements.