Home > Software design >  prevent 2 users from reading the same id in Real Time Firebase database
prevent 2 users from reading the same id in Real Time Firebase database

Time:12-17

I have a real time database of firebase with this structure:

enter image description here

In my app the user is given a productId randomly from products and at the same time the productId is deleted from products and inserted in consumedProducts, then he connects to the firestore with this id and makes changes to the object. The problem is that 2 users at the same time can get the same productId while in products if they access the same page at the same time. Instead I would like that if the first one gets an id , the second one will not get the same one but another one. How could I solve this problem? I have seen the use of transaction https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactions but these are used only in case of writing in the same field

CodePudding user response:

There is no way to prevent multiple users from reading the same node in the database. If you need that, you'll need to implement your own custom API either on a server you control, or in something like Cloud Functions or Cloud Run.

But since you say you're moving the key from products to consumedProducts, you may be able to capture that move in a transaction - and prevent multiple users from writing the same key into consumedProducts (which they at the same time then also remove from products).

You'll need to run a transaction on the Firebase-root in your data model in that case, so you may want to consider moving these two nodes under a common ancestor to prevent having contention across your entire database.

  • Related