I have a plan as to how I would go about doing this and wanted to know if I am headed in the right direction or if there is a better way altogether.
From Firestore Documentation: In the case of a concurrent edit, Cloud Firestore runs the entire transaction again. For example, if a transaction reads documents and another client modifies any of those documents, Cloud Firestore retries the transaction. This feature ensures that the transaction runs on up-to-date and consistent data.
I have a react front end and node express backend.
Front end sends request to create a checkout session.
In the backend I simply parse the request with the required data then send it to Stripe and receive Stripe's response.
Then for each product P in the customers cart:
We create a Firebase transaction in which:
- get (P) from Firestore - if P.stock >= 1 then decrement by one and send the redirect uri from stripe to frontend - else Item is out of stock send custom Failed payment response to front end
Now if two people are trying to purchase the same item and we only have 1 of that item in stock, only one person will be able to complete the payment flow. Is that correct?
I am adding this image to better explain what the flow would look like: Flow Diagram