multithreading - Rails balance withdraw action threading issue -
to allow users create balance withdrawal request, have withdrawalscontroller#create
action. code checks if user has sufficient balance before proceeding creating withdrawal.
def create if amount > current_user.available_balance error! :bad_request, :metadata => {code: "002", description: "insufficient balance"} return end withdrawal = current_user.withdrawals.create(amount: amount, billing_info: current_user.billing_info) exposes withdrawal end
this can pose serious issue in multi-threaded server. when 2 create requests arrive simultaneously, , both requests pass the balance check before creating withdrawal, both withdrawal can created if sum of 2 exceeding original balance.
having class variable of mutex
not solution because lock action users, lock on per-user level desired.
what best solution this?
the following diagram illustrates suspected threading issue, occurring in rails?
as far can tell code safe here, mutlithreading not of problem. more app instances generate app server, each instance end testing amount > current_user.available_balance
. if paranoiac it. wrap transacaction
:
activerecord::base.transaction withdrawal = current_user.withdrawals.create!( amount: amount, billing_info: current_user.billing_info ) # if after saving `available_balance` goes under 0 # hole transaction rolled , # change happened database undone. raise activerecord::rollback if current_user.available_balance < 0 end
Comments
Post a Comment