Multi-tenancy patterns in Firebase - Time & Space Complexity
When using Firebase for multi-tenancy, we want to know how the work grows as more tenants use the system.
We ask: How does the number of operations change when we add more tenants?
Analyze the time complexity of this Firebase data fetch for multiple tenants.
const tenants = ['tenantA', 'tenantB', 'tenantC'];
tenants.forEach(async (tenant) => {
const snapshot = await firebase.firestore()
.collection('tenants')
.doc(tenant)
.collection('users')
.get();
console.log(`${tenant} users count:`, snapshot.size);
});
This code fetches user data for each tenant separately from Firestore.
Look at what repeats as tenants increase.
- Primary operation: Firestore read for each tenant's users collection.
- How many times: Once per tenant in the list.
Each new tenant adds one more Firestore read operation.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 Firestore reads |
| 100 | 100 Firestore reads |
| 1000 | 1000 Firestore reads |
Pattern observation: The number of reads grows directly with the number of tenants.
Time Complexity: O(n)
This means the work grows in a straight line as you add more tenants.
[X] Wrong: "Fetching all tenants' data is just one operation regardless of tenant count."
[OK] Correct: Each tenant's data is stored separately, so Firebase must do a separate read for each tenant.
Understanding how operations grow with tenants helps you design scalable apps and explain your choices clearly.
What if we stored all tenants' users in a single collection with tenant IDs as fields? How would the time complexity change?