skip to content

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%

answer

  1. transaction block yields ActiveRecord::Transaction
  2. Wallet.current_transaction
  3. runs after the outermost COMMIT
  4. savepoint rollback drops it
  5. no transaction open: runs at once

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.

solid answer

~40 s

Since 7.2, `Wallet.transaction do |transaction| ... end` yields an `ActiveRecord::Transaction`, and `Wallet.current_transaction` returns the same kind of object from anywhere. `transaction.after_commit { ... }` queues a block for after the data is durable: in a joined block it is attached to the outer transaction; in a `requires_new: true` savepoint it moves to the parent when the savepoint is released and is discarded if the savepoint rolls back; with no transaction open it runs at once. `after_rollback` is the counterpart. An error raised in the block reaches the caller, but the rows stay committed. That makes it the place for side effects such as broadcasting a leaderboard update after a transfer, without tying them to one model's lifecycle. Across several databases, `ActiveRecord.after_all_transactions_commit` waits for every open transaction.

go deeper

for a junior

Know that work like broadcasts belongs after commit, and that Rails 7.2+ lets you register it with transaction.after_commit.

for a middle

Explain when the block runs: immediately with no transaction, after the outermost commit when nested, never after a rollback.

for a senior

Use current_transaction.after_commit in services to keep side effects composable, and treat callback failures as not undoing the commit.

for a principal

Decide which side effects may be best-effort after commit and which need a durable record processed by a job.

## The problem it solves Code at the end of a transaction block runs **before** `COMMIT`. If the commit then fails, or if your block is itself nested inside a bigger transaction that later rolls back, the side effect has already happened: ```ruby Wallet.transaction do move_credits!(from, to, 50) LeaderboardChannel.broadcast_to(to.player, credits: to.credits) # too early end ``` Model `after_commit` callbacks have long solved this for work tied to a record's lifecycle. Rails 7.2 added a general tool for work tied to **a unit of code** instead. ## The API - `Wallet.transaction do |transaction| ... end` yields an **`ActiveRecord::Transaction`**. - `Wallet.current_transaction` returns the current one from anywhere (a service object, a helper) and never returns `nil`: with no transaction open it returns a closed placeholder. - `transaction.after_commit { ... }` registers a block to run after commit. - `transaction.after_rollback { ... }` registers a block to run after rollback. - `transaction.open?` / `closed?` say whether a real, unfinished transaction exists; `transaction.uuid` gives an id for logging. - `ActiveRecord.after_all_transactions_commit { ... }` waits for every open transaction across all databases. ```ruby def award_bonus!(wallet, amount) wallet.update!(credits: wallet.credits + amount) Wallet.current_transaction.after_commit do LeaderboardChannel.broadcast_to(wallet.player, credits: wallet.credits) end end ``` Called inside a transfer's transaction, the broadcast waits for the transfer to commit. Called on its own, it runs immediately after the update, because there is nothing to wait for. ## When the block runs | Where `after_commit` was registered | When the block runs | |---|---| | No transaction open | immediately | | Top-level transaction | right after its `COMMIT` | | A joined inner block (no `requires_new`) | after the outer transaction commits, because it is the same transaction | | A `requires_new: true` savepoint that is released | moved to the parent; runs after the outermost commit | | A savepoint that rolls back | never; the block is dropped | | Any level, and the outer transaction rolls back | never | | A transaction that has already finished | registration raises `ActiveRecord::ActiveRecordError` | `after_rollback` mirrors this: with no transaction open its block is never called, and a block registered in a savepoint that commits is passed up to the parent, so it runs only if something above rolls back. ## Errors inside the block By the time an `after_commit` block runs, the data is committed. If the block raises, the exception reaches the caller of `transaction`, but the rows stay committed, and blocks queued after it in the same list do not run. The Rails documentation warns against relying on these callbacks alone to keep two systems consistent. For anything that must eventually happen, record the intent in the database inside the transaction and process it from a job. ## How it relates to its neighbours - **Model `after_commit` callbacks** (`after_commit :notify, on: :create`) are declared on a model and fire for each record saved in the transaction. They suit behaviour that belongs to the record; `transaction.after_commit` suits behaviour that belongs to the calling code. - **Enqueuing jobs**: in Rails 8.1 a job enqueued inside a transaction is not deferred unless the job class sets `enqueue_after_transaction_commit = true`. Wrapping `perform_later` in `transaction.after_commit` is the explicit way to defer one enqueue. ## Testing code that uses it In Rails' transactional tests every test runs inside a non-joinable transaction, so a `Wallet.transaction` your code opens becomes a savepoint inside it. Rails runs that savepoint's commit callbacks when it is released, so `transaction.after_commit` blocks fire during the test as they would in production. Assert on their effect (a broadcast, a counter) right after calling the code under test, and add a test where the transaction rolls back to prove the block does not run. ## Edge cases from the source 1. A block registered while inside a **non-joinable** transaction (the one Rails' transactional tests wrap around each test) runs immediately, because that transaction exposes no user-facing transaction object. 2. `ActiveRecord.after_all_transactions_commit` only counts joinable open transactions, and with none open it runs the block at once. 3. The `ActiveRecord::Transaction` class in 8.1 exposes `after_commit` and `after_rollback`; the doc comment on `DatabaseStatements#transaction` also shows a `before_commit`, which the public class does not define, so do not rely on it.

  • How is transaction.after_commit different from declaring after_commit :broadcast_balance in the Wallet model?
    The model callback fires for every Wallet saved in a committed transaction, wherever the save happened, so it couples the side effect to the model. `transaction.after_commit` is registered by the calling code for one unit of work, runs once, and needs no record at all. Use the model callback for record behaviour and the transaction object for use-case side effects.
  • What happens if a transaction.after_commit block raises an exception?
    The transaction has already committed, so nothing is rolled back. The exception propagates to the code that called `transaction`, and any blocks registered after the failing one in that list are skipped. Treat these blocks as best-effort and keep work that must not be lost in a job or an outbox row written inside the transaction.

  • transaction.after_commit runs its block at the end of the inner block, even when nested.
  • With no transaction open, transaction.after_commit never runs its block.
  • If an after_commit block raises, Rails rolls the committed data back.
  • A block registered in a savepoint that rolls back still runs after the outer commit.
  • Wallet.current_transaction returns nil when no transaction is open.

Assumes Rails 8.1; transaction blocks yield ActiveRecord::Transaction and current_transaction / after_all_transactions_commit exist since Rails 7.2.