Bird
Raised Fist0
Firebasecloud~5 mins

Optimistic concurrency in Firebase - Commands & Configuration

Choose your learning style10 modes available
Introduction
When multiple users or processes try to change the same data at the same time, conflicts can happen. Optimistic concurrency helps prevent overwriting changes by checking if the data was changed before saving new updates.
When multiple users edit the same document in a Firebase Firestore database at the same time.
When you want to avoid losing updates by checking if data changed before saving.
When you want to keep your app responsive without locking data for long periods.
When you want to handle conflicts by retrying or notifying users about changes.
When you want to ensure data consistency in collaborative apps like chat or notes.
Commands
This command updates the 'counter' field of the document 'my-doc' in 'my-collection' only if the document was last updated exactly at the given time. This prevents overwriting if the document changed since then.
Terminal
firebase firestore:documents:update my-collection/my-doc --updateField=counter --updateValue=5 --precondition='lastUpdateTime=2023-06-01T12:00:00Z'
Expected OutputExpected
Updated document my-collection/my-doc successfully.
→
--updateField - Specifies which field to update.
→
--updateValue - Specifies the new value for the field.
→
--precondition - Ensures the update only happens if the document matches the condition.
This command fetches the current state of the document to check its fields and last update time before trying to update it.
Terminal
firebase firestore:documents:get my-collection/my-doc
Expected OutputExpected
{ "name": "projects/my-project/databases/(default)/documents/my-collection/my-doc", "fields": { "counter": {"integerValue": "4"} }, "updateTime": "2023-06-01T12:00:00Z" }
Key Concept

If you remember nothing else from this pattern, remember: always check the data's last update time before saving changes to avoid overwriting others' updates.

Common Mistakes
Updating a document without checking its last update time.
This can overwrite changes made by others, causing data loss.
Use a precondition with the last update time to ensure the document has not changed before updating.
Using outdated last update time in the precondition.
The update will fail because the document has changed since that time.
Always fetch the latest document state before updating to get the current last update time.
Summary
Fetch the current document to get its last update time.
Update the document using a precondition that checks the last update time.
This prevents overwriting changes made by others between fetch and update.

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