skip to content

In Rails 8.1, what happens when perform_later is called inside an Active Record transaction, and how does enqueue_after_transaction_commit change it?

level: seniorimportance: must knowfreq 52%

answer

  1. default false in 8.1
  2. pushed before the commit
  3. worker cannot see uncommitted rows
  4. true: after_all_transactions_commit, dropped on rollback
  5. adapter's own preference ignored

basics

~20 s

In Rails 8.1 the job is pushed at once, before commit, so a worker may see uncommitted or rolled-back data. Setting self.enqueue_after_transaction_commit = true on the job or ApplicationJob defers the push to commit and drops it on rollback.

solid answer

~40 s

In Rails 8.1 `enqueue_after_transaction_commit` is a per-job class attribute that defaults to `false`, so `perform_later` inside `Enrollment.transaction` hands the job to the adapter at once. With Solid Queue on its own `queue` database, as `rails new` sets it up, that job row commits independently: a worker may run before the enrollment commits and hit `DeserializationError` or stale data, and if the transaction rolls back the job still runs. Setting `self.enqueue_after_transaction_commit = true`, usually in `ApplicationJob`, registers the enqueue with `ActiveRecord.after_all_transactions_commit`: it happens once every open transaction commits, is dropped on rollback, and runs immediately when no transaction is open. `perform_later` then returns the job instance right away. An adapter's own preference is no longer consulted, and 7.2's global config and `:never`/`:always`/`:default` values were removed in 8.1.

code

ruby · 10 lines
ruby
class ApplicationJob < ActiveJob::Base
  self.enqueue_after_transaction_commit = true
end

Enrollment.transaction do
  enrollment.update!(completed_at: Time.current)
  GenerateCertificateJob.perform_later(enrollment) # registered, not pushed yet
  raise ActiveRecord::Rollback if enrollment.course.archived?
end
# committed: the job is pushed now; rolled back: it is never pushed

go deeper

for a junior

Know that a job queued inside a transaction can run before the data is committed, and that Rails 8.1 does not defer it unless told to.

for a middle

Explain the worker's separate connection, the class attribute and its false default, and what happens on commit and on rollback.

for a senior

Enable deferral deliberately in ApplicationJob, know which backends make the race real, and remember deferral fixes ordering but not durability.

for a principal

Decide where ordering is enough and where intent must be recorded inside the transaction, and how to keep that consistent across teams and backends.

## The race A **database transaction** keeps its writes invisible to other connections until it commits. A background worker always uses **its own connection**. So if a job that depends on a write is queued *before* that write commits, two things can go wrong: - **The job runs too early.** The worker picks it up within milliseconds, loads the enrollment through GlobalID and either cannot find it (a new row, so `ActiveJob::DeserializationError`) or sees the old state (an update not yet visible). - **The transaction rolls back, but the job is already queued.** The certificate job runs for a course completion that never happened. ```ruby Enrollment.transaction do enrollment.update!(completed_at: Time.current) enrollment.course_progress.update!(state: "finished") GenerateCertificateJob.perform_later(enrollment) end ``` ## What Rails 8.1 does by default In 8.1, **`enqueue_after_transaction_commit` is a class attribute on every job, with a default of `false`**, and the generated `ApplicationJob` does not change it. So in the block above the job is handed to the adapter the moment `perform_later` runs, inside the transaction. Whether that is dangerous depends on where the queue lives: | Queue setup | Is the job insert part of the app's transaction? | |---|---| | Solid Queue on its own `queue` database (what `rails new` configures in production) | No: the job commits independently, so the race exists | | Solid Queue sharing the application's database and connection | Yes: the job row commits or rolls back with the transaction | | A Redis-backed backend such as Sidekiq | No: Redis knows nothing about the SQL transaction | The middle row is a coincidence of deployment, not a guarantee: move the queue to its own database or switch backends and the protection disappears without any code change. The Active Job guide recommends not relying on it. ## Turning deferral on ```ruby class ApplicationJob < ActiveJob::Base self.enqueue_after_transaction_commit = true end ``` With the attribute set to `true` (on one job or on `ApplicationJob` for all of them), Active Job's enqueue goes through `ActiveRecord.after_all_transactions_commit`: 1. If **no transaction is open** on any connection pool, the job is enqueued immediately, as usual. 2. If transactions are open, the enqueue is registered to run **after all of them commit**, including transactions on other databases. 3. If the transaction **rolls back**, the registered enqueue never runs: the job is dropped. 4. `perform_later` returns the **job instance immediately**, before the job is actually pushed, so the return value no longer proves the push happened. The **enqueue callbacks** run at commit time, with the queue, priority and `scheduled_at` captured at the original call. Since 8.1.2, `ActiveJob.perform_all_later` honours the same per-job setting, deferring only the jobs whose class enables it. ## How it got here - **7.2** introduced automatic deferral, with symbol values (`:never`, `:always`, `:default`) and a global `config.active_job.enqueue_after_transaction_commit`, letting each adapter state a preference. - **8.0** deprecated the setting. - **8.1** removed the global config and the symbol values. What remains is a per-job `true`/`false`, defaulting to `false`. The Solid Queue adapter still answers `true` to `enqueue_after_transaction_commit?`, but Rails 8.1 no longer asks. Some documentation, including the comment on `perform_later` itself, still describes the old implicit deferral; the source is what counts. ## Spotting the race in production The bug is intermittent, which is why it survives code review. Typical symptoms and checks: 1. `ActiveJob::DeserializationError` appears for records created moments earlier, mostly under load, when workers are idle enough to grab jobs within milliseconds. 2. Jobs act on state that was never committed, such as a certificate issued for an enrollment whose completion was rolled back by a later validation failure. 3. Look for `perform_later` calls that run inside a transaction without being obvious about it: model callbacks such as `after_save` and `after_create` run inside the save's transaction, and service objects often wrap several writes in `transaction`. 4. Check the deployment: is the queue on its own database or in Redis? If so, the race is real for every such call site. ## Alternatives and limits - Enqueueing from a model's `after_commit` callback, or from `transaction.after_commit` on the transaction object, gives the same ordering for one call site; enabling the attribute in `ApplicationJob` covers every job at once. - Deferral fixes ordering, **not durability**: if the process dies between the commit and the deferred enqueue, the job is lost. Work that must never be lost needs a pattern that records the intent inside the transaction itself. - Jobs enqueued after commit should still tolerate running more than once, because backends retry.

  • Why might a team rely on Solid Queue's transactional behaviour by accident, and why is that fragile?
    If Solid Queue shares the application's database and connection, the job row is written inside the same transaction, so jobs vanish on rollback without any setting. That holds only for that topology. Moving Solid Queue to its own `queue` database, as `rails new` does, or switching backends silently reintroduces the race, so the guide recommends enabling `enqueue_after_transaction_commit` explicitly.
  • With deferral enabled, what does perform_later return inside an open transaction?
    The job instance, immediately, even though nothing has reached the adapter yet. The actual push and the enqueue callbacks happen at commit. So a truthy return value no longer proves the job is queued, and on rollback the instance you got back was never enqueued.

Deferring the enqueue is like posting the confirmation letter only after the contract is signed: if the deal falls through, the letter is never sent, and if no deal is pending, it goes out straight away.

  • Rails 8.1 always defers perform_later until the transaction commits
  • Setting config.active_job.enqueue_after_transaction_commit in application.rb enables deferral in 8.1
  • The Solid Queue adapter turns deferral on for you
  • Deferring the enqueue guarantees the job can never be lost
  • A job enqueued inside a transaction runs inside that same transaction

Assumes Rails 8.1: enqueue_after_transaction_commit is a per-job class attribute defaulting to false; 7.2's global config and symbol values were removed in 8.1.