Concurrency & Atomicity
If you wanna produce correct working code, you have to understand well that we are living in a world where things are running in parallel. So your server can get more than 1 request at a time
This can lead to major issues on the backend if not well handled
This code will work fine in sequential environment
user = User.first user.money -= 50.dollar user.save!
Here you are reading the amount of money the user has then deducing 50 dollars from his account (maybe because he purchased something) then saving the user again
If this code ran twice at the same time, you can face this race condition
Request 1 loaded user object with remaining money
Request 2 loaded user object with same remaining money
Request 1 deduced money and save user
Request 2 deducted money (old value although it has changed already) and save user
The end result is that the user was able to do two purchases each for 50 dollar but actually just 50 dollar was deduced rather than 100 dollar
The problem is originated because your code is doing two transactions 1 to read the amount and another to deduce but actually both operations should be part of the same transaction. If you made it part of the same transaction, request two will wait for request 1 to deduce money as it will be locked by your DB engine
You must consider this concept of âAtomicityâ in all your work and operations
Note that validations when you run save! are done as part of the transaction which is a good thing













