Your question is Refactor to Avoid Race Conditions. Take a moment with it on the right.
Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).
Stripe's ledger service exposes an internal transfer_funds helper that account-services call whenever money moves between two internal balances — refunds, payouts, and manual adjustments all go through it. A security review flagged it after two customers reported balances that briefly went negative under load.
def transfer_funds(account_id, amount, db):
account = db.execute(
"SELECT balance FROM accounts WHERE id = %s", (account_id,)
).fetchone()
current_balance = account["balance"]
if current_balance < amount:
raise InsufficientFundsError("Not enough funds")
new_balance = current_balance - amount
db.execute(
"UPDATE accounts SET balance = %s WHERE id = %s",
(new_balance, account_id)
)
db.execute(
"INSERT INTO transactions (account_id, amount, type) VALUES (%s, %s, 'debit')",
(account_id, amount)
)
db.commit()
return new_balance
How would you refactor this code to prevent a race condition during this sensitive financial operation? Explain what you would change and why, and call out every place this function could leave the ledger in an inconsistent state under concurrent requests, not just the most obvious one.