Sobes.tech
Junior — Senior

Correct deduction of funds from the user balance

livecode

Task condition

The system has a table user, where the current balance of each user is stored. A pseudocode function is provided that implements the process of withdrawing an amount from the balance. It is necessary to analyze it, identify problematic areas, and suggest improvements, considering that the code operates in production. Special attention should be paid to issues of concurrent access, atomicity of operations, use of transactions, and potential race conditions.

func withdrawBalance(userID int32, amount float32) {
    balance = exec('select balance from user u where u.id=$1', userID)
    if balance - amount >= 0.0 {
        exec('update user u set balance=balance-$1', amount)
        return exec('select balance from user u where u.id=$1', userID)
    }
}