Transaction basics in Firebase - Time & Space Complexity
When using transactions in Firebase, it's important to know how the time to complete changes as more data is involved.
We want to understand how the number of reads and writes inside a transaction affects its execution time.
Analyze the time complexity of this Firebase transaction code.
const docRef = firestore.doc('items/item1');
firestore.runTransaction(async (transaction) => {
const doc = await transaction.get(docRef);
const newCount = (doc.data().count || 0) + 1;
transaction.update(docRef, { count: newCount });
return newCount;
});
This code reads a document, updates a count field, and writes it back inside a transaction.
Look at the main actions inside the transaction.
- Primary operation: One read (get) and one write (update) on the document.
- How many times: Each transaction run does these operations once per document involved.
As the number of documents involved grows, the transaction does more reads and writes.
| Input Size (n documents) | Approx. Api Calls/Operations |
|---|---|
| 1 | 1 read + 1 write |
| 10 | 10 reads + 10 writes |
| 100 | 100 reads + 100 writes |
Pattern observation: The number of operations grows directly with the number of documents involved.
Time Complexity: O(n)
This means the time grows linearly with the number of documents read and written in the transaction.
[X] Wrong: "Transactions always take the same time no matter how many documents they touch."
[OK] Correct: Each document read and write adds work, so more documents mean more time.
Understanding how transaction time grows helps you design efficient data updates and shows you can reason about cloud operations clearly.
"What if the transaction reads multiple documents but only writes to one? How would the time complexity change?"