Answer the question
In order to leave comments, you need to log in
How to solve race condition problem in Yii2 API?
Problem: When sending multiple requests simultaneously to the API method - creating an order, incorrect work occurs: orders are created that are larger than the amount on the balance. Actually the problem is related to "Race Condition".
Answer the question
In order to leave comments, you need to log in
Use database transactions. In this case, the next request will not receive the balance until it is updated with the previous transaction.
Use `select for update` for your database.
This way you can SELECT block access to the data and safely perform an UPDATE
$sql = Wallet::find()
->where(['id' => $id])
->createCommand()
->getRawSql();
/** @var Wallet $model */
$model = Wallet::findBySql($sql . ' FOR UPDATE')->one();
$model->amount += $amount;
$model->save(false);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question