Is your database or backend doing strange or unexpected things?
Is your database or backend doing strange or unexpected things?
Welcome to race conditions
Imagine you are about to eat a piece of cake, your fork is going closer and closer to your mouth, when suddenly, you are called and you switch your attention to somewhere else for a few seconds. Then when you are back on track, you realise a kid has eaten your cake. Damn kid.
This happened because the operation you were doing was interruptible and in correct terminology "non-atomic".
Something similar happens in software all the time, with parallel and concurrent programs. Maybe your backend is handling a request and start touching the database, in the meantime something else touches as well the database. If not handled properly, the request can finish with an inconsistent state. For example, think about having $20 in the bank and withdrawing that while receiving a bill of the same amount as well, the final amount could end up being $0 instead of -$20.
This is called a race condition, basically there is a common element or resource that is scarce and more than one entity needs to modify it. In the first example the cake was the common element, and you and the kid were the entities that needed that.
There are a lot of different race conditions that can happen in software, even in React. One of the most common one is the one that occurs with the database, in order to protect these operations we have two options optimistic locking and pessimistic locking.
With optimistic locking you version your data rows and when you modify the data you hope most of the times is gonna be ok and you search data specifying the version of the expected data you want, e.g. 1, then when you update you increase the version number. If someone in the meantime has updated the same data, version will not be 1, it will be 2 so the search will fail, the end user of the backend will have to retry.
With pessimistic locking you have a lock to handle your data because you hope most of the times is not going to be ok. So basically every time you need to touch your data, you lock it for you and only you, and nobody else can access it. When you finish modifying the data, you can free the lock. In this scenario the end user of the backend doesn't need to retry but it might be an scenario where it's waiting for the lock to be freed.
Which one to use depends on your scenario but I'd argued the most common one is the optimistic locking. The pessimistic locking can be tricky if you don't know what you are doing to be honest.
This is of course an overview, but if you want me to go deeper in something in particular please let me know.