Linked Questions

Popular Questions

Preventing double execution. PHP financial app

Asked by At

If I have a script that decreases a users balance in a double entry book keeping system, and a malicious user decides to execute this script on his account on two different machines (or the same machine) at EXACTLY the same time, the whole thing would run twice right? SO heres my over simplified hypothetical scenario.

    $balance = $user->ledger->getBalance(); // returns 5000
    $amount = 3000;
    if ($amount <= $balance) {

    echo $user->ledger->getBalance(); // echo's 2000

If the script is run one after the other, the second execution will fail because there is only 2000 left in the account and it tried to decrease by 3000.

If the scripts are run simultaneously at exactly the same time, won't both balances be 5000, and both script executions deduct 3000, leaving a negative value in the ledger?

How would you prevent such a thing happening? It is vitally important to maintain the data integrity in this database table.

Related Questions