Home > database >  Firebase prevent multiple users from getting the same item
Firebase prevent multiple users from getting the same item

Time:01-12

I have this items node:

items
|
|----item_id_1
     -name:
     -type:
     -price:

The idea is when one user gets an item, 2 things happen:

  1. The item gets removed from the items node.
  2. The item gets added to his/her my_items node.

These are items that only one user can get, obviously the user that requested them first, and then they get removed.


The problem:

If multiple users requested the item at the same time, how do I handle where this item will go?

Question:

  1. How to make sure that if multiple users requested an item at the same time, only one will get it (No One Else)?

  2. Are Security rules able to solve this?

  3. I am aware of Firebase Transaction operations, but not sure if they help in my case.

Any advice is appreciated.

Thanks.

CodePudding user response:

I am aware of Firebase Transaction operations, but not sure if they help in my case.

When it comes to updating a Realtime Database location (node) in a multi-user environment, then indeed a transaction is required. However, a transaction can only read and update a single location (node). There is no way you can perform multi-location transactions. On the other hand, Firestore does:

Using the Cloud Firestore client libraries, you can group multiple operations into a single transaction.

So when using Firestore, you can update documents no matter if they exist in a collection or a sub-collection. In the Realtime Database, you can only safely update children under the location (node) you are using for the transaction.

Are Security rules able to solve this?

Yes, there will be an alternative to secure your multi-location by writing security rules. Please see below an example:

  • Related