skip to content

Rollbacks, Savepoints & Locks

Model.transaction wraps writes in one commit, requires_new: adds savepoints, and lock_version or with_lock guard rows against races. Interviewers ask what actually rolls back, and why.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In Active Record, what does wrapping two wallet updates in a transaction block guarantee, and which failures inside the block actually roll it back?

level: juniorimportance: must knowfreq 70%

answer

  1. one connection, all or nothing
  2. an exception escaping the block
  3. save returns false, save! raises
  4. ActiveRecord::Rollback is swallowed
  5. return or break commits since 7.2

basics

~20 s

A transaction block makes the writes inside it commit together or not at all on one connection. It rolls back when an exception leaves the block; update returning false is not an exception, so use update! or raise yourself.

solid answer

~40 s

`Wallet.transaction do ... end` opens one database transaction on the model's connection; when the block finishes normally Rails sends COMMIT. If any exception propagates out of the block, Rails sends ROLLBACK and re-raises it, so `update!` failing validation (`ActiveRecord::RecordInvalid`) undoes the earlier debit. Plain `update` or `save` returns `false` on a validation failure and raises nothing, so the block keeps going and commits whatever did succeed. `ActiveRecord::Rollback` is the one exception that rolls back and is then swallowed; the call returns `nil`. Since Rails 7.2, leaving the block early with `return`, `break` or `throw` commits rather than rolls back. A transaction covers one connection only, so writes through another database's models are not part of it, and atomicity does not stop two concurrent transfers from reading the same balance; that needs a lock.

code

ruby · 12 lines
ruby
class CreditTransfer < ApplicationRecord
  belongs_to :from_wallet, class_name: "Wallet"
  belongs_to :to_wallet, class_name: "Wallet"

  def self.move!(from:, to:, amount:)
    transaction do
      from.update!(credits: from.credits - amount)
      to.update!(credits: to.credits + amount)
      create!(from_wallet: from, to_wallet: to, amount: amount)
    end
  end
end

go deeper

for a junior

Know that a transaction commits everything or nothing, and that an exception leaving the block is what rolls it back; prefer update! inside one.

for a middle

Explain the full table: re-raised exceptions, the swallowed ActiveRecord::Rollback returning nil, false returns, and commit on return since 7.2.

for a senior

Point out what atomicity does not cover: other connections, concurrent readers, and side effects that a rollback cannot undo.

for a principal

Set team conventions for transaction boundaries, such as bang methods only and no external calls inside, so these traps are caught in review.

## What a transaction block is `ActiveRecord::Base.transaction` (callable on any model, such as `Wallet.transaction`, or on a record) wraps a block in a database **transaction**: a unit of work the database applies completely or not at all. In an arcade-games app, moving 50 credits from one player's wallet to another's is the textbook case: ```ruby Wallet.transaction do from.update!(credits: from.credits - 50) to.update!(credits: to.credits + 50) CreditTransfer.create!(from_wallet: from, to_wallet: to, amount: 50) end ``` Rails opens the transaction lazily (the `BEGIN` is sent with the first query), runs the block, and sends `COMMIT` when the block ends normally. Each `save` and `destroy` inside it is already wrapped in a transaction of its own; inside your block those join the outer one. ## What rolls it back | What happens inside the block | Result | |---|---| | An exception propagates out of the block (`RecordInvalid`, `RecordNotUnique`, your own error) | `ROLLBACK`, then the exception is re-raised to the caller | | `raise ActiveRecord::Rollback` | `ROLLBACK`, the exception is swallowed, `transaction` returns `nil` | | `update` / `save` returns `false` | nothing special; the block continues and later commits | | An exception raised and **rescued inside** the block | nothing special; Rails never sees it | | `return`, `break` or `throw` out of the block (Rails 7.2+) | `COMMIT` | | The block finishes normally | `COMMIT`, and `transaction` returns the block's value | The rule behind the table is simple: **apart from a thread being killed mid-block, Rails only rolls back for failures that leave the block as exceptions.** ## The false-return trap Suppose `Wallet` has `validates :credits, numericality: { greater_than_or_equal_to: 0 }` and the sender has only 30 credits: ```ruby Wallet.transaction do from.update(credits: from.credits - 50) # invalid: returns false to.update(credits: to.credits + 50) # valid: written end ``` The debit fails validation and returns `false`; nothing is raised, so the credit is written and committed. Credits appear from nowhere. The fixes: - use the bang methods (`update!`, `save!`, `create!`, `destroy!`) inside transactions, so failures raise; - or check the return value and `raise` a domain error; - or `raise ActiveRecord::Rollback` when you want to cancel quietly (and remember the call then returns `nil`). ## Leaving the block early In Rails 7.2 and later, `return`, `break` or `throw` out of a transaction block **commits** what was done so far. Earlier versions rolled back with a deprecation warning, and the `commit_transaction_on_non_local_return` setting that controlled it was removed in Rails 8.0. Code written to "bail out" with `return` therefore needs a `raise` instead if the intent is to undo. ## What a transaction does not give you - **Other connections.** A transaction belongs to one connection. If `Wallet` and `AuditEntry` live in different databases, `Wallet.transaction` does not cover `AuditEntry` writes. - **Isolation from concurrent requests.** Two transfers can both read `from.credits == 100` and both write `50`. Atomicity says each transfer is all-or-nothing, not that they cannot interleave; row locks or `lock_version` solve that. - **Undoing the outside world.** A webhook sent or an email delivered inside the block stays sent after a rollback. Work like that belongs after the commit. ## Reading it in the log The development log makes the behaviour visible. Each transaction shows up as `TRANSACTION (0.1ms) BEGIN` followed by the statements and either `TRANSACTION (0.2ms) COMMIT` or `TRANSACTION (0.1ms) ROLLBACK`. When a transfer misbehaves, checking which of the two closes the block, and whether the failing statement appears at all, answers most questions faster than reading the code. A validation failure, for instance, leaves no UPDATE in the log for that record, because the SQL was never sent. ## Where the boundary usually lives - `Wallet.transaction` and `wallet.transaction` are the same thing: the instance method delegates to the class, and both use the model's connection. - Put the block around one use case, typically in a model class method or a service object, rather than in a controller action, so it can be reused and tested. ## What interviewers listen for 1. "Only exceptions roll back" stated plainly, with the bang-method fix. 2. The special status of `ActiveRecord::Rollback` and the `nil` return. 3. The 7.2 change for `return` inside the block. 4. Awareness that atomicity is not concurrency control.

  • In Rails 8.1, what happens when a method returns from inside a Wallet.transaction block after the debit but before the credit?
    The transaction commits, so the debit is saved without the credit. Since Rails 7.2 a non-local exit (`return`, `break`, `throw`) commits; the earlier roll-back-with-warning behaviour was removed. To undo, raise an exception (or `ActiveRecord::Rollback`) instead of returning.
  • Why should you not rescue ActiveRecord::StatementInvalid inside a transaction block and carry on?
    On some databases, PostgreSQL among them, a failed statement aborts the whole transaction, and every later statement errors until it ends. Rescuing inside the block hides the failure from Rails but not from the database. Let it propagate, or isolate the risky statement in a `transaction(requires_new: true)` savepoint.

  • Any failed save inside a transaction block rolls the whole transaction back.
  • update raises ActiveRecord::RecordInvalid when it is called inside a transaction.
  • Returning early from a transaction block rolls it back in Rails 8.1.
  • A transaction block stops two concurrent transfers from reading the same balance.
  • Model.transaction also covers writes made through another database's models.

Assumes Rails 8.1; since 7.2 return, break or throw out of a transaction block commits, and the old rollback behaviour's setting was removed in 8.0.

open as a page

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%

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.

open as a page

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%

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.

open as a page

In Rails, how does raising ActiveRecord::Rollback inside a transaction differ from raising another exception, and why can it silently do nothing in a nested block?

level: middleimportance: should knowfreq 50%

basics

~20 s

Both roll back a transaction that the block itself opened, but transaction swallows ActiveRecord::Rollback and returns nil, while any other exception is re-raised. In a nested block that joined an outer transaction, Rollback is swallowed without any ROLLBACK, so the outer block commits.

open as a page

Since Rails 7.2, what does after_commit on the transaction object yielded by Wallet.transaction do, and when does its block run inside nested transactions?

level: middleimportance: should knowfreq 30%

basics

~20 s

Wallet.transaction yields an ActiveRecord::Transaction, and its after_commit registers a block that runs once the outermost real transaction commits. Registered in a savepoint, it moves up on success and is dropped on rollback; with no transaction open, it runs immediately.

open as a page

In Rails, when does transaction(requires_new: true) give you a savepoint, and what do the isolation: and joinable: options change for nested transaction calls?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Inside an open transaction, requires_new: true wraps the block in a savepoint, so its failure undoes only that block. isolation: applies only to a new top-level transaction and raises TransactionIsolationError when joining with another level or nesting; joinable: false makes later nested calls take savepoints.

open as a page