Home » Php » php – prevent concurrent request from a user

php – prevent concurrent request from a user

Posted by: admin February 25, 2020 Leave a comment


I have a question about concurrent request a user from different browser

Imagine we have balance in wallet for just buy one product, if a user request a product at the same time with two different browser, can user buy a product two times? if it is possible, how can I prevent the second action?


user A balance : 100$

user A ---->  mozila ----> request ----> product A50(price 100$)
user A ---->  chrome ----> request ----> product A50(price 100$)

above request happen at the same time after that some process the amount of wallet decrease

How to&Answers:

You should perform these operations in SQL TRANSACTIONs having an appropriate isolation level. All of the operations performed within the transaction will be “all or nothing,” which means that all of the changes take effect if you COMMIT and none of them do if you instead ROLLBACK. Furthermore, if two transactions attempt to touch the same row, one of them will either be forced to wait or will be turned away. Also, the other transaction will not see anything that hasn’t yet been committed.

For instance, if you want to “deduct money from the user’s account and apply it to an order,” you would perform both updates in one transaction. So, “if everything worked, both updates happened instantaneously.” And, “if it didn’t work and the transaction was rolled back, nothing changed anywhere.”

But it’s important that you also test the user’s balance within the same transaction! (Otherwise, there would be a “race” between testing the balance and proceeding with the sale.) Your logic might be something like this pseudocode:

 BEGIN TRANSACTION with proper isolation level
 Retrieve user's account.
 If there isn't enough money:
     UPDATE user account to withdraw money.
     UPDATE the invoice to show payment.
     INSERT a new entry into the (financial ...) transaction log table.

This works as intended because the entire set of operations that occurs within the transaction is “atomic.”

SQL servers vary slightly in their implementation of transactions but here is a web-page on the topic (covering MS SQL Server):