I'm developing an cryptocurrency project. When a customer tries to withdraw his money, I use the code shown here to ensure that this customer has enough balance to make the withdrawal, then I pay the desired amount into customer wallet.
public async Task EnsureCustomerHasEnoughBalance(decimal withdrawAmount, Guid customerId)
{
var currentBalance = await _transactionService.GetCustomerBalance(customerId);
if (currentBalance < withdrawAmount)
throw new Exception("Insufficient balance");
}
The problem is if someone calls my async API many times and quickly, some of the requests will be processed the same time in different threads. So, any customer can hack my code and withdraw more money than his balance allows.
I've tried using lock, semaphore and etc but none of them work in async. Do you have any solution?
Thanks for any help