Home > front end >  How to handle limit problem if a user execute the function two times together?
How to handle limit problem if a user execute the function two times together?

Time:08-02

In my store (firestore database) I have a fruit.

{
  id: 'apple',
  stock: 1,
};

Now I use google cloud function to handle everything when a user places an order.

The function

  const fruitStock = await getFruitStock("apple");          // =====> STEP 1

  if (fruitStock > 0) await updateFruitStock("apple", -1);  // =====> STEP 2

The problem.

A user makes an order. The function executes. When the function is about to go to step 2, the user makes a 2nd order. Now when the 2nd order function completes its step 1 before the 1st order function completes its step 2. I will have a -1 stock at the end.

This can happen too if user1 makes an order same time as user2.

CodePudding user response:

I believe that you may want to resolve this through using a firestore security rule getAfter(). This security rule will validate the state of the decrement operation after it has completed but before it is committed to the database. If the database operation fails because it has dropped below your threshold of zero, you will then be notified in the function after updating the table. For more information, check out the document called Data Validation for Atomic Operations.

CodePudding user response:

You want to use transactions so that the read and update happen atomically. Any other user/process will wait while you hold a transaction handle (lock).

This document has more details on how to implement this:

Firebase: Transactions and batched writes

  • Related