Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase - Two offline devices modifying same data and order of changes

I have an Android app, that keeps track of some items and their quantities.

What I need is a way for the user to modify data on multiple devices while being offline, with proper synchronization order.

I don't know how to best explain it, so I'll give an example:

  1. Device A changes quantity of item to 5.
  2. Device B changes it to 3.
  3. Device B goes online, changes data on server, like it should, to 3.
  4. Device A goes online and replaces that data with 5 which is an older change and shouldn't be done.

Can this situation be prevented natively in Firebase, or should I, for example, use timestamps on items myself, and replace it only if newer?

Thanks.

like image 900
user3662061 Avatar asked Dec 04 '16 16:12

user3662061


People also ask

Does Firebase Auth work offline?

By enabling persistence, any data that the Firebase Realtime Database client would sync while online persists to disk and is available offline, even when the user or operating system restarts the app. This means your app works as it would online by using the local data stored in the cache.

Does Firebase scale automatically?

Lastly, it'll scale massively and automatically. Firebase Functions will just do it automatically for you based on the traffic you receive and at an incredibly low cost.

When should you not use Firebase?

Firebase is not made for processing complex queries as it relies on a flat data hierarchy. Complicated queries like reversing the order of certain items cannot be executed using Firebase. On top of that, even when you go offline, your app might begin to underperform due to the concurrency.


1 Answers

Adding timestamp field to every item in database and writing security rule in firebase seems to work.
The thing to consider is, when offline, the only timestamp I can get is from the device, not from the server, so it can sometimes lead to overwrite of data that we don't want. Still it works good enough for this project.
Below is the database rule needed to check those timestamps:

"$name" : {
         ".write": "!data.exists() || (newData.child('timestamp').isNumber() && data.child('timestamp').val() <= newData.child('timestamp').val())"
      }

It says: "you can write if there's no data, or stored data has older timestamp that new request"
Important thing to remember while making those is, that parent nodes overwrite rules in children. That means any authentication of write should be done on this level too.

like image 96
user3662061 Avatar answered Oct 20 '22 01:10

user3662061