Multi-Tenant Systems
Multi-tenant systems host many customers (tenants) on the same infrastructure while keeping their data isolated.
Introduction
Multi-tenant systems host many customers (tenants) on the same infrastructure while keeping their data isolated. MongoDB supports the full spectrum — from a single shared cluster with tenantId on every document, to one cluster per enterprise tenant — and the choice is mostly an economic and compliance question.
This lesson covers the three patterns, when to use each, and how to combine them in a single platform.
Understanding the topic
The three multi-tenant patterns:
- Shared collection + tenantId — cheapest, densest, scales horizontally with sharding by tenant.
- Database-per-tenant — stronger isolation, easy per-tenant backup/restore, hits catalog limits beyond ~10k tenants.
- Cluster-per-tenant — full isolation, full cost; reserved for whales and regulated tenants.
- Hybrid — long tail in shared, top 1% in dedicated clusters; one platform code-base.
- Zone sharding — pin tenant data to a region for residency/latency.
- Per-tenant encryption keys — CSFLE for cryptographic isolation when compliance demands.
Syntax reference
Choose by tenant count + isolation requirement:
Tenants Pattern Why─────────────────────────────────────────────────────────────────────────────1 – 10 000+ Shared collection + tenantId Cheapest, scales fine100 – ~5 000 Database-per-tenant Easy backup/restore1 – ~100 (whales) Cluster-per-tenant Hard isolation, complianceMix of all three Hybrid Reality at scale
Informative example
Repository enforces tenant scoping for the shared pattern:
class TenantScopedRepo<T> {constructor(private col: Collection<T & { tenantId: string }>, private tid: string) {}find(filter: Filter<T> = {}) {return this.col.find({ ...filter, tenantId: this.tid } as any).toArray();}insertOne(doc: OptionalUnlessRequiredId<T>) {return this.col.insertOne({ ...doc, tenantId: this.tid } as any);}}
Real-world use
Most B2B SaaS run shared-collection multi-tenancy with a tenantId field; large enterprise customers get moved to dedicated databases or clusters on demand. Atlas project + cluster split makes that promotion a 1-day migration.
Best practices
- Enforce tenant scoping in the repository, never trust the request layer.
- tenantId first in every compound index and shard key.
- Cap noisy-neighbor tenants with quotas; export hot ones to dedicated clusters.
- Always run periodic cross-tenant leak tests against your repo layer.
Common mistakes
- One query without
tenantId= catastrophic data leak. - Going database-per-tenant at scale — catalog explodes past 10k tenants.
- Mixing payment tiers in a single shared cluster without quotas.