Question about race conditions
Hello everyone,
As far as I have read from the documentation, Convex is entirely reactive and prevents race conditions. That's great! In this case, can we say for certain that there will be no race condition in the following scenarios?
Let's say a "like" function will be created, which will create a like document when liked and delete this document when unliked. In this case, the first option is to create a single toggleLike function and check if the document exists with each like and unlike operation, and the second option is to create two functions for like and unlike, and learn whether it is already liked or not based on a previously defined useQuery result before performing a useMutation, and then use the appropriate function accordingly.
Which of these two options guarantees that there will be no race condition, meaning that no extra like document will be accidentally created when multiple people like at the same time? (Assuming they all use the same account)
Thank you in advance for your time 🙏
3 Replies
the race-safety has to do with the body of a mutation -- the mutation is an acid transaction
so you should both "check" and "conditionally change" in a single mutation, then you have no race conditions
if you do two different operations from the client (e.g. the browser) to ensure the precondition, you're not inside of a transactional window so the race can still occur
so in your framing, I think you want the first option
Thank you, this is exactly what I needed to know
great! glad it was helpful