Switchyard

Race conditions

Two requests, one gift card

Check-then-act code passes every test and falls over the moment someone sends the same request twice at the same time.

In May 2015, Egor Homakov bought three $5 Starbucks gift cards and moved money between them by sending the same transfer twice at nearly the same moment. Both transfers went through. He ended up with $20 on cards that had held $15, spent some of it on an actual purchase (then put the money back), and reported it. By his account, Starbucks responded with a phone call that used the word "fraud."

Most Rails code reads like a script: look something up, check it, change it. That’s fine until two requests run the same script at the same moment. Both look it up, both pass the check, and both make the change. Puma runs requests in parallel across threads and processes, so this is a when, not an if.

The basic bug

class GiftCard < ApplicationRecord
  def redeem_for!(user)
    raise AlreadyRedeemed if redeemed_at?

    user.increment!(:credit_cents, amount_cents)
    update!(redeemed_at: Time.current)
  end
end

Fire this endpoint ten times in parallel (Turbo Intruder, or curl in a loop with &) and a $50 card pays out several times. The gap between the check and the update is a few milliseconds. That’s plenty.

The basic fix

class GiftCard < ApplicationRecord
  def redeem_for!(user)
    with_lock do
      raise AlreadyRedeemed if redeemed_at?

      user.increment!(:credit_cents, amount_cents)
      update!(redeemed_at: Time.current)
    end
  end
end

with_lock opens a transaction, takes a SELECT FOR UPDATE lock on the row, and reloads it. The second request waits at the lock, then sees redeemed_at set and raises. The check has to happen inside the lock; checking first and locking after is the same bug with extra steps.

The hardcore version

class Promotion < ApplicationRecord
  has_many :redemptions

  def redeem_for!(user)
    raise SoldOut if redemptions.count >= max_redemptions
    raise AlreadyRedeemed if redemptions.exists?(user: user)

    redemptions.create!(user: user)
  end
end

"First 100 customers, once each." There’s no existing row to lock here, because the thing you’re racing over is a row that doesn’t exist yet. Two requests both count 99, both see no redemption for this user, and both insert. validates :user_id, uniqueness: true has the exact same race, because it’s also just a SELECT before an INSERT.

The webhook version

def create
  event = Stripe::Webhook.construct_event(request.body.read, request.headers["Stripe-Signature"], ENV.fetch("STRIPE_WEBHOOK_SECRET"))
  return head :ok if ProcessedEvent.exists?(stripe_id: event.id)

  if event.type == "checkout.session.completed"
    account = Account.find_by!(stripe_customer_id: event.data.object.customer)
    account.increment!(:credits, 100)
  end
  ProcessedEvent.create!(stripe_id: event.id)
  head :ok
end

Stripe says outright that it may deliver the same event more than once, and a retry can land while the first attempt is still running (your endpoint was slow, Stripe timed out and tried again). Both copies check exists?, both find nothing, both add credits. Nobody malicious required. It shows up as a support ticket from a customer with 200 credits instead of 100, and nobody can reproduce it.

class AddUniqueIndexToProcessedEvents < ActiveRecord::Migration[8.0]
  def change
    add_index :processed_events, :stripe_id, unique: true
  end
end
def create
  event = Stripe::Webhook.construct_event(request.body.read, request.headers["Stripe-Signature"], ENV.fetch("STRIPE_WEBHOOK_SECRET"))

  ApplicationRecord.transaction do
    ProcessedEvent.create!(stripe_id: event.id)
    fulfill(event) if event.type == "checkout.session.completed"
  end
  head :ok
rescue ActiveRecord::RecordNotUnique
  head :ok
end

Claim the event first, then do the work, inside one transaction. The second insert waits for the first transaction to commit and then fails on the unique index, so exactly one copy does the work. If the work blows up, the claim rolls back with it and Stripe’s next retry gets a clean shot. Same move for your own job retries and for double-clicked Pay buttons: give the operation an idempotency key and let a unique index decide.

The transfer version

class GiftCard < ApplicationRecord
  def transfer_to!(other, amount_cents)
    transaction do
      lock!
      other.lock!
      raise InsufficientFunds if balance_cents < amount_cents
      update!(balance_cents: balance_cents - amount_cents)
      other.update!(balance_cents: other.balance_cents + amount_cents)
    end
  end
end

This one locks, checks inside the lock, and is correct. It also deadlocks. Card A sends to card B while card B sends to card A, each request holds one lock and waits on the other, and Postgres kills one of them with ActiveRecord::Deadlocked. The errors pile up in your tracker, someone decides the locks are the problem, and the fix that ships is deleting the two lock! lines. Now it’s the basic bug again, in the code that moves money.

def transfer_to!(other, amount_cents)
  raise ArgumentError, "amount must be positive" unless amount_cents.positive?

  transaction do
    cards = GiftCard.where(id: [id, other.id]).order(:id).lock.index_by(&:id)
    from = cards.fetch(id)
    to = cards.fetch(other.id)
    raise InsufficientFunds if from.balance_cents < amount_cents
    from.update!(balance_cents: from.balance_cents - amount_cents)
    to.update!(balance_cents: to.balance_cents + amount_cents)
  end
end

Take both locks in one query, in the same order every time (lowest ID first), and two transfers can never each be holding the lock the other one wants. Postgres locks the rows in the order the query returns them, so the order(:id) is doing the actual work. When you see a deadlock, fix the lock order. Deleting the lock trades an error you can see for a bug you can’t. (The positive-amount check is unrelated to the race. A transfer of negative five dollars is just a theft with extra steps.)

That’s the Starbucks fix, too. With both cards locked before the balance check, Homakov’s second transfer would have waited for the first one to commit, read a balance of zero, and raised InsufficientFunds.

Fix #1: Lock the parent

def redeem_for!(user)
  with_lock do
    raise SoldOut if redemptions.count >= max_redemptions
    raise AlreadyRedeemed if redemptions.exists?(user: user)

    redemptions.create!(user: user)
  end
end

Lock the promotion and every redemption for it runs one at a time. It works, and it’s often good enough. The cost is that all redemptions for that promotion now queue behind a single row, which is fine for a coupon and less fine for a ticket drop with 50,000 people hitting it at noon.

Fix #2: Let one UPDATE decide

def redeem_for!(user)
  transaction do
    claimed = Promotion.where(id: id)
                       .where("redemptions_count < max_redemptions")
                       .update_all("redemptions_count = redemptions_count + 1")
    raise SoldOut if claimed.zero?

    redemptions.create!(user: user)
  end
end

A single UPDATE with the condition in the WHERE clause is atomic. Exactly 100 requests get 1 back and everyone after gets 0, without holding a lock for the length of your Ruby code. If the insert fails, the transaction rolls the counter back.

Fix #3: Put the rules in the schema

class AddPromotionConstraints < ActiveRecord::Migration[8.0]
  def change
    add_index :redemptions, [:promotion_id, :user_id], unique: true
    add_check_constraint :promotions, "redemptions_count <= max_redemptions",
      name: "promotions_redemptions_within_limit"
  end
end

Now the database refuses a second redemption per user and refuses to go over the limit, no matter which code path tries. Rescue ActiveRecord::RecordNotUnique and ActiveRecord::StatementInvalid where you want a friendly error. The Ruby checks stay for nice messages; the constraints are what’s actually true.

Your test suite runs one request at a time, so it’ll never find these. Something has to send them in parallel.

Secure your Rails app today.

Find and fix critical vulnerabilities in minutes.

Inquire