Bird
Raised Fist0
Firebasecloud~5 mins

Optimistic concurrency in Firebase - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Optimistic concurrency
O(n)
Understanding Time Complexity

When using optimistic concurrency in Firebase, we want to know how the number of operations changes as more users try to update data at the same time.

We ask: How does the system handle conflicts and how many retries might happen?

Scenario Under Consideration

Analyze the time complexity of this optimistic concurrency update:

const docRef = firestore.collection('items').doc('item1');

firestore.runTransaction(async (transaction) => {
  const doc = await transaction.get(docRef);
  const currentCount = doc.data().count || 0;
  transaction.update(docRef, { count: currentCount + 1 });
  return Promise.resolve();
});

This code tries to read a document, increment a count, and write it back safely using a transaction that retries if conflicts happen.

Identify Repeating Operations

Look at what repeats when many users update the same document:

  • Primary operation: Reading and writing the document inside a transaction.
  • How many times: The transaction may retry multiple times if others update the document simultaneously.
How Execution Grows With Input

As more users try to update at once, retries increase because transactions conflict.

Input Size (n)Approx. Api Calls/Operations
10About 10-15 calls (some retries)
100More than 100 calls (many retries)
1000Much more than 1000 calls (high retry rate)

Pattern observation: The number of retries grows as more users try to update simultaneously, increasing total operations.

Final Time Complexity

Time Complexity: O(n)

This means the total operations grow roughly in proportion to the number of concurrent updates trying to happen.

Common Mistake

[X] Wrong: "The transaction will only run once no matter how many users update at the same time."

[OK] Correct: When many users update simultaneously, transactions can conflict and retry multiple times, increasing operations.

Interview Connect

Understanding how optimistic concurrency scales helps you design systems that handle many users safely and efficiently.

Self-Check

What if we changed from optimistic concurrency to a simple write without transactions? How would the time complexity and conflict handling change?

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