Alexsandr Krivobokov
Alexsandr Krivobokov

Reputation: 105

Firebase database several updates of the same value at the same time

There is a certain int value in the realtime database. I modify it using two different Firebase functions. Suppose now it is 500 and both of these functions have been called. One should add 100 to the value, the other - 20. I get the current value from the database (500) in each function and add the corresponding value to it, then write the new value to the database. If I understand correctly, then I will lose one of the values ​​and in the database I will have the value that was last recorded (600 or 520). How can this be avoided?

Upvotes: 0

Views: 160

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

What you're describing requires that you use a transaction, or the recently added increment() operation.

From Cloud Functions you'll be using the Firebase Admin SDK for Node, where this can be as simple as:

ref.set(firebase.database.ServerValue.increment(100));

And

ref.set(firebase.database.ServerValue.increment(-20));

Also see my answer comparing the performance of both operations: How quickly can you atomically increment a value on the Firebase Realtime Database?

Upvotes: 1

Related Questions