D
D
dantolman2018-05-04 10:51:44
PHP
dantolman, 2018-05-04 10:51:44

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

4 answer(s)
Y
Yan-s, 2018-05-04
@Yan-s

SQL transactions

F
frosterdam, 2018-05-04
@frosterdam

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.

A
Adamos, 2018-05-04
@Adamos

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 fact, these actions are optionally performed by a single atomic UPDATE ... JOIN ... WHERE query.
After which you can check how many rows the request has changed - and either save information about a successfully completed transaction (it’s not only the amount on your accounts that changes, right?), Or return a response about the impossibility of transfer.

S
Stas Kuryan, 2018-05-10
@Stafox

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 question

Ask a Question

731 491 924 answers to any question