Realtime Database vs Firestore decision in Firebase - Performance Comparison
When choosing between Firebase Realtime Database and Firestore, it's important to understand how their operation costs grow as your data or users increase.
We want to see how the number of database calls changes when reading or writing data.
Analyze the time complexity of reading a list of user messages from each database.
// Realtime Database
const messagesRef = firebase.database().ref('messages');
messagesRef.once('value').then(snapshot => {
const messages = snapshot.val();
// process messages
});
// Firestore
const messagesCollection = firebase.firestore().collection('messages');
messagesCollection.get().then(querySnapshot => {
querySnapshot.forEach(doc => {
const message = doc.data();
// process message
});
});
This code reads all messages once from each database type to process them.
Look at what happens repeatedly when reading data.
- Primary operation: Reading each message record from the database.
- How many times: Once per message in the list.
As the number of messages grows, the number of read operations grows too.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 1 read |
| 100 | 1 read |
| 1000 | 1 read |
Pattern observation: The number of operations grows directly with the number of messages.
Time Complexity: O(n)
This means the time to read all messages grows linearly with how many messages there are.
[X] Wrong: "Reading a large list from Firestore or Realtime Database is always a single operation regardless of size."
[OK] Correct: Each message is a separate read operation, so more messages mean more reads and longer time.
Understanding how database reads scale helps you design apps that stay fast as they grow. This skill shows you can think about real-world app performance.
"What if we used Firestore queries to limit results instead of reading all messages? How would the time complexity change?"