Answer the question
In order to leave comments, you need to log in
How to avoid race condition when transferring money?
For example, you need to make a transfer from one user to another:
1. get the user's balance from the database
2. check if there are enough funds to transfer according to the received balance in paragraph 1
3. update the values of one user and the other in the database
How to protect yourself from race more correctly here condition when transferring money from one user to another?
Answer the question
In order to leave comments, you need to log in
There is another option, in addition to those suggested earlier. A little exotic. But there is a place to be, because. I personally encountered it using vendor software.
This is the state of the transfer at any given time. Roughly speaking, when a transfer is created, a record is immediately generated (in a separate table, for example) with the status of this transfer, for example, CREATED. When an action is performed, the state changes (it is the status field in the record that changes), for example, to LOCKED. And if it is LOCKED, then no action can be taken with this transfer. If the transfer is successful, then the status changes to, for example, APPROVED or ACCEPTED. And if there were errors during the transfer, then it goes into the status, for example, DECLINED.
As practice has shown, such a solution is enough in 99% of cases.
1. get the user's balance from the database
2. check if there are enough funds to transfer according to the received balance in point 1
3. update the values of one user and the other in the database
In general, in a good way, you should not have such a thing as balance. More precisely, it can be like a result cache (sum of `amount` of all transactions). And during the next transaction, recalculate the cache.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question