What if your app could magically prevent data mix-ups when many people update at once?
Why Transaction read-then-write pattern in Firebase? - Purpose & Use Cases
Imagine you are updating a shared shopping list on your phone while your friend is doing the same from theirs. You both try to add items at the same time without checking what the other has just added.
Without a careful process, your updates can overwrite each other, causing lost items or wrong quantities. Manually checking and updating data is slow and can easily cause mistakes, especially when many people use the app at once.
The transaction read-then-write pattern in Firebase helps by first reading the current data, then safely writing the update only if the data hasn't changed in the meantime. This keeps everyone's changes safe and consistent automatically.
db.collection('list').doc('shared').set({items: newItems})
const docRef = db.collection('list').doc('shared'); db.runTransaction(transaction => { return transaction.get(docRef).then(doc => { const currentItems = doc.data().items; const updatedItems = updateItems(currentItems); transaction.update(docRef, {items: updatedItems}); }); })
This pattern makes it possible to safely update shared data in real time without losing anyone's changes.
In a group budgeting app, multiple users can add expenses at the same time, and the total balance updates correctly without errors or lost data.
Manual updates can overwrite each other causing data loss.
Transaction read-then-write checks data before updating to keep it safe.
This ensures consistent and reliable shared data updates.
Practice
Solution
Step 1: Understand transaction role
Transactions allow reading and writing data atomically, meaning both happen together safely.Step 2: Identify conflict prevention
This prevents conflicts when multiple users try to update the same data at once.Final Answer:
To safely read and write data together without conflicts -> Option CQuick Check:
Transaction = safe read-write [OK]
- Thinking transactions only speed up reads
- Assuming transactions delete data
- Believing transactions store data permanently without changes
Solution
Step 1: Recall Firestore transaction syntax
The correct method to run a transaction is db.runTransaction with an async callback.Step 2: Check other options
Other options like transactionStart, beginTransaction, or startTransaction are not valid Firestore methods.Final Answer:
db.runTransaction(async (transaction) => { /* code */ }) -> Option DQuick Check:
runTransaction is correct method [OK]
- Using non-existent methods like transactionStart
- Forgetting async keyword in callback
- Confusing transaction syntax with other database APIs
db.runTransaction(async (transaction) => {
const docRef = db.collection('counters').doc('counter1');
const doc = await transaction.get(docRef);
if (!doc.exists) {
transaction.set(docRef, { count: 1 });
} else {
const newCount = doc.data().count + 1;
transaction.update(docRef, { count: newCount });
}
});Solution
Step 1: Check if document exists
The document exists with count = 5, so the else block runs.Step 2: Calculate new count
New count is 5 + 1 = 6, and transaction updates the document with this value.Final Answer:
6 -> Option AQuick Check:
Existing count + 1 = 6 [OK]
- Assuming count resets to 1 even if doc exists
- Forgetting to add 1 to existing count
- Confusing set and update behavior
db.runTransaction(async (transaction) => {
const docRef = db.collection('items').doc('item1');
const doc = await transaction.get(docRef);
const currentStock = doc.data().stock;
if (currentStock > 0) {
transaction.update(docRef, { stock: currentStock - 1 });
}
});Solution
Step 1: Check document existence
The code accesses doc.data().stock without verifying if doc.exists, which can cause errors if doc is missing.Step 2: Confirm other parts
transaction.update is correct for partial update, awaiting update is not needed as transaction methods handle it, and collection name syntax is correct.Final Answer:
Missing check if document exists before accessing data -> Option AQuick Check:
Always check doc.exists before data [OK]
- Skipping doc.exists check causing runtime errors
- Confusing update with set methods
- Expecting to await transaction.update explicitly
Solution
Step 1: Check document existence and condition
db.runTransaction(async (transaction) => { const userRef = db.collection('users').doc('user1'); const doc = await transaction.get(userRef); if (doc.exists && doc.data().score < 100) { transaction.update(userRef, { score: doc.data().score + 1 }); } }); correctly checks if the document exists and if the score is less than 100 before updating.Step 2: Verify update method and logic
It uses transaction.update to increment the score by 1 only when condition is met, preserving existing data.Final Answer:
db.runTransaction(async (transaction) => { const userRef = db.collection('users').doc('user1'); const doc = await transaction.get(userRef); if (doc.exists && doc.data().score < 100) { transaction.update(userRef, { score: doc.data().score + 1 }); } }); -> Option BQuick Check:
Check exists + condition before update [OK]
- Not checking if doc exists before reading data
- Using set instead of update causing overwrite
- Updating without condition or setting fixed value
Ready to prove it?
Pass the test and this pattern moves unknown
