Firebase - multiple users updating the same object at the same time using the old value

I keep track of the account that users update in the Firebase database through an Android app. The way it works right now is that when interacting, the user application looks at the current counter in the database (using the addListenerForSingleValueEvent() and onDataChange() defined in the new ValueEventListener ) and adds it to it and then sets the counter to it to the new value using mRef.setValue() , where mRef is the database reference.

The problem I'm worried about is what happens if a large number of users interact with the database at the same time; Firebase takes care to make sure that the value is read and incremented correctly, or because of this there are many overlaps and possibly data loss.

+7
android firebase firebase-database
source share
2 answers

When dealing with complex data that may be corrupted by simultaneous modifications, such as incremental counters, Firebase provides a transactional operation.

You pass this operation two arguments: an update function and an optional completion completion response. The update function takes the current state of the data as an argument and returns the new desired state that you want to write.

For example, if we wanted to increase the number of upvotes in a certain blog post, we would record the transaction as follows (Legacy code):

  Firebase upvotesRef = new Firebase("https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes"); upvotesRef.runTransaction(new Transaction.Handler() { @Override public Transaction.Result doTransaction(MutableData currentData) { if(currentData.getValue() == null) { currentData.setValue(1); } else { currentData.setValue((Long) currentData.getValue() + 1); } return Transaction.success(currentData); //we can also abort by calling Transaction.abort() } @Override public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) { //This method will be called once with the results of the transaction. } }); 

Source of obsolete

New source of firebase version

+11
source share

The Firebase database processes up to 100 simultaneous real-time connections to your database, if you use their free plan, but as soon as the 101st user connects to your database, the database will stop responding and will display the values ​​that were the last times edited. Firebase is really good at using real-time connections at the same time, so it depends on your pricing plans. If you want to use the database for free, there will be no problem processing 100 connections, but if you want to process more users, use their generous tariff plans.

0
source share

All Articles