Firestore trigger functions in Firebase - Time & Space Complexity
When using Firestore trigger functions, it's important to understand how the time to run your function changes as your data grows.
We want to know how the number of operations grows when many documents trigger the function.
Analyze the time complexity of the following Firestore trigger function.
exports.onUserUpdate = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
const newData = change.after.data();
const oldData = change.before.data();
if (newData.status !== oldData.status) {
return updateUserStats(context.params.userId);
}
return null;
});
function updateUserStats(userId) {
// Updates stats for the user
return admin.firestore().collection('stats').doc(userId).set({ updated: true });
}
This function triggers when a user document changes. It checks if the status changed, then updates stats for that user.
Look for repeated actions that affect performance.
- Primary operation: The function runs once per document update event.
- How many times: It runs once for each user document that changes.
As more user documents update, the function runs more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function runs |
| 100 | 100 function runs |
| 1000 | 1000 function runs |
Pattern observation: The number of operations grows directly with the number of document updates.
Time Complexity: O(n)
This means the total work grows linearly with the number of document updates triggering the function.
[X] Wrong: "The function runs once and handles all document updates at once."
[OK] Correct: Each document update triggers the function separately, so the work adds up with more updates.
Understanding how trigger functions scale helps you design efficient backend processes that respond well as your app grows.
What if the function also queried a collection of related documents for each update? How would the time complexity change?