skip to content

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%

answer

  1. both send ROLLBACK at the top level
  2. Rollback swallowed, others re-raised
  3. transaction returns nil after Rollback
  4. nested block joins the outer one
  5. requires_new: true for a savepoint

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.

solid answer

~40 s

`transaction` has a `rescue ActiveRecord::Rollback` with no body: the exception triggers a ROLLBACK of the transaction it opened and stops there, and the call returns `nil`. Any other exception also triggers the ROLLBACK, then propagates to the caller. The trap is nesting. A `Wallet.transaction` block inside another one does not open anything by default; it **joins** the outer transaction. Raising `ActiveRecord::Rollback` there is rescued by the inner call, no ROLLBACK is issued, and the outer block carries on and commits everything, including the inner writes. Pass `requires_new: true` to the inner call to get a savepoint that `Rollback` can undo on its own, or raise a real exception if the whole outer transaction must fail.

code

ruby · 10 lines
ruby
Wallet.transaction do
  from.update!(credits: from.credits - 50)

  Wallet.transaction(requires_new: true) do   # SAVEPOINT active_record_1
    to.update!(credits: to.credits + 50)
    raise ActiveRecord::Rollback if to.player.banned?
  end                                         # ROLLBACK TO SAVEPOINT active_record_1

  from.update!(credits: from.credits + 50) if to.player.banned?
end

go deeper

for a junior

Remember that ActiveRecord::Rollback cancels a transaction quietly, while other exceptions cancel it and keep propagating.

for a middle

Explain why a nested transaction joins the outer one, why Rollback is then a no-op, and how requires_new: true changes that.

for a senior

Avoid Rollback across method boundaries, choose named exceptions for failures callers must see, and spot the joined-block bug in review.

for a principal

Define how services signal failure inside shared transactions so composition never changes whether work is undone.

## Two ways to cancel a transaction Inside an Active Record transaction block there are two ways to make the work disappear: - **Raise any exception** (`ActiveRecord::RecordInvalid`, `ArgumentError`, `InsufficientCredits`). Rails rolls back and re-raises it, so the caller sees the failure. - **Raise `ActiveRecord::Rollback`**. Rails rolls back and then swallows it. The `transaction` call returns `nil`, and the caller sees nothing unless it checks that return value. The difference is visible in the source of `DatabaseStatements#transaction`: it ends with `rescue ActiveRecord::Rollback` and an empty body, a comment says "rollbacks are silently swallowed", and no other exception class is rescued there. ## Why Rollback can do nothing The surprise comes from nesting. By default, a `transaction` call made while another transaction is open (and joinable) **does not start anything**. It simply yields, and every statement inside becomes part of the outer transaction: ```ruby Wallet.transaction do from.update!(credits: from.credits - 50) Wallet.transaction do # joins the outer transaction to.update!(credits: to.credits + 50) raise ActiveRecord::Rollback if to.player.banned? end CreditTransfer.create!(from_wallet: from, to_wallet: to, amount: 50) end ``` If the receiving player is banned, the inner `raise ActiveRecord::Rollback` is caught by the **inner** `transaction` call. That call had not opened anything, so there is nothing for it to roll back, and it sends no `ROLLBACK`. The outer block never sees an exception, so it creates the transfer record and commits: the debit, the credit to the banned player and the transfer row are all saved. The Rails documentation calls this behaviour "surprising" and uses almost the same example. ## The fixes 1. **Ask for a real sub-transaction** with `requires_new: true`. The inner block then runs inside a savepoint; `ActiveRecord::Rollback` rolls back to that savepoint only, and the outer transaction continues without the inner writes. 2. **Raise a real exception** when the whole transfer must fail. It leaves the inner block, leaves the outer block, and the outer transaction rolls back. 3. **Do not use `Rollback` across method boundaries.** A service method that raises `ActiveRecord::Rollback` behaves differently depending on whether its caller already opened a transaction, which is exactly the kind of hidden coupling that breaks later. ## Comparing the outcomes | Inner block raises | Inner call | Outer block | Result | |---|---|---|---| | `ActiveRecord::Rollback` (joined) | swallows, no SQL | continues | everything commits | | `ActiveRecord::Rollback` (`requires_new: true`) | `ROLLBACK TO SAVEPOINT`, swallows | continues | outer work commits, inner work undone | | `InsufficientCredits` (joined) | re-raises | sees the exception | everything rolls back, exception reaches the caller | | `InsufficientCredits` (`requires_new: true`) | rolls back the savepoint, re-raises | sees the exception | everything rolls back unless the outer block rescues it | ## The nil return At the top level, `ActiveRecord::Rollback` does roll back, and the call returns `nil` instead of the block's value: ```ruby result = Wallet.transaction do from.update!(credits: from.credits - 50) raise ActiveRecord::Rollback :done end result # => nil ``` Code that treats `nil` as "it worked" will mislead you. When the caller needs to know, raise a named error instead. ## Choosing between them - Use **`ActiveRecord::Rollback`** for a deliberate, quiet cancel in code that owns the transaction and checks the `nil` result, such as a dry-run mode that computes a transfer and then discards it. - Use **a named exception** (`InsufficientCredits`, `PlayerBanned`) whenever the caller has to react: it rolls back at every level and carries the reason with it. - Use **`requires_new: true`** when one step may fail without spoiling the rest, and handle that failure right outside the inner block. - Avoid relying on `ActiveRecord::Rollback` in a method that might be called from inside someone else's transaction; its effect then depends on the caller. ## Where Rails itself uses Rollback `save` uses the same mechanism internally: when a save fails it raises `ActiveRecord::Rollback` inside its own `transaction` call. That is why a failed `save` inside your block neither raises nor rolls back your other writes, which is the same lesson from the other side.

  • What does Wallet.transaction { raise ActiveRecord::Rollback } return, and why does that matter?
    It returns `nil`, because `transaction` rescues `ActiveRecord::Rollback` and the rescue clause has no body. A caller that expected the block's value, or that treats any non-exception as success, cannot tell that nothing was saved. Raise a named error when the caller has to react.
  • Why does a failed save inside your transaction block not roll back your other writes?
    `save` runs inside its own `transaction` call and raises `ActiveRecord::Rollback` internally when it fails. Inside your block that call has joined your transaction, so the Rollback is swallowed with no ROLLBACK, and `save` returns `false`. Your block continues and commits the rest.

  • ActiveRecord::Rollback is re-raised to the caller like any other exception.
  • Raising ActiveRecord::Rollback in a nested block always rolls back the outer transaction.
  • A nested transaction call opens a new transaction by default.
  • After ActiveRecord::Rollback, transaction returns false.
  • requires_new: true makes the inner rollback undo the outer block's writes too.