How to avoid race condition when transferring money?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
33 views
For example, you need to make a transfer from one user to another:

1. get the user's balance from the database

2. check whether enough funds for translation according to the obtained balance in paragraph 1

3. updated values of the one user and another database

Here is more properly to be protected from a race condition when transferring money from one user to another?
by | 33 views

5 Answers

0 like 0 dislike
SQL transaction
by
0 like 0 dislike
There is another option, in addition to the previously proposed. A bit exotic. But is the place to be, because he has personally faced with it using vendor SOFTWARE.

This state of the transfer at each moment of time. Roughly speaking, when you create a transfer, it immediately generates a record (in a separate plate, for example) with the status of this transfer, for example, CREATED. When performing any action, the status will be changed (it changes the status field in the record), for example, LOCKED. And if it's LOCKED, then no action with this transfer can be done. If the transfer completed successfully, the status enters, for example, APPROVED or ACCEPTED. And if the transfer was error, it goes to the status, for example, DECLINED.

As shown, it is this decision lacking in 99% of cases.
by
0 like 0 dislike
by
0 like 0 dislike
1. get the user's balance from the database
2. check whether enough funds for translation according to the obtained balance in paragraph 1
3. updated values of the one user and another database

In fact, these actions, if desired, made in one atomic UPDATE request ... JOIN ... WHERE.
After which, you can check how many rows changed the query and either save the information about the successfully performed transaction (you also not only the amount in the accounts is changing, right?) either return a response about the impossibility of translation.
by
0 like 0 dislike
Generally, on good, should not You be no such thing as balance. More precisely, it can be like a cached result (the sum of the `amount` of all transactions). And during the next transaction to recalculate the cache.
by

Related questions

0 like 0 dislike
4 answers
asked May 20, 2019 by Lite_stream
0 like 0 dislike
3 answers
asked Apr 14, 2019 by santavits
110,608 questions
257,187 answers
0 comments
40,796 users