Transaction read-then-write pattern in Firebase - Time & Space Complexity
When using Firebase transactions, we want to know how the time to complete changes as we work with more data.
We ask: How does the number of reads and writes grow when we update data inside a transaction?
Analyze the time complexity of the following operation sequence.
const docRef = firestore.doc('items/item1');
firestore.runTransaction(async (transaction) => {
const doc = await transaction.get(docRef);
const currentCount = doc.data().count || 0;
transaction.update(docRef, { count: currentCount + 1 });
});
This code reads a document's current count and then updates it inside a transaction to add one.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: One read (get) and one write (update) inside the transaction.
- How many times: Each transaction attempt does one read and one write; retries may repeat these.
Each transaction reads and writes one document regardless of data size.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 reads + 10 writes (one per transaction) |
| 100 | 100 reads + 100 writes |
| 1000 | 1000 reads + 1000 writes |
Pattern observation: The number of operations grows linearly with the number of transactions.
Time Complexity: O(n)
This means the total time grows directly in proportion to how many transactions you run.
[X] Wrong: "The transaction reads once and then updates many documents at the same time, so it's constant time."
[OK] Correct: Each transaction reads and writes only the documents it touches. If you update many documents, each requires its own read and write, so time grows with the number of documents.
Understanding how transactions scale helps you design reliable apps that handle data safely and efficiently.
"What if the transaction updated multiple documents instead of one? How would the time complexity change?"