skip to content

In an Active Record model, why should a gym member's welcome SMS and search-index sync go in after_create_commit and after_save_commit rather than after_save?

level: middleimportance: must knowfreq 66%

answer

  1. save wraps callbacks in a transaction
  2. after_save sees an uncommitted row
  3. after_create_commit is after_commit on: :create
  4. exceptions after commit do not roll back
  5. after_rollback for the failure path

basics

~20 s

Rails runs after_create and after_save inside the save's transaction, before COMMIT, so a later failure can roll the row back after the SMS went out. The commit variants run only once the outermost transaction has committed and the row is visible.

solid answer

~40 s

`save` wraps the whole callback chain in a transaction, so `after_create` and `after_save` run before `COMMIT`. If anything later raises, or the save sits inside an outer transaction that rolls back, the member row disappears but the SMS is already sent and the search index holds a ghost. Other database connections, such as an indexer or a job worker, cannot even see the row yet. `after_commit` runs after the outermost transaction commits; `after_create_commit` is `after_commit on: :create`, `after_save_commit` covers create and update, and `after_destroy_commit` handles removal. The trade-off: by then the data is permanent, so an exception in an `after_commit` callback reaches the caller of `save` without rolling anything back and stops the remaining commit callbacks. Keep the hook small, typically enqueuing a job, and use `after_rollback` for cleanup.

code

ruby · 18 lines
ruby
class GymMember < ApplicationRecord
  after_create_commit  :send_welcome_sms
  after_save_commit    :sync_search_index
  after_destroy_commit :remove_from_search_index

  private
    def send_welcome_sms
      WelcomeSmsJob.perform_later(self)
    end

    def sync_search_index
      MemberIndexJob.perform_later(id)
    end

    def remove_from_search_index
      MemberIndexJob.perform_later(id, remove: true)
    end
end

go deeper

for a junior

Remember that save runs inside a transaction and that after_commit and its create, update, save and destroy variants are the hooks that wait for COMMIT.

for a middle

Explain the two failure modes of after_save side effects, a rollback after the SMS and a row other connections cannot see, and map each commit macro to its on: option.

for a senior

Show the operational edges: exceptions after commit do not roll back and skip later commit hooks, outer transactions delay the callback, and callbacks fire from every code path, so keep them small.

for a principal

Decide which side effects stay as model callbacks and which become explicit calls, given that callbacks fire from consoles, imports and migrations as well as from the product flow.

## Where after_save sits Active Record wraps `save`, `save!` and `destroy` in a database transaction, and every callback up to and including `after_save` runs inside it. The `INSERT` has been sent but not committed. Two things follow for a `GymMember`: - **The row can still vanish.** If a later callback raises, or the save happens inside an outer `ActiveRecord::Base.transaction` block that fails, Rails issues `ROLLBACK`. An SMS sent from `after_create` has already reached the member's phone, and the search index now lists a member who does not exist. - **Nobody else can see the row yet.** A search indexer or a background worker reading through its own database connection finds nothing until `COMMIT`. ## The commit-aware callbacks | Macro | Same as | Fires after COMMIT of | |---|---|---| | `after_commit` | (all actions) | a create, update or destroy | | `after_create_commit` | `after_commit on: :create` | a create | | `after_update_commit` | `after_commit on: :update` | an update | | `after_save_commit` | `after_commit on: [:create, :update]` | a create or update | | `after_destroy_commit` | `after_commit on: :destroy` | a destroy | | `after_rollback` | (all actions) | a rolled-back create, update or destroy | The `on:` option accepts only `:create`, `:update` and `:destroy`; anything else raises `ArgumentError` when the class loads. ## What after_commit does and does not promise - It runs after the **outermost** transaction commits, so a member saved inside a larger transaction is announced only when that whole unit succeeds; if it rolls back, `after_rollback` fires instead. - It does not run for a record whose create failed, since nothing was persisted. - The callback body is **not** inside a transaction; writes it makes commit on their own. - An exception raised there **bubbles up** to whoever called `save`, but the row stays committed, and the remaining `after_commit` callbacks for that record are skipped. Rescue inside the callback when other commit hooks must still run. - A record saved several times in one transaction gets its commit callbacks once, after the final `COMMIT`. ## Building the gym member example 1. Put the SMS on create only: `after_create_commit :send_welcome_sms`. 2. Put the index sync on create and update: `after_save_commit :sync_search_index`. 3. Remove the document on delete: `after_destroy_commit :remove_from_search_index`. 4. Keep each method tiny: enqueue a job with the member, rather than calling the SMS gateway inline in the request. 5. Add `after_rollback` only when a step before commit wrote something outside the database, such as a file, that must be undone. Enqueuing from `after_commit` also sidesteps a separate trap: a job enqueued from `after_save` could be picked up by a worker before `COMMIT` and find no row. That is why Active Job has its own setting for deferring enqueues until commit, which is a topic of its own. ## Testing these callbacks With Rails' transactional tests, each test runs inside a wrapper transaction that is not joinable, so a model's `save` opens its own savepoint-backed transaction and its `after_commit` callbacks still fire when that inner transaction completes. You can assert on the enqueued job directly. ## after_save versus after_commit at a glance | Question | `after_save` / `after_create` | `after_commit` variants | |---|---|---| | Is the row committed? | no, still inside the transaction | yes | | Can other connections see it? | no | yes | | Does an exception roll the row back? | yes | no, it only propagates | | Does it run if an outer transaction fails? | yes, before the failure | no, `after_rollback` runs instead | | Good for | writes that must succeed or fail with the row | SMS, search index, cache, jobs | ## When a callback is the wrong home Commit callbacks fire for every save from every code path: the console, a data migration, a seed file, an admin bulk edit. When the SMS should go out only for a self-service sign-up, call it explicitly from the sign-up code path instead, or guard the callback with a condition. Interviewers often follow up on exactly that judgement.

  • What happens when an after_commit callback raises an exception?
    The data is already committed, so nothing rolls back. The exception propagates to the code that called `save` or `destroy`, and any `after_commit` callbacks for that record that had not run yet are skipped. If other commit hooks must still run, rescue and report inside the callback.
  • Do after_commit callbacks fire in Rails tests that use transactional fixtures?
    Yes. The test wrapper transaction is not joinable, so the model's save runs in its own nested transaction backed by a savepoint, and Rails runs its commit callbacks when that inner transaction completes. You do not need a gem or a non-transactional test to exercise them.
  • Why put the SMS in after_create_commit rather than plain after_commit?
    Plain `after_commit` fires after creates, updates and destroys, so every profile edit would text the member again. `after_create_commit` is `after_commit on: :create` and fires once, after the row that was inserted has committed.

A gym's front desk hands over the welcome pack only after the membership contract is countersigned, not while the form is still on the desk and could be torn up.

  • after_save runs after COMMIT, so a worker reading the row always finds it
  • An exception in after_commit rolls the INSERT back
  • after_commit fires even when the create failed validation
  • after_create_commit runs inside the transaction, just later than after_create
  • Transactional tests never run after_commit callbacks