简体   繁体   中英

Firestore Avoid two request for the same document

I am developing a application in react for lotteries. There are about 10k tickets inform of documents. They have the field isAvailabe:true. How it works is, When a user requests for a ticket. I run a query where(isAvailable==true) and set the limit to 1. hence giving the user a ticket and then update isAvailable:false. My problem is what happens when 100's of user request the ticket at the same moment which will result in clashes. I thought of using transactions for this problem but I'm still uncertain. What approach should I take? Is there a better option?

Whenever you need to write something to a document based on its current value, and there is a chance of multiple users performing conflicting updates at the same time, you'll need to use a transaction .

In a transaction you can combine read and write operations, and the server will ensure that the write is only committed if nobody modified the data since you read it. If somebody modified the data while your code was running the transaction, it will automatically be retried.

This is exactly the scenario you have here, so as you already expected, you should use a transaction indeed.

If you have problems while implementing this, I recommend posting a new question with the minimal, complete/standalone code that anyone of us can run to reproduce where you are stuck .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM