skip to content

In Active Record, how does adding a lock_version column give a Wallet optimistic locking, and what should code do when ActiveRecord::StaleObjectError is raised?

level: middleimportance: should knowfreq 52%

answer

  1. integer lock_version, default 0
  2. WHERE lock_version = n
  3. zero rows means StaleObjectError
  4. save raises, it does not return false
  5. hidden field round-trips the version

basics

~20 s

With an integer lock_version column, every update and destroy adds WHERE lock_version = n and bumps it to n + 1. If another write changed the row first, zero rows match and Rails raises ActiveRecord::StaleObjectError; reload, then retry or show the conflict.

solid answer

~40 s

Optimistic locking switches on by itself when the table has a `lock_version` column (rename with `self.locking_column`, disable with `lock_optimistically = false`). Each `save` sends `UPDATE wallets SET credits = 30, lock_version = 4 WHERE id = 7 AND lock_version = 3`; `destroy` adds the same check. When the row was changed in between, zero rows are affected and Rails raises `ActiveRecord::StaleObjectError`, from `save` as well as `save!`, and restores the in-memory `lock_version`. Handle it by `reload`ing and re-applying the change, retrying a bounded number of times, or by showing the player that someone else edited the record. For a form, `lock_version` must travel with the page as a hidden field and be permitted, or the second request checks the current version and the guard does nothing. `update_all` skips the check entirely.

code

ruby · 6 lines
ruby
a = Wallet.find(7)
b = Wallet.find(7)

a.update!(nickname: "PixelQueen")   # lock_version 3 -> 4
b.update!(nickname: "Arcadia")      # WHERE lock_version = 3 matches nothing
# => raises ActiveRecord::StaleObjectError

go deeper

for a junior

Know that adding a lock_version integer column makes Rails reject a save based on an outdated copy with ActiveRecord::StaleObjectError.

for a middle

Explain the UPDATE with WHERE lock_version = n, the zero-rows check, the hidden form field, and which writes skip the check.

for a senior

Pick per use case between showing the conflict, a bounded reload-and-retry, and switching to row locks for hot records.

for a principal

Decide which models carry a version at all, weighing silent lost edits against conflict handling cost in every client.

## Turning it on **Optimistic locking** in Active Record needs one thing: an integer column named `lock_version` on the table. ```ruby class AddLockVersionToWallets < ActiveRecord::Migration[8.1] def change add_column :wallets, :lock_version, :integer, default: 0, null: false end end ``` There is no macro to call. `ActiveRecord::Locking::Optimistic` checks for the column (`locking_enabled?` is true when `lock_optimistically` is true and the column exists). Two class-level knobs exist: - `self.locking_column = :wallet_version` to use another column name; - `self.lock_optimistically = false` to switch the behaviour off for a model. Give the column a default and `null: false`. A `nil` version makes the next update raise an error saying the locking column "can't be nil". ## What Rails sends Loading a wallet reads `lock_version` like any attribute. Saving it adds the version to both sides of the UPDATE: ```sql UPDATE "wallets" SET "credits" = 30, "lock_version" = 4 WHERE "wallets"."id" = 7 AND "wallets"."lock_version" = 3 ``` - **One row affected**: the write won, and the in-memory `lock_version` is now 4. - **Zero rows affected**: someone else saved first and the version moved. Rails raises **`ActiveRecord::StaleObjectError`** and puts `lock_version` back to 3. `destroy` adds the same `WHERE lock_version = n` and raises `StaleObjectError` when nothing was deleted. `touch` bumps the version as well. ## What does and does not go through the check | Call | Checks lock_version? | Bumps it? | On conflict | |---|---|---|---| | `save`, `save!`, `update`, `update!` | yes | yes | raises `StaleObjectError` (also from `save`) | | `destroy`, `destroy!` | yes | n/a | raises `StaleObjectError` | | `touch` | yes | yes | raises `StaleObjectError` | | `update_columns` | yes (in the WHERE) | no | returns `false`, no exception | | `Wallet.where(...).update_all(...)` | no | no | writes regardless | The `save` row surprises people: `save` normally returns `false` on failure, but a stale version is an exception, not a validation error. ## Making it work across requests Within one process the version is carried in the loaded object. Across web requests, the player loads the edit page now and submits later, so the version must travel with the form: ```erb <%= form_with model: @wallet do |form| %> <%= form.hidden_field :lock_version %> <%= form.text_field :nickname %> <% end %> ``` The controller must also permit it, for example `params.expect(wallet: [:nickname, :lock_version])`. If the hidden field is missing or filtered out, the update loads the current row, checks the current version and always succeeds, which silently removes the protection. ## Handling StaleObjectError There are three sensible reactions, chosen per use case: 1. **Show the conflict** in an edit form: rescue it, `reload`, re-render with a message that the wallet changed, and let the player re-apply their edit. 2. **Retry automatically** for small, recomputable changes: `reload`, re-apply the change, save again, with a small attempt limit. 3. **Give up** and report the error for background work where a conflict means a bug. ```ruby attempts = 0 begin wallet.reload wallet.update!(nickname: new_name) rescue ActiveRecord::StaleObjectError retry if (attempts += 1) < 3 raise end ``` ## Testing the guard A model test can reproduce a conflict without threads, because two loaded copies of the same row behave like two requests: ```ruby test "a stale wallet copy cannot overwrite a newer edit" do first = Wallet.find(wallets(:pixel).id) second = Wallet.find(first.id) first.update!(nickname: "PixelQueen") assert_raises(ActiveRecord::StaleObjectError) { second.update!(nickname: "Arcadia") } end ``` A controller or system test should also submit a form whose hidden `lock_version` is out of date, which is the only way to prove the field is rendered and permitted. ## When optimistic locking is the wrong tool For a hot counter such as a wallet balance hit by many concurrent transfers, conflicts are the normal case, and retries pile up. A row lock (`with_lock`) or a single atomic `UPDATE ... SET credits = credits - 50` serves that better. Optimistic locking shines on records people edit by hand, where conflicts are rare and losing an edit silently is the real risk.

  • Which Active Record writes bypass the lock_version check, and why does that matter?
    `update_all` (and other relation-level SQL) never looks at `lock_version`, so it overwrites rows and leaves the version unchanged; other copies will not notice. `update_columns` does include the version in its WHERE but does not bump it, and returns `false` instead of raising when it is stale. Use them knowingly, and bump the version yourself if other code relies on it.
  • Why does optimistic locking on a Rails edit form need lock_version in the form?
    The second request loads a fresh copy of the row, whose `lock_version` is current. Without the value from the time the page was rendered, the UPDATE checks the current version and always succeeds. A hidden `lock_version` field, permitted in the controller, makes the save compare against the version the player actually saw.

  • Optimistic locking needs a lock_optimistically macro call in each model.
  • With lock_version, a stale save returns false and adds an error to wallet.errors.
  • update_all also raises StaleObjectError when another process changed the rows.
  • Rails stores the version in the session, so forms need no hidden field.
  • lock_version holds a database row lock until the record is saved.