Bird
Raised Fist0
Firebasecloud~30 mins

Optimistic concurrency in Firebase - Mini Project: Build & Apply

Choose your learning style10 modes available
Optimistic Concurrency Control with Firebase
📖 Scenario: You are building a simple app where multiple users can update a shared document in Firebase Firestore. To avoid overwriting each other's changes, you will implement optimistic concurrency control using a version number.
🎯 Goal: Create a Firestore document with a version field, read and update it safely by checking the version to prevent conflicts.
📋 What You'll Learn
Create a Firestore document with a content string and a version number
Read the document and store its version
Write an update function that only updates if the version matches
Increment the version on successful update
💡 Why This Matters
🌍 Real World
Optimistic concurrency control is used in collaborative apps where multiple users edit shared data to prevent overwriting each other's changes.
💼 Career
Understanding concurrency control in cloud databases like Firestore is essential for backend and full-stack developers working on real-time applications.
Progress0 / 4 steps
1
Create initial Firestore document
Create a Firestore document in the collection sharedDocs with the ID doc1. The document should have two fields: content set to "Initial content" and version set to 1.
Firebase
Hint

Use setDoc with doc(db, 'sharedDocs', 'doc1') and set content and version fields.

2
Read document and store version
Write code to read the Firestore document doc1 from the sharedDocs collection. Store the document data in a variable called docData and the version field in a variable called currentVersion.
Firebase
Hint

Use getDoc to read the document, then extract version from the data.

3
Implement optimistic concurrency update logic
Write a function called updateContentIfVersionMatches that takes newContent and expectedVersion as parameters. It should read the document doc1, check if the version matches expectedVersion, and if so, update the content to newContent and increment the version by 1. Use Firestore transactions to ensure atomicity.
Firebase
Hint

Use runTransaction to read and update the document atomically. Check if version matches expectedVersion before updating.

4
Call update function with concurrency check
Call the function updateContentIfVersionMatches with newContent set to "Updated content" and expectedVersion set to the previously stored currentVersion variable.
Firebase
Hint

Call updateContentIfVersionMatches with the exact string 'Updated content' and the variable currentVersion.

Practice

(1/5)
1. What is the main purpose of optimistic concurrency in Firebase?
easy
A. To automatically backup data every hour
B. To speed up data retrieval by caching results
C. To encrypt data during transmission
D. To prevent overwriting data by checking for changes before updating

Solution

  1. Step 1: Understand optimistic concurrency concept

    Optimistic concurrency means checking if data changed before saving updates to avoid overwriting others' changes.
  2. Step 2: Match concept to Firebase usage

    Firebase uses transactions to check and update data atomically, which is an example of optimistic concurrency.
  3. Final Answer:

    To prevent overwriting data by checking for changes before updating -> Option D
  4. Quick Check:

    Optimistic concurrency = prevent overwrites [OK]
Hint: Optimistic concurrency checks data before saving updates [OK]
Common Mistakes:
  • Confusing optimistic concurrency with caching
  • Thinking it encrypts data
  • Assuming it backs up data automatically
2. Which Firebase method is used to safely update data with optimistic concurrency?
easy
A. firebase.database().set()
B. firebase.database().transaction()
C. firebase.database().push()
D. firebase.database().once()

Solution

  1. Step 1: Identify methods for data update in Firebase

    Methods like set() overwrite data directly, push() adds new data, once() reads data once.
  2. Step 2: Find method supporting atomic update with retry

    transaction() reads current data, applies update, retries if data changed during update, ensuring safe concurrency.
  3. Final Answer:

    firebase.database().transaction() -> Option B
  4. Quick Check:

    Safe update method = transaction() [OK]
Hint: Use transaction() for atomic updates with concurrency control [OK]
Common Mistakes:
  • Using set() which overwrites without concurrency check
  • Confusing push() with update methods
  • Using once() which only reads data
3. Consider this Firebase transaction code snippet:
const ref = firebase.database().ref('counter');
ref.transaction(current => {
  return (current || 0) + 1;
});

What happens if two users run this code at the same time?
medium
A. The counter increments by 1 only once
B. The counter resets to 0
C. The counter increments by 2 safely without overwriting
D. The transaction fails and throws an error

Solution

  1. Step 1: Understand transaction behavior with concurrent updates

    Firebase transactions read current value, apply update, and retry if data changed during update.
  2. Step 2: Analyze two concurrent increments

    Both users read current value, increment by 1, but Firebase retries one transaction to avoid overwrite, resulting in counter increasing by 2.
  3. Final Answer:

    The counter increments by 2 safely without overwriting -> Option C
  4. Quick Check:

    Concurrent transactions = safe increments [OK]
Hint: Transactions retry to avoid overwriting, so increments add up [OK]
Common Mistakes:
  • Thinking only one increment happens
  • Assuming counter resets
  • Believing transaction throws error on conflict
4. You wrote this Firebase transaction:
ref.transaction(current => {
  current = current + 1;
  return current;
});

But sometimes it throws an error. What is the likely problem?
medium
A. current might be null, causing addition to fail
B. transaction() cannot update numbers
C. You must use set() inside transaction
D. Firebase transactions do not support arrow functions

Solution

  1. Step 1: Check how current value is used

    If current is null (no data yet), adding 1 to null causes an error.
  2. Step 2: Identify fix for null current

    Use (current || 0) + 1 to handle null safely inside transaction.
  3. Final Answer:

    current might be null, causing addition to fail -> Option A
  4. Quick Check:

    Null current causes error in addition [OK]
Hint: Check for null before arithmetic in transactions [OK]
Common Mistakes:
  • Thinking transaction can't update numbers
  • Trying to use set() inside transaction callback
  • Believing arrow functions are unsupported
5. You want to implement a like counter for a post in Firebase using optimistic concurrency. Which approach ensures the counter updates correctly even if many users like simultaneously?
hard
A. Use ref.transaction(currentLikes => (currentLikes || 0) + 1) to increment safely
B. Use ref.set(currentLikes + 1) without checking current value
C. Read currentLikes once, then call ref.set(currentLikes + 1)
D. Use ref.push() to add a new like entry instead of counting

Solution

  1. Step 1: Understand concurrency risks with simple set()

    Using set() without checking current value risks overwriting likes if multiple users update simultaneously.
  2. Step 2: Use transaction for atomic increments

    transaction() reads current value, increments safely, and retries if data changed, ensuring correct count.
  3. Step 3: Evaluate other options

    Reading once then setting risks race conditions; push() adds entries but does not increment counter directly.
  4. Final Answer:

    Use ref.transaction(currentLikes => (currentLikes || 0) + 1) to increment safely -> Option A
  5. Quick Check:

    Safe counter update = transaction() increment [OK]
Hint: Use transaction() with (current || 0) + 1 for safe counters [OK]
Common Mistakes:
  • Using set() without concurrency control
  • Reading once then setting causing race conditions
  • Confusing push() with incrementing counters
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