Bird
Raised Fist0
Firebasecloud~20 mins

Transaction read-then-write pattern in Firebase - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Firebase Transaction Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ service_behavior
intermediate
2:00remaining
What happens if a Firebase transaction reads stale data?

In Firebase Realtime Database, a transaction reads data, modifies it, then writes it back. What happens if the data read is outdated because another client updated it just before the write?

AThe transaction queues the write and applies it after all other writes.
BThe transaction automatically retries with the latest data until it succeeds or fails.
CThe transaction fails immediately with a conflict error.
DThe transaction overwrites the other client's update without warning.
Attempts:
2 left
💡 Hint

Think about how Firebase ensures data consistency when multiple clients write simultaneously.

❓ Architecture
intermediate
2:00remaining
Which Firebase transaction pattern ensures atomic update of a user's score after reading it?

You want to increase a user's score by 10 points only if their current score is less than 100. Which transaction pattern correctly implements this?

Firebase
const userScoreRef = firebase.database().ref('scores/user123');

// Which code snippet correctly updates the score atomically?
A
userScoreRef.transaction(currentScore => {
  if (currentScore < 100) {
    return currentScore + 10;
  } else {
    return currentScore;
  }
});
B
userScoreRef.once('value').then(snapshot => {
  const score = snapshot.val();
  if (score < 100) {
    userScoreRef.set(score + 10);
  }
});
CuserScoreRef.set(firebase.database.ServerValue.increment(10));
DuserScoreRef.update({score: firebase.database.ServerValue.increment(10)});
Attempts:
2 left
💡 Hint

Consider atomicity and reading the current value before writing.

❓ security
advanced
2:00remaining
How do Firebase security rules affect transaction read-then-write operations?

When a Firebase transaction reads data and writes back an update, how do security rules influence the transaction's success?

AThe transaction fails if the client lacks read or write permission on the data path.
BThe transaction ignores security rules during the read phase but enforces them on write.
CSecurity rules only apply after the transaction commits successfully.
DThe transaction bypasses security rules if it uses server-side SDKs.
Attempts:
2 left
💡 Hint

Think about how Firebase enforces security on both reading and writing data.

✅ Best Practice
advanced
2:00remaining
What is the best practice to minimize transaction retries in Firebase?

Firebase transactions retry automatically if data changes during the transaction. Which practice helps reduce the number of retries?

ARead large data snapshots inside the transaction to ensure accuracy.
BUse multiple nested transactions to isolate updates on different data paths.
CDisable security rules temporarily during transactions to speed up writes.
DKeep the transaction callback logic simple and fast to reduce time spent inside the transaction.
Attempts:
2 left
💡 Hint

Consider what causes transaction retries and how to avoid conflicts.

🧠 Conceptual
expert
2:00remaining
Why does Firebase transaction callback receive null on first read sometimes?

In a Firebase transaction, the callback function sometimes receives null as the current data value even though data exists. Why does this happen?

ABecause the data was deleted by another client just before the transaction started.
BBecause the transaction failed to read data due to permission errors.
CBecause the local cache has no data yet, so the transaction starts with null before syncing from server.
DBecause the transaction callback always receives null on the first call by design.
Attempts:
2 left
💡 Hint

Think about how Firebase clients sync data locally before server confirmation.

Practice

(1/5)
1. What is the main purpose of using a transaction in Firebase when updating data?
easy
A. To speed up data retrieval from the database
B. To store data permanently without changes
C. To safely read and write data together without conflicts
D. To delete data automatically after a set time

Solution

  1. Step 1: Understand transaction role

    Transactions allow reading and writing data atomically, meaning both happen together safely.
  2. Step 2: Identify conflict prevention

    This prevents conflicts when multiple users try to update the same data at once.
  3. Final Answer:

    To safely read and write data together without conflicts -> Option C
  4. Quick Check:

    Transaction = safe read-write [OK]
Hint: Transactions combine read and write safely [OK]
Common Mistakes:
  • Thinking transactions only speed up reads
  • Assuming transactions delete data
  • Believing transactions store data permanently without changes
2. Which of the following is the correct syntax to start a transaction in Firebase Firestore using JavaScript?
easy
A. db.startTransaction(() => { /* code */ })
B. db.transactionStart(() => { /* code */ })
C. db.beginTransaction(async () => { /* code */ })
D. db.runTransaction(async (transaction) => { /* code */ })

Solution

  1. Step 1: Recall Firestore transaction syntax

    The correct method to run a transaction is db.runTransaction with an async callback.
  2. Step 2: Check other options

    Other options like transactionStart, beginTransaction, or startTransaction are not valid Firestore methods.
  3. Final Answer:

    db.runTransaction(async (transaction) => { /* code */ }) -> Option D
  4. Quick Check:

    runTransaction is correct method [OK]
Hint: Use db.runTransaction with async callback [OK]
Common Mistakes:
  • Using non-existent methods like transactionStart
  • Forgetting async keyword in callback
  • Confusing transaction syntax with other database APIs
3. Given this transaction code snippet, what will be the final value of the 'count' field if the document initially has count = 5?
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 });
  }
});
medium
A. 6
B. 1
C. 5
D. 0

Solution

  1. Step 1: Check if document exists

    The document exists with count = 5, so the else block runs.
  2. Step 2: Calculate new count

    New count is 5 + 1 = 6, and transaction updates the document with this value.
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Existing count + 1 = 6 [OK]
Hint: If doc exists, increment count by 1 [OK]
Common Mistakes:
  • Assuming count resets to 1 even if doc exists
  • Forgetting to add 1 to existing count
  • Confusing set and update behavior
4. Identify the error in this transaction code snippet:
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 });
  }
});
medium
A. Missing check if document exists before accessing data
B. Using transaction.update instead of transaction.set
C. Not awaiting transaction.update call
D. Incorrect collection name syntax

Solution

  1. Step 1: Check document existence

    The code accesses doc.data().stock without verifying if doc.exists, which can cause errors if doc is missing.
  2. 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.
  3. Final Answer:

    Missing check if document exists before accessing data -> Option A
  4. Quick Check:

    Always check doc.exists before data [OK]
Hint: Always check doc.exists before reading data [OK]
Common Mistakes:
  • Skipping doc.exists check causing runtime errors
  • Confusing update with set methods
  • Expecting to await transaction.update explicitly
5. You want to implement a transaction that increments a user's score only if the current score is less than 100. Which of the following code snippets correctly applies the transaction read-then-write pattern to achieve this?
hard
A. db.runTransaction(async (transaction) => { const userRef = db.collection('users').doc('user1'); const doc = await transaction.get(userRef); if (doc.data().score < 100) { transaction.set(userRef, { score: doc.data().score + 1 }); } });
B. 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 }); } });
C. db.runTransaction(async (transaction) => { const userRef = db.collection('users').doc('user1'); const doc = await transaction.get(userRef); transaction.update(userRef, { score: 100 }); });
D. db.runTransaction(async (transaction) => { const userRef = db.collection('users').doc('user1'); transaction.update(userRef, { score: 1 }); });

Solution

  1. 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.
  2. 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.
  3. 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 B
  4. Quick Check:

    Check exists + condition before update [OK]
Hint: Check doc exists and condition before update [OK]
Common Mistakes:
  • Not checking if doc exists before reading data
  • Using set instead of update causing overwrite
  • Updating without condition or setting fixed value
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard