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?"
Practice
Solution
Step 1: Understand transaction purpose
Transactions are designed to keep data changes safe and consistent when multiple users might update the same data.Step 2: Eliminate unrelated options
Speeding up retrieval, storing files, or sending notifications are not the main goals of transactions.Final Answer:
To ensure data changes are safe and consistent -> Option BQuick Check:
Transaction purpose = safe and consistent data [OK]
- Thinking transactions speed up data retrieval
- Confusing transactions with file storage
- Assuming transactions send notifications
Solution
Step 1: Recall Firebase transaction syntax
The correct method to start a transaction is callingtransaction()on a database reference.Step 2: Check each option
database.ref('path').transaction(updateFunction) usesref('path').transaction(updateFunction), which is correct. Options A, B, and D use incorrect method names or call patterns.Final Answer:
database.ref('path').transaction(updateFunction) -> Option AQuick Check:
Correct method is .transaction() on ref [OK]
- Using .setTransaction() which does not exist
- Calling transaction directly on database object
- Using .runTransaction() which is invalid
database.ref('counter').transaction(currentValue => {
if (currentValue === null) {
return 1;
} else {
return currentValue + 1;
}
});
What will be the value of 'counter' after this transaction if it was initially 5?Solution
Step 1: Analyze the transaction function logic
The function checks if the current value is null; if so, it returns 1. Otherwise, it returns currentValue + 1.Step 2: Apply initial value 5
Since currentValue is 5 (not null), the function returns 5 + 1 = 6.Final Answer:
6 -> Option AQuick Check:
5 + 1 = 6 [OK]
- Assuming value stays the same
- Confusing null check logic
- Returning 1 regardless of current value
database.ref('score').transaction(() => {
database.ref('score').set(10);
return 20;
});Solution
Step 1: Understand transaction function rules
All reads must happen before any writes inside the transaction function to ensure consistency.Step 2: Identify the problem in code
The code callsset(10)inside the transaction function before returning a new value, which violates the rule.Final Answer:
Reads must happen before writes inside the transaction function -> Option CQuick Check:
Transaction rule: read before write [OK]
- Calling set() inside transaction function
- Returning a value is allowed and required
- Thinking transaction function must be async
database.ref('users/user1/points').transaction(currentPoints => {
// Your code here
});Solution
Step 1: Understand the condition to increment points
Points should increment only if currentPoints is less than 100 or if it is null (no points yet).Step 2: Check each option logic
if (currentPoints === null || currentPoints < 100) { return (currentPoints || 0) + 1; } else { return currentPoints; } increments points by 1 if currentPoints is null or less than 100, else returns currentPoints unchanged. This matches the requirement. if (currentPoints >= 100) { return currentPoints + 1; } else { return currentPoints; } increments when points are 100 or more, which is wrong. return currentPoints + 1; always increments ignoring the limit. if (currentPoints === null) { return 0; } else { return 100; } resets points incorrectly.Final Answer:
if (currentPoints === null || currentPoints < 100) { return (currentPoints || 0) + 1; } else { return currentPoints; } -> Option DQuick Check:
Increment only if points < 100 or null [OK]
- Incrementing points when already 100 or more
- Ignoring null initial value
- Resetting points instead of incrementing
Ready to prove it?
Pass the test and this pattern moves unknown
