Similar to a shopping program, the procedure is as follows: 1. the user initiates a request, order 2. check whether various parameters are complete and valid. 3. check whether the user balance is sufficient. 4. write the order table. 5. write the user table, reduce the user balance. 6. write the user balance to the record table, record what the user ordered to buy, and spent it... the procedure is as follows:
1. the user initiates a request and places an order
2. check whether all parameters are complete and valid.
3. check whether the user balance is sufficient.
4. write the order table
5. write the user table to reduce the user balance
6. write a record table to record what the user ordered to buy and how much it took
Today, I found a magical user who made 20 orders within one second! It cannot be detected in one second, because the database is accurate to only seconds.
What's more strange is:
1. when there is not enough balance, the subsequent steps are continued.
2. the order table is successfully written, the record table is successfully written, but no balance is deducted.
I don't want to figure out how this happened. Have you ever met me? How can this problem be solved?
** Other users are completely normal, but many orders are not normal at this moment.
Public function orderCreate (Request $ request, Response $ response) {if (! $ User = session ('WeChat. oauth_user ') {return response ()-> json (['error' => 'Id verification failed. open the verification area again and then renew']);} if (is_null ($ request-> input ('object', NULL) | is_null ($ request-> input ('stack', NULL )) | is_null ($ request-> input ('time', NULL) | is_null ($ request-> input ('direction', NULL) {return response () -> json (['error' => 'incomplete batch data submission, please open a new batch and then click ']);} if ($ request-> input ('stack ')! = 20 & $ request-> input ('stack ')! = 50 & $ request-> input ('stack ')! = 100 & $ request-> input ('stack ')! = 200 & $ request-> input ('stack ')! = 500 & $ request-> input ('stack ')! = 1000 & $ request-> input ('stack ')! = 2000 & $ request-> input ('stack ')! = 3000) {return response ()-> json (['error' => 'batch number submitted response, please open the response area again and then failed']);} if ($ request-> input ('time ')! = 60 & $ request-> input ('time ')! = 120 & $ request-> input ('time ')! = 180 & $ request-> input ('time ')! = 240 & $ request-> input ('time ')! = 300) {return response ()-> json (['error' => 'batch number submitted response, please open the response area again and then failed']);} if ($ request-> input ('direction ')! = 1 & $ request-> input ('direction ')! = 0) {return response ()-> json (['error' => 'batch number submitted response, please open the response area again and then failed']);} if (! $ Object = Object: find ($ request-> input ('object') {return response () -> json (['error' => 'upload data submit response, open the response area again and then click ']);} $ object_latestPrice = Price :: where ('id _ object', $ object-> id)-> orderBy ('created _ at', 'desc')-> first (); if (strtotime ($ object_latestPrice-> body_price_time) + 300) <time () {return response () -> json (['error' => 'Transactions cannot be made during the closing period ']);} if (! $ User = User: where ('id _ wechat ', $ user-> id)-> first () {return response () -> json (['error' => 'Id verification failed. open the verification area again and then renew ']);} if (floatval ($ user-> body_balance) <$ request-> input ('stack') {return response ()-> json (['error' => 'Invalid response has insufficient quota available, please recharge your account before trading ']);} if ($ user-> is_disabled> 0) {return response () -> json (['error' => 'transaction prohibited, cannot be traded ']);} $ order = new Order; $ order-> id_user = $ user-> id; $ order-> id_object = $ ob Ject-> id; $ order-> body_price_buying = $ object_latestPrice-> body_price; $ order-> body_stake = $ request-> input ('stack '); $ order-> body_bonus = $ object-> body_profit * $ request-> input ('stack'); $ order-> body_direction = $ request-> input ('direction '); $ order-> body_time = $ request-> input ('time'); $ order-> save (); $ user-> body_balance = floatval ($ user-> body_balance) -floatval ($ order-> body_stake); $ user-> body _ Transactions = floatval ($ user-> body_transactions) + floatval ($ order-> body_stake); $ user-> save (); $ record = new Record; $ record-> id_user = $ user-> id; $ record-> id_order = $ order-> id; $ record-> body_name = $ request-> input ('direction ') = 1? 'Allow inbound and outbound view': 'Allow inbound and outbound viewing'; $ record-> body_direction = 0; $ record-> body_stake = $ order-> body_stake; $ record-> save (); return response ()-> json (['result' => $ order-> toArray ()]);}
UPDATE:
Now, after a lot of condition judgments, I want to change to something to handle this matter. but is Laravel's transaction written correctly? Or can I write it like this to what I want? --
DB: beginTransaction (); $ user-> body_balance = floatval ($ user-> body_balance)-$ request-> input ('stack '); $ user-> body_transactions = floatval ($ user-> body_transactions) + $ request-> input ('stack'); $ user-> save (); if ($ user-> body_balance <0) {DB: rollback ();} else {$ order = new Order; $ order-> id_user = $ user-> id; $ order-> id_object = $ object-> id; $ order-> body_price_buying = $ object_latestPrice-> body_p Rice; $ order-> body_stake = $ request-> input ('stack '); $ order-> body_bonus = $ object-> body_profit * $ request-> input ('stack'); $ order-> body_direction = $ request-> input ('direction '); $ order-> body_time = $ request-> input ('time'); $ order-> save (); $ record = new Record; $ record-> id_user = $ user-> id; $ record-> id_order = $ order-> id; $ record-> body_name = $ request-> input ('direction ') = 1? 'Allow inbound and outbound view': 'Allow inbound and outbound viewing'; $ record-> body_direction = 0; $ record-> body_stake = $ order-> body_stake; $ record-> save (); $ this-> computeNetwork ($ user, $ order); if ($ order-> body_time = 60) $ this-> computePrice ($ user, $ order, $ object);} DB: commit ();
Reply content:
The procedure is as follows:
1. the user initiates a request and places an order
2. check whether all parameters are complete and valid.
3. check whether the user balance is sufficient.
4. write the order table
5. write the user table to reduce the user balance
6. write a record table to record what the user ordered to buy and how much it took
Today, I found a magical user who made 20 orders within one second! It cannot be detected in one second, because the database is accurate to only seconds.
What's more strange is:
1. when there is not enough balance, the subsequent steps are continued.
2. the order table is successfully written, the record table is successfully written, but no balance is deducted.
I don't want to figure out how this happened. Have you ever met me? How can this problem be solved?
** Other users are completely normal, but many orders are not normal at this moment.
Public function orderCreate (Request $ request, Response $ response) {if (! $ User = session ('WeChat. oauth_user ') {return response ()-> json (['error' => 'Id verification failed. open the verification area again and then renew']);} if (is_null ($ request-> input ('object', NULL) | is_null ($ request-> input ('stack', NULL )) | is_null ($ request-> input ('time', NULL) | is_null ($ request-> input ('direction', NULL) {return response () -> json (['error' => 'incomplete batch data submission, please open a new batch and then click ']);} if ($ request-> input ('stack ')! = 20 & $ request-> input ('stack ')! = 50 & $ request-> input ('stack ')! = 100 & $ request-> input ('stack ')! = 200 & $ request-> input ('stack ')! = 500 & $ request-> input ('stack ')! = 1000 & $ request-> input ('stack ')! = 2000 & $ request-> input ('stack ')! = 3000) {return response ()-> json (['error' => 'batch number submitted response, please open the response area again and then failed']);} if ($ request-> input ('time ')! = 60 & $ request-> input ('time ')! = 120 & $ request-> input ('time ')! = 180 & $ request-> input ('time ')! = 240 & $ request-> input ('time ')! = 300) {return response ()-> json (['error' => 'batch number submitted response, please open the response area again and then failed']);} if ($ request-> input ('direction ')! = 1 & $ request-> input ('direction ')! = 0) {return response ()-> json (['error' => 'batch number submitted response, please open the response area again and then failed']);} if (! $ Object = Object: find ($ request-> input ('object') {return response () -> json (['error' => 'upload data submit response, open the response area again and then click ']);} $ object_latestPrice = Price :: where ('id _ object', $ object-> id)-> orderBy ('created _ at', 'desc')-> first (); if (strtotime ($ object_latestPrice-> body_price_time) + 300) <time () {return response () -> json (['error' => 'Transactions cannot be made during the closing period ']);} if (! $ User = User: where ('id _ wechat ', $ user-> id)-> first () {return response () -> json (['error' => 'Id verification failed. open the verification area again and then renew ']);} if (floatval ($ user-> body_balance) <$ request-> input ('stack') {return response ()-> json (['error' => 'Invalid response has insufficient quota available, please recharge your account before trading ']);} if ($ user-> is_disabled> 0) {return response () -> json (['error' => 'transaction prohibited, cannot be traded ']);} $ order = new Order; $ order-> id_user = $ user-> id; $ order-> id_object = $ ob Ject-> id; $ order-> body_price_buying = $ object_latestPrice-> body_price; $ order-> body_stake = $ request-> input ('stack '); $ order-> body_bonus = $ object-> body_profit * $ request-> input ('stack'); $ order-> body_direction = $ request-> input ('direction '); $ order-> body_time = $ request-> input ('time'); $ order-> save (); $ user-> body_balance = floatval ($ user-> body_balance) -floatval ($ order-> body_stake); $ user-> body _ Transactions = floatval ($ user-> body_transactions) + floatval ($ order-> body_stake); $ user-> save (); $ record = new Record; $ record-> id_user = $ user-> id; $ record-> id_order = $ order-> id; $ record-> body_name = $ request-> input ('direction ') = 1? 'Allow inbound and outbound view': 'Allow inbound and outbound viewing'; $ record-> body_direction = 0; $ record-> body_stake = $ order-> body_stake; $ record-> save (); return response ()-> json (['result' => $ order-> toArray ()]);}
UPDATE:
Now, after a lot of condition judgments, I want to change to something to handle this matter. but is Laravel's transaction written correctly? Or can I write it like this to what I want? --
DB: beginTransaction (); $ user-> body_balance = floatval ($ user-> body_balance)-$ request-> input ('stack '); $ user-> body_transactions = floatval ($ user-> body_transactions) + $ request-> input ('stack'); $ user-> save (); if ($ user-> body_balance <0) {DB: rollback ();} else {$ order = new Order; $ order-> id_user = $ user-> id; $ order-> id_object = $ object-> id; $ order-> body_price_buying = $ object_latestPrice-> body_p Rice; $ order-> body_stake = $ request-> input ('stack '); $ order-> body_bonus = $ object-> body_profit * $ request-> input ('stack'); $ order-> body_direction = $ request-> input ('direction '); $ order-> body_time = $ request-> input ('time'); $ order-> save (); $ record = new Record; $ record-> id_user = $ user-> id; $ record-> id_order = $ order-> id; $ record-> body_name = $ request-> input ('direction ') = 1? 'Allow inbound and outbound view': 'Allow inbound and outbound viewing'; $ record-> body_direction = 0; $ record-> body_stake = $ order-> body_stake; $ record-> save (); $ this-> computeNetwork ($ user, $ order); if ($ order-> body_time = 60) $ this-> computePrice ($ user, $ order, $ object);} DB: commit ();
I have never seen any transactions involving money that can be executed without opening transactions. please use transactions to solve such problems.
Update:
Some people will just deduct the money first. The answer is No. in MySQL, this operation cannot be completed without transactions.
For example, if you do not need to deduct money first,
-
Receive request A to query the balance. the balance is sufficient,
-
At this time, B was requested to break in, and the balance was also queried. the balance was sufficient,
-
Request A to start updating the balance and perform other operations,
-
Request B to update the balance and perform other operations.
In this way, the concurrency problem cannot be solved.
The transaction is incremented, and important conditions such as the amount are prioritized.
I don't understand the specific implementation of your code, but I guess you may get dirty data.
You can try the following solution:
Trans begin
SQL: update xxx set account balance = account balance-consumption amount (deduction)
SQL: select account balance from xxx (obtain the balance after deduction)
If (account balance <0) rollback
Else commit
20 concurrent orders, each order should be sufficient when determining the balance, then write the table operation, the first deduction of the balance is successful, and the next 19 single deduction failed, however, if your code is not processed, the order is created, but the balance is not deducted.
The solution is described above. use transaction commit to update the balance field first and then perform the remaining operations. This ensures that there is a lock in the balance during concurrency, other requests cannot be executed until the request is committed or rollback.
First, there is still a problem with the code last posted by the landlord.
In general, this requires transactions and locks, while avoiding some pitfalls.
First, check the transaction level of mysql. we need to be at the repeatable read level.
2. confirm the online database structure and ensure that all the read and write operations use a single database connection (especially in the case of read/write splitting ).
Third, start the transaction first.
Fourth, after starting a transaction, the first statement is to use select for update to query the user's Balance (avoid consistent non-locked read ).
Fifth, determine and deduct funds. if you pay attention to php computing, use bcmath for processing.
Sixth, all fund operations should be recorded, and all data exceptions or code errors should be recorded.
7. submit the transaction after the business operation.
The account balance is deducted before the current logic is executed, but an error occurs during the deduction process. for example, the amount field cannot be less than 0. If you deduct the fee before, you can determine whether the execution is successful. Otherwise, an error is prompted!
The problem lies in 3, 4, and 5. this logic may cause problems when similar concurrent centralized requests occur. The correct logic is:
3-update table set balance = balance-amount where user_id =? & Balance> amount, check the number of rows affected by this modification. if it is 0, it indicates that no update is made, that is, the balance is insufficient.
4-write orders
No more than 5
The problem with the original logic is that the balance is sufficient during the 3 query, but it is not necessary to wait until the balance is deducted in step 3.
Well, to add it, it is clear that even if you modify the logic that involves important data, it is best to use transactions.
The same is true for transactions involving money or something similar.