0
0
Firebasecloud~5 mins

Optimistic concurrency in Firebase - Commands & Configuration

Choose your learning style9 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.