How To Avoid Racing Issues Using Cloud Firestore Triggers

I'm using Cloud Firestore onCreate triggers on Firebase, where client is a React Native app.

Users are getting points by writing in a separate collection which has onCreate triggers attached. User can create multiple single-point documents one after the other.

Example: User 1 gets 3x100 points. This creates three documents and trigger is triggered three times.

First executiong finds last user point amount (for example 500) increases it by 100, and saves new state = 600 into user profile. Meanwhile, before this has finished, second trigger is triggered, reads previous state which is still 500 since the previous trigger isn't finished, increases it by 100, and saves 600 also. Third one manages to do the same.

In the end user should have gotten 500 + 100 + 100 + 100 = 800 points, but he has 600 only because last trigger has been triggered before the first one has finished updating user profile and all inbetween changes are overwriten.

How to tackle this?




You need to use a transaction to make sure that all access to a common document is performed atomically. This will ensure that competing writes don't clobber each other's updates. In the event that there is a race to update, the transaction handler will be retried with updated data.