In Active Record, what does wrapping two wallet updates in a transaction block guarantee, and which failures inside the block actually roll it back?
answer
- one connection, all or nothing
- an exception escaping the block
- save returns false, save! raises
- ActiveRecord::Rollback is swallowed
- return or break commits since 7.2
basics
~20 sA 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 linesclass 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
endgo deeper
Know that a transaction commits everything or nothing, and that an exception leaving the block is what rolls it back; prefer update! inside one.
Explain the full table: re-raised exceptions, the swallowed ActiveRecord::Rollback returning nil, false returns, and commit on return since 7.2.
Point out what atomicity does not cover: other connections, concurrent readers, and side effects that a rollback cannot undo.
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.