Real-time listeners (onSnapshot) in Firebase - Time & Space Complexity
When using real-time listeners in Firebase, it is important to understand how the number of updates affects performance.
We want to know how the cost grows as more data changes and triggers updates.
Analyze the time complexity of setting up a real-time listener on a collection.
const unsubscribe = firestore.collection('messages')
.onSnapshot(snapshot => {
snapshot.docChanges().forEach(change => {
if (change.type === 'added') {
console.log('New message:', change.doc.data());
}
});
});
This code listens for new documents added to the 'messages' collection and processes each new message as it arrives.
Look at what happens repeatedly when data changes.
- Primary operation: Receiving and processing document change events from the listener.
- How many times: Once for each batch of changes sent by Firebase, which depends on how many documents change.
As more documents are added or changed, the listener receives more updates to process.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | Processes about 10 document change events |
| 100 | Processes about 100 document change events |
| 1000 | Processes about 1000 document change events |
Pattern observation: The number of operations grows roughly in direct proportion to the number of document changes.
Time Complexity: O(n)
This means the work done grows linearly with the number of document changes received by the listener.
[X] Wrong: "The listener only runs once and cost is constant no matter how many documents change."
[OK] Correct: The listener runs continuously and processes every change, so cost grows with the number of changes.
Understanding how real-time listeners scale helps you design apps that stay responsive and efficient as data grows.
What if we changed the listener to watch a single document instead of a collection? How would the time complexity change?