0
0
Firebasecloud~10 mins

Optimistic concurrency in Firebase - Step-by-Step Execution

Choose your learning style9 modes available
Process Flow - Optimistic concurrency
Read document snapshot
Make local changes
Attempt to write with version check
Version matches?
NoConflict detected
Write succeeds
Read data, change locally, then write back only if data version is unchanged to avoid conflicts.
Execution Sample
Firebase
const docRef = firestore.doc('items/item1');
const snapshot = await docRef.get();
const data = snapshot.data();
const version = data.version;
await firestore.runTransaction(async (transaction) => {
  const freshSnapshot = await transaction.get(docRef);
  if (freshSnapshot.data().version !== version) {
    throw new Error('Conflict detected');
  }
  transaction.update(docRef, { count: data.count + 1, version: version + 1 });
});
Reads a document, increments a count and version, then writes back only if version matches.
Process Table
StepActionData Version ReadLocal ChangeVersion CheckWrite Result
1Read document snapshot3N/AN/AN/A
2Increment count locally3count + 1N/AN/A
3Attempt write with version=33count + 1, version=4Check if current version == 3Success
4Write completes4N/AN/ADocument updated with version=4
5Another client tries write with version=33count + 1, version=4Check if current version == 3Fail - Conflict detected
💡 Write fails if document version changed since read, ensuring no overwrite of concurrent updates.
Status Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
versionN/A33443 (stale)
countN/Acurrentcurrent + 1current + 1updatedcurrent + 1 (stale)
writeResultN/AN/AN/ASuccessCompletedFail
Key Moments - 2 Insights
Why does the write fail at step 5 even though the client read version 3?
Because between reading and writing, another client updated the document to version 4 (see step 4), so the version check at step 5 fails to prevent overwriting newer data.
What happens if we don't check the version before writing?
Without version check, writes could overwrite concurrent changes, causing data loss or inconsistency (not shown in execution_table but implied by failure at step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the document version after step 4?
A4
B3
C5
D2
💡 Hint
Check the 'Data Version Read' and 'Write Result' columns at step 4.
At which step does the write fail due to a version conflict?
AStep 3
BStep 5
CStep 4
DStep 2
💡 Hint
Look for 'Fail - Conflict detected' in the 'Write Result' column.
If the version check was removed, how would the write result at step 5 change?
AIt would still fail
BIt would cause an error before writing
CIt would succeed and overwrite data
DIt would retry automatically
💡 Hint
Refer to the 'key_moments' explanation about version checks preventing overwrites.
Concept Snapshot
Optimistic concurrency means:
- Read data with a version number
- Make local changes
- Write back only if version unchanged
- Prevents overwriting others' updates
- Common in Firebase to avoid conflicts
Full Transcript
Optimistic concurrency in Firebase means you first read a document including its version number. Then you make changes locally. When you write back, you check if the version is still the same. If yes, the write succeeds and increments the version. If no, the write fails because someone else updated the document meanwhile. This prevents data conflicts and lost updates. The execution table shows reading version 3, updating to 4, and a later write failing because the version changed. This method helps keep data consistent when many clients update the same document.