Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore - How to prevent concurrent writes?

I'm currently working on a question and answer app for which I am using firestore.

Current Scenario - One person will ask a question. That question is matched with multiple people. However, only one of them can claim that question and answer. When a person claims a question, I change the status on the question document from 'pending' to 'claimed'. To avoid two people claiming the same question, I have the logic in a transaction. I update the document only when question status is still 'pending'.

Current Issue - If two people try to claim that question simultaneously, my app crashes saying 'Error · Firestore: The operation was aborted, typically due to a concurrency issue like transaction aborts, etc. (firestore/aborted).'

I don't understand the error enough to solve this. How do I go about solving this?

Generic question - How do I ensure only one person can update the firestore document at a time? And any pending updates don't crash the app?

like image 701
Vishwas Avatar asked Jan 18 '26 07:01

Vishwas


1 Answers

I suspect the following scenario.

Person A: successfully claims the question, their transaction succeeds.

Person B: is unable to claim the question, your code (transaction callback) ends with an error. It's being repeated until 5 times limit, but your code doesn't handle that properly and fails each time. After the limit of 5, the whole Transaction promise is being returned with a failed response.

To fix your code you should end transaction successfully for Person B (without claim), and then check if he/she had successfully claimed the question. It will execute as follows:

Person A: successfully claims the question in 1 round of transaction

Person B: loses the race condition in 1 round of transaction, a transaction is executed for the 2nd time because a write occurred in the meantime. In round 2 you detect that it's already claimed and gracefully finish the transaction without a claim.

I hope this helps.

like image 153
damienix Avatar answered Jan 21 '26 00:01

damienix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!