skip to content

In a Rails arcade app, two concurrent credit transfers read the same Wallet balance and one debit is lost; how do lock!, with_lock and Wallet.lock fix it?

level: seniorimportance: must knowfreq 48%

answer

  1. lost update between read and write
  2. SELECT ... FOR UPDATE
  3. lock! reloads, only inside a transaction
  4. with_lock = transaction + lock!
  5. lock rows in a consistent order

basics

~20 s

Lock the row before reading the balance. Inside a transaction, wallet.lock! reloads it with SELECT ... FOR UPDATE, wallet.with_lock opens the transaction and locks in one call, and Wallet.lock.find(id) locks while loading, so the second transfer waits and reads the new balance.

solid answer

~40 s

The bug is a lost update: both requests load `credits: 100`, both write `50`, and 50 credits vanish from the books. A **pessimistic lock** fixes it. `wallet.lock!` reloads the row with `SELECT ... FOR UPDATE` and returns the record; `wallet.with_lock { ... }` wraps a transaction around `lock!` and your block; `Wallet.lock.find(id)` adds the lock to the loading query. The second transfer blocks on its `FOR UPDATE` until the first commits, then reads 50 and fails the balance check. The lock lasts until the transaction ends, so `lock!` outside a transaction protects nothing. `lock!` raises if the record has unsaved changes, accepts a clause such as `"FOR UPDATE NOWAIT"`, and raises `ActiveRecord::ReadOnlyError` on the reading role. Lock both wallets in id order to avoid deadlocks, and keep slow work out of the locked section.

code

ruby · 5 lines
ruby
wallet = Wallet.find(params.expect(:id))
wallet.with_lock do          # BEGIN; SELECT ... FOR UPDATE
  raise InsufficientCredits if wallet.credits < 50
  wallet.update!(credits: wallet.credits - 50)
end                           # COMMIT releases the row lock

go deeper

for a junior

Know that two requests can read the same balance and overwrite each other, and that with_lock makes the second one wait.

for a middle

Explain FOR UPDATE, why the lock only lasts until the transaction ends, and the difference between lock!, with_lock and Model.lock.

for a senior

Lock rows in a fixed order, keep locked sections short, use NOWAIT where waiting hurts, and prefer an atomic UPDATE for plain counters.

for a principal

Choose between row locks, version checks and single-statement updates per write path, based on contention and how much logic needs the read.

## The race A transfer that reads, computes and writes is not safe under concurrency, even inside a transaction: ```ruby Wallet.transaction do from = Wallet.find(from_id) # request A and B both read credits: 100 raise InsufficientCredits if from.credits < 50 from.update!(credits: from.credits - 50) # both write 50 Wallet.find(to_id).increment!(:credits, 50) end ``` Two requests running this at the same time both load `credits: 100`, both pass the check, and both write `50`. One debit is **lost**, yet both recipients were credited. Under the default isolation of PostgreSQL and MySQL, the transaction alone does not stop this. ## Pessimistic locking in Active Record A **row lock** makes the second reader wait until the first transaction finishes. Active Record offers three ways to take one: | API | What it does | |---|---| | `Wallet.lock.find(id)` | adds `FOR UPDATE` to the loading query | | `wallet.lock!` | reloads this record with `FOR UPDATE` and returns it | | `wallet.with_lock { ... }` | opens a transaction, calls `lock!`, then runs the block | All three accept a custom clause instead of the default `FOR UPDATE`, for example `Wallet.lock("FOR UPDATE NOWAIT")` or `wallet.with_lock("FOR UPDATE NOWAIT") { ... }`. With `NOWAIT` the database raises instead of waiting; on PostgreSQL Active Record maps that error to `ActiveRecord::LockWaitTimeout`, while other adapters may raise a plain `ActiveRecord::StatementInvalid`. `with_lock` also passes `requires_new:`, `isolation:` and `joinable:` on to its transaction. ## The fixed transfer ```ruby def transfer!(from_id:, to_id:, amount:) Wallet.transaction do first, second = Wallet.lock.where(id: [from_id, to_id]).order(:id).to_a from = [first, second].find { |w| w.id == from_id } to = [first, second].find { |w| w.id == to_id } raise InsufficientCredits if from.credits < amount from.update!(credits: from.credits - amount) to.update!(credits: to.credits + amount) end end ``` Now request B's `SELECT ... FOR UPDATE` waits until A commits, then reads 50, and B fails the balance check instead of overdrawing. ## Rules that keep locks correct 1. **Lock inside a transaction.** The lock lasts until the transaction ends. Called outside one, `lock!` runs in autocommit mode and the lock is released as soon as the SELECT finishes. 2. **Lock before you read the value you decide on.** `lock!` reloads the row, so it discards a stale in-memory balance. It raises an error if the record has **unsaved changes**, telling you to `save` or `reload` first, so you cannot silently lose edits. 3. **Lock in a consistent order.** A transfer from wallet 7 to 9 and one from 9 to 7, each locking "from" first, can wait on each other forever; the database then aborts one, which Rails raises as `ActiveRecord::Deadlocked`. Locking both rows in id order, as above, avoids that cycle. 4. **Keep the locked section short.** No HTTP calls, emails or file uploads while holding the lock; other transfers touching those wallets queue behind you. 5. **Locks need the writing role.** Inside `connected_to(role: :reading)`, `lock!` and `Model.lock` raise `ActiveRecord::ReadOnlyError`. ## Choosing among the three APIs - **`Wallet.lock.find(id)`** when you are loading the row anyway: one query, locked from the start. - **`wallet.lock!`** when the record is already loaded (say, by a `before_action`) and you only need the lock now; it costs a second SELECT. - **`wallet.with_lock { ... }`** when one record is the whole story: the transaction, the lock and the block in a single call, which is also the hardest to get wrong. - For **several rows**, lock them in one query with a stable `order(:id)`, as in the transfer above, rather than one `lock!` at a time in whatever order the code happens to visit them. ## Adapter notes - **PostgreSQL and MySQL** take real row locks for `FOR UPDATE`. - **SQLite** has no row locks. Its Arel visitor drops the lock clause entirely, and writers are serialized by the database lock instead, which the SQLite adapter's transaction mode deals with. ## A lighter alternative When the whole operation is "subtract if enough", a single conditional UPDATE needs no read at all: ```ruby rows = Wallet.where(id: from_id).where("credits >= ?", amount) .update_all(["credits = credits - ?", amount]) raise InsufficientCredits if rows.zero? ``` `update_all` returns the number of affected rows, skips validations, callbacks and `lock_version`, and is atomic in the database. It suits simple counters; the locked version suits logic that must look at several columns or records before writing.

  • What does wallet.lock! do if called outside any transaction?
    It still reloads the record with `SELECT ... FOR UPDATE`, but in autocommit mode the statement is its own transaction, so the lock is released the moment the SELECT finishes. Nothing is protected. Call it inside `Wallet.transaction`, or use `with_lock`, which opens the transaction for you.
  • Why does wallet.lock! raise when the wallet has unsaved attribute changes?
    `lock!` works by reloading the row under the lock, which would throw away the in-memory edits. Rather than lose them silently, Active Record raises and tells you to `save` the changes or `reload` to discard them first. Take the lock before you modify the record.

A row lock is the single key to an arcade prize locker: whoever holds it may count and change what is inside, everyone else queues at the door, and the key goes back only when the transaction ends. Calling lock! outside a transaction is taking the key and handing it straight back.

  • Wrapping the transfer in Wallet.transaction alone prevents the lost update.
  • wallet.lock! outside a transaction keeps the row locked until the request ends.
  • lock! keeps the in-memory balance and only adds a lock on top.
  • Locking the from wallet first in every transfer can never deadlock.
  • Rails retries a transaction automatically after ActiveRecord::Deadlocked.