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?
answer
- SAVEPOINT active_record_1
- ROLLBACK TO SAVEPOINT on failure
- rescue outside the inner block
- TransactionIsolationError when joining or nesting
- joinable: false forces savepoints below
basics
~20 sInside 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.
solid answer
~40 sWith no transaction open, `requires_new: true` just starts a normal transaction. Inside one, it starts a sub-transaction, normally `SAVEPOINT active_record_1`: success sends `RELEASE SAVEPOINT`, and an exception sends `ROLLBACK TO SAVEPOINT` before re-raising (a `Rollback` stops there). That lets you rescue an expected failure, such as `ActiveRecord::RecordNotUnique`, **outside** the inner block and keep the outer transaction usable, which matters on PostgreSQL where a failed statement otherwise poisons the whole transaction. `isolation:` (`:read_uncommitted`, `:read_committed`, `:repeatable_read`, `:serializable`) only applies when a real transaction begins; it raises `ActiveRecord::TransactionIsolationError` if the adapter lacks support, if you join an open transaction with a different level, or if you ask for it on a savepoint. `joinable: false` marks a transaction that nested calls cannot join, so each of them gets its own savepoint; Rails' transactional tests rely on that.
go deeper
Know that requires_new: true lets an inner block roll back on its own without cancelling the outer transaction.
Describe the SAVEPOINT, RELEASE and ROLLBACK TO SAVEPOINT sequence and why the rescue must sit outside the inner block.
Use savepoints to survive expected constraint violations on PostgreSQL, set isolation only on the outermost transaction, and handle SerializationFailure.
Decide when savepoint-heavy flows signal a design that should split into separate transactions or move work after commit.
## Savepoints in one paragraph Most databases do not support true nested transactions. They offer **savepoints** instead: a named marker inside a transaction that you can roll back to without abandoning the whole transaction. Active Record uses them to emulate nesting when you pass `requires_new: true`. ## What requires_new: true does | Situation | What Rails does | |---|---| | No transaction open | starts an ordinary transaction (`BEGIN` ... `COMMIT`) | | Inside an open transaction | starts a sub-transaction, normally `SAVEPOINT active_record_N` | | Sub-transaction block finishes | `RELEASE SAVEPOINT active_record_N` | | Exception leaves the sub-transaction block | `ROLLBACK TO SAVEPOINT active_record_N`, then re-raise | | `ActiveRecord::Rollback` in the sub-transaction block | `ROLLBACK TO SAVEPOINT active_record_N`, swallowed | Two refinements from the source: - Transactions and savepoints are **lazy**: nothing is sent until the first query inside them. - When the outer transaction has written nothing yet, Rails may **restart the outer transaction** (roll back and begin again) instead of creating a savepoint, since there is nothing to lose. What you observe is the same: the inner work is undone and the outer one goes on. ## The case that makes savepoints necessary In the arcade app, a transfer also awards a "first gift" badge, guarded by a unique index on `player_badges(player_id, badge)`: ```ruby Wallet.transaction do move_credits!(from, to, 50) begin PlayerBadge.transaction(requires_new: true) do PlayerBadge.create!(player: from.player, badge: "first_gift") end rescue ActiveRecord::RecordNotUnique # already has the badge; the transfer still commits end end ``` Without the savepoint, the failed `INSERT` would leave a PostgreSQL transaction **aborted**: every later statement fails with "current transaction is aborted, commands ignored until end of transaction block", and the transfer could not commit. With it, Rails rolls back to the savepoint, the database is usable again, and the outer block continues. Note where the `rescue` sits: **outside** the inner block. If you rescue inside it, the inner `transaction` call never sees the exception, never rolls back to the savepoint, and the transaction stays aborted. ## isolation: `transaction(isolation: :serializable)` asks the database for that isolation level for the new transaction. The valid values are `:read_uncommitted`, `:read_committed`, `:repeatable_read` and `:serializable`. Rails raises **`ActiveRecord::TransactionIsolationError`** when: 1. the adapter does not support setting isolation; 2. you join an open transaction and ask for a level different from its own ("cannot set isolation when joining a transaction"); 3. you combine `isolation:` with a savepoint ("cannot set transaction isolation in a nested transaction"). The mysql2, trilogy and postgresql adapters support the four levels. The SQLite adapter accepts only `:read_uncommitted`, and only with shared-cache mode on. What each level means is the database's business. Under `:serializable`, be ready for `ActiveRecord::SerializationFailure`, which the database raises when it refuses a conflicting commit. One more source detail: inside the non-joinable transaction that Rails' transactional tests wrap around each test, an `isolation:` on the first-level call is validated and then ignored, so tests do not fail on it. ## joinable: By default every transaction is **joinable**: a later `transaction` call without `requires_new` simply joins it. `joinable: false` changes that for calls made inside it: - nested `transaction` calls get their own sub-transaction (a savepoint) instead of joining; - the non-joinable transaction does not hand out a user-facing transaction object, so `transaction.after_commit` registered against it runs at once. Rails' fixtures use exactly this: each test runs inside a non-joinable transaction, so the transactions your code opens behave as real (savepoint) transactions and are rolled back with the test. Application code rarely needs `joinable: false`. ## Passing the options through with_lock `with_lock` accepts the same options for the transaction it opens, for example `wallet.with_lock(requires_new: true) { ... }` or `wallet.with_lock("FOR UPDATE NOWAIT", isolation: :repeatable_read) { ... }`. ## Caveat on MySQL MySQL commits implicitly on DDL such as `CREATE TABLE` or `TRUNCATE`, releasing every savepoint. Running DDL inside a `requires_new: true` block makes Rails' later `RELEASE SAVEPOINT` fail, so keep schema changes out of nested transactions there.
- Why must the rescue of ActiveRecord::RecordNotUnique sit outside the requires_new: true block rather than inside it?The inner `transaction` call rolls back to its savepoint only when an exception leaves its block. A rescue inside the block hides the error, so Rails releases the savepoint instead, and on PostgreSQL the transaction stays aborted: the next statement fails. Rescue outside the inner block, so the savepoint rollback happens first.
- In Rails, what happens if you call Wallet.transaction(isolation: :serializable) inside a transaction that was opened without isolation:?It raises `ActiveRecord::TransactionIsolationError` ("cannot set isolation when joining a transaction"), because the call would join a transaction whose level differs. Isolation is chosen when the outermost transaction begins, so set it there, or open the serializable unit outside any other transaction.
- requires_new: true raises an error when no transaction is open yet.
- Rescuing the error inside the requires_new block still rolls back to the savepoint.
- isolation: can tighten the level of a savepoint inside a transaction.
- On PostgreSQL you can rescue a failed INSERT mid-transaction and keep querying normally.
- joinable: false makes every nested transaction call raise an error.