Bird
Raised Fist0
Firebasecloud~20 mins

Transaction basics in Firebase - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Firebase Transaction Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ service_behavior
intermediate
2:00remaining
What is the output of this Firebase transaction code?

Consider this Firebase transaction on a document with initial field count: 5. What will be the final value of count after this transaction completes successfully?

Firebase
const docRef = firestore.collection('counters').doc('counter1');

await firestore.runTransaction(async (transaction) => {
  const doc = await transaction.get(docRef);
  const newCount = (doc.data()?.count ?? 0) + 3;
  transaction.update(docRef, { count: newCount });
});
A0
B3
C5
D8
Attempts:
2 left
💡 Hint

Think about how the transaction reads the current value and adds 3.

🧠 Conceptual
intermediate
1:30remaining
Which statement about Firebase transactions is true?

Choose the correct statement about Firebase transactions.

ATransactions can only update one document at a time.
BTransactions automatically retry if data changes during the transaction.
CTransactions do not guarantee atomicity across multiple documents.
DTransactions can only read data but cannot write updates.
Attempts:
2 left
💡 Hint

Think about how Firebase handles concurrent updates inside transactions.

❓ Configuration
advanced
2:00remaining
What error occurs with this Firebase transaction code?

What error will this Firebase transaction code raise when executed?

Firebase
const docRef = firestore.collection('users').doc('user1');

await firestore.runTransaction(async (transaction) => {
  transaction.update(docRef, { score: 10 });
  const doc = await transaction.get(docRef);
  console.log(doc.data());
});
ATransactionError: Cannot update before reading document
BSyntaxError: Missing await before transaction.update
CNo error, transaction runs successfully
DTypeError: transaction.update is not a function
Attempts:
2 left
💡 Hint

Check the order of operations allowed in Firebase transactions.

❓ security
advanced
1:30remaining
Which Firebase security rule prevents unauthorized transaction writes?

Given a Firestore collection orders, which security rule correctly prevents users from updating orders they do not own, even inside transactions?

Aallow update: if request.auth.uid == resource.data.ownerId;
Ballow update: if request.auth.uid != resource.data.ownerId;
Callow update: if request.auth.token.admin == true;
Dallow update: if request.time < timestamp.date(2025, 1, 1);
Attempts:
2 left
💡 Hint

Think about how to restrict updates to only the owner of the document.

❓ Architecture
expert
2:30remaining
What is the best explanation for why Firebase transactions retry automatically?

Firebase transactions retry automatically when data changes during the transaction. Why is this behavior important in distributed systems?

ATo ensure eventual consistency by resolving conflicts caused by concurrent updates.
BTo reduce network traffic by batching multiple writes into one request.
CTo prevent any writes from happening if the user is offline.
DTo guarantee that transactions always complete within a fixed time limit.
Attempts:
2 left
💡 Hint

Consider how multiple users might update the same data at the same time.

Practice

(1/5)
1. What is the main purpose of using a transaction in Firebase?
easy
A. To speed up data retrieval
B. To ensure data changes are safe and consistent
C. To store large files
D. To send notifications to users

Solution

  1. Step 1: Understand transaction purpose

    Transactions are designed to keep data changes safe and consistent when multiple users might update the same data.
  2. Step 2: Eliminate unrelated options

    Speeding up retrieval, storing files, or sending notifications are not the main goals of transactions.
  3. Final Answer:

    To ensure data changes are safe and consistent -> Option B
  4. Quick Check:

    Transaction purpose = safe and consistent data [OK]
Hint: Transactions protect data integrity during concurrent updates [OK]
Common Mistakes:
  • Thinking transactions speed up data retrieval
  • Confusing transactions with file storage
  • Assuming transactions send notifications
2. Which of the following is the correct way to start a transaction in Firebase Realtime Database?
easy
A. database.ref('path').transaction(updateFunction)
B. database.ref('path').setTransaction(updateFunction)
C. database.transaction('path', updateFunction)
D. database.ref('path').runTransaction(updateFunction)

Solution

  1. Step 1: Recall Firebase transaction syntax

    The correct method to start a transaction is calling transaction() on a database reference.
  2. Step 2: Check each option

    database.ref('path').transaction(updateFunction) uses ref('path').transaction(updateFunction), which is correct. Options A, B, and D use incorrect method names or call patterns.
  3. Final Answer:

    database.ref('path').transaction(updateFunction) -> Option A
  4. Quick Check:

    Correct method is .transaction() on ref [OK]
Hint: Use .transaction() on a database reference to start [OK]
Common Mistakes:
  • Using .setTransaction() which does not exist
  • Calling transaction directly on database object
  • Using .runTransaction() which is invalid
3. Consider this transaction code snippet:
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?
medium
A. 6
B. 1
C. null
D. 5

Solution

  1. 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.
  2. Step 2: Apply initial value 5

    Since currentValue is 5 (not null), the function returns 5 + 1 = 6.
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    5 + 1 = 6 [OK]
Hint: If value exists, transaction adds 1; else sets to 1 [OK]
Common Mistakes:
  • Assuming value stays the same
  • Confusing null check logic
  • Returning 1 regardless of current value
4. What is wrong with this Firebase transaction code?
database.ref('score').transaction(() => {
  database.ref('score').set(10);
  return 20;
});
medium
A. You cannot return a value in a transaction function
B. Calling set() inside transaction causes an error
C. Reads must happen before writes inside the transaction function
D. Transaction function must be async

Solution

  1. Step 1: Understand transaction function rules

    All reads must happen before any writes inside the transaction function to ensure consistency.
  2. Step 2: Identify the problem in code

    The code calls set(10) inside the transaction function before returning a new value, which violates the rule.
  3. Final Answer:

    Reads must happen before writes inside the transaction function -> Option C
  4. Quick Check:

    Transaction rule: read before write [OK]
Hint: Do all reads before any writes inside transaction function [OK]
Common Mistakes:
  • Calling set() inside transaction function
  • Returning a value is allowed and required
  • Thinking transaction function must be async
5. You want to increment a user's points only if their current points are less than 100. Which transaction function correctly implements this logic?
database.ref('users/user1/points').transaction(currentPoints => {
  // Your code here
});
hard
A. if (currentPoints === null) { return 0; } else { return 100; }
B. if (currentPoints >= 100) { return currentPoints + 1; } else { return currentPoints; }
C. return currentPoints + 1;
D. if (currentPoints === null || currentPoints < 100) { return (currentPoints || 0) + 1; } else { return currentPoints; }

Solution

  1. 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).
  2. 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.
  3. Final Answer:

    if (currentPoints === null || currentPoints < 100) { return (currentPoints || 0) + 1; } else { return currentPoints; } -> Option D
  4. Quick Check:

    Increment only if points < 100 or null [OK]
Hint: Check null or less than 100 before incrementing [OK]
Common Mistakes:
  • Incrementing points when already 100 or more
  • Ignoring null initial value
  • Resetting points instead of incrementing
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