skip to content

Active Job

Active Job wraps background work in one API over swappable queue backends such as Solid Queue and Sidekiq, with per-job queues, scheduling and retry rules. Interviewers ask what belongs in a job.

part ofRuby on Railsread it →
on this pageshow

explore

questions

23

In Rails, what is the difference between calling perform_later and perform_now on an Active Job class, and what does each one return?

level: juniorimportance: must knowfreq 78%

answer

  1. one goes through the adapter, one does not
  2. arguments serialized only on the queued path
  3. perform_later: job instance or false
  4. perform_now: whatever perform returns
  5. :async fallback, :solid_queue in production

basics

~20 s

perform_later serializes the arguments and hands the job to the configured queue adapter, returning the job instance (or false if enqueuing failed); perform_now runs perform at once in the calling process and returns perform's own return value.

solid answer

~40 s

`perform_later` builds the job, runs the enqueue callbacks and passes it to the queue adapter, which serializes the arguments (a record becomes a GlobalID); a worker later rebuilds the job and calls `perform`. It returns the job instance, carrying its `job_id`, or `false` when a `before_enqueue` callback throws `:abort` or the adapter raises `ActiveJob::EnqueueError`. `perform_now` never touches the adapter: it runs the perform callbacks and `perform` on the caller's thread, blocks until it finishes and returns whatever `perform` returns, and an exception that no `rescue_from` handler takes propagates to the caller. Where `perform_later` goes depends on configuration: Rails falls back to `:async`, an in-process thread pool that loses pending jobs on restart (`:test` in tests), and a new app's `production.rb` is switched to `:solid_queue` by the Solid Queue installer.

code

ruby · 9 lines
ruby
job = GenerateCertificateJob.perform_later(enrollment) do |enqueued|
  Rails.logger.warn("not enqueued") unless enqueued.successfully_enqueued?
end

job            # => #<GenerateCertificateJob ...> or false
job && job.job_id

blob_id = GenerateCertificateJob.perform_now(enrollment)
# => the value perform returned; any unhandled error is raised here

go deeper

for a junior

Know which method queues and which runs inline, and what each returns: the job instance or false versus perform's own value.

for a middle

Explain the path perform_later takes: enqueue callbacks, adapter, serialization through GlobalID, and a worker that rebuilds the job and calls perform_now.

for a senior

Show you check which adapter each environment really uses, never ship :async to production, and keep slow work out of perform_now in request paths.

for a principal

Be ready to argue where inline execution is acceptable and where every side effect must cross a durable queue, and how that choice shapes failure handling.

## Two entry points to the same `perform` An Active Job class defines one instance method, `perform`, that holds the work. Rails gives you two class methods that end up calling it, and they differ in *where* and *when* the work happens: - **`perform_later`** puts the job on a queue so a separate worker runs it later. - **`perform_now`** runs it immediately, inline, in the code that called it. In an e-learning app that issues a PDF certificate when a learner finishes a course, the difference is whether the learner's request waits for the PDF to render: ```ruby class GenerateCertificateJob < ApplicationJob queue_as :certificates def perform(enrollment) pdf = CertificatePdf.new(enrollment).render enrollment.certificate.attach(io: StringIO.new(pdf), filename: "certificate.pdf") enrollment.certificate.blob.id end end GenerateCertificateJob.perform_later(enrollment) # => #<GenerateCertificateJob ...> or false GenerateCertificateJob.perform_now(enrollment) # => the blob id perform returned ``` ## What `perform_later` does 1. It instantiates the job with your arguments; the queue name and priority come from the class (`queue_as`, `queue_with_priority`). 2. It runs the **enqueue callbacks** (`before_enqueue`, `around_enqueue`, `after_enqueue`) in the caller. 3. It calls the adapter's `enqueue`, or `enqueue_at` when a delay was set with `set(wait:)`. The adapter calls `serialize` on the job, which turns every argument into JSON-safe data: an Active Record object becomes a **GlobalID** string, and an unsupported type raises `ActiveJob::SerializationError` right there, in the caller. 4. It returns the **job instance** when the adapter accepted it, or **`false`** when a `before_enqueue` callback threw `:abort` or the adapter raised `ActiveJob::EnqueueError` (kept on `job.enqueue_error`). With a block, `perform_later` also yields the job after the attempt, so `job.successfully_enqueued?` can be checked inline. The worker later calls `ActiveJob::Base.execute` with the stored payload: it rebuilds the job, and that rebuilt job's `perform_now` is what finally runs `perform`. The value `perform` returns there is never sent back to the caller. ## What `perform_now` does `perform_now` skips steps 2 to 4 entirely. It increments `executions`, runs the **perform callbacks** (`before_perform`, `around_perform`, `after_perform`) and `perform` on the current thread, and returns `perform`'s value. Because nothing is serialized, the arguments are the very objects you passed, including an unsaved record that `perform_later` would refuse. If `perform` raises, Active Job first offers the exception to the class's `rescue_from` handlers; anything they do not handle is re-raised to the caller. ## Side by side | | `perform_later` | `perform_now` | |---|---|---| | Where `perform` runs | a worker, later | the calling thread, now | | Arguments | serialized (GlobalID for records) | passed as-is | | Callbacks in the caller | enqueue callbacks | perform callbacks | | Returns | the job instance, or `false` | `perform`'s return value | | An exception in `perform` | stays on the worker side | raised to the caller unless handled | ## Which adapter receives the job `perform_later` is only as durable as the adapter behind it: - Without any configuration Rails uses **`:async`**, a Concurrent Ruby thread pool inside the same process. Jobs do run in the background, but pending and scheduled ones vanish when the process restarts. A new app's `development.rb` sets no adapter, so development uses it. - The test environment falls back to **`:test`**, which records jobs instead of running them. - `rails new` runs the Solid Queue installer, which sets `config.active_job.queue_adapter = :solid_queue` in **`production.rb`** only. ## When to reach for which - Use **`perform_later`** for anything slow or failure-prone that the user should not wait for: rendering the certificate PDF, calling a payment API, sending a batch of notifications. - Use **`perform_now`** where blocking is the point: a console fix-up, a rake task, one job composing another inline, or reproducing a failing job by hand. - Do not treat `perform_now` as a cheap `perform_later`: it holds the request thread for the full duration and surfaces the job's errors to the caller. ## Common mistakes - **Reading `perform_later`'s return value as the job's result.** It is the job object. Whatever `perform` returns on the worker is discarded, so anything the caller needs later must be written somewhere it can read, such as the attached certificate or a status column on the enrollment. - **Wrapping `perform_later` in `rescue` to catch job failures.** An error raised inside `perform` happens on the worker and never reaches the caller. Only enqueue-time problems reach it, such as `ActiveJob::SerializationError` for an argument Active Job cannot store. - **Passing bulky data as arguments.** Every argument is written into the payload. Pass the enrollment, which travels as a short GlobalID string, not the rendered PDF bytes or a large hash of attributes. - **Assuming a call inside a transaction waits for the commit.** In Rails 8.1 it does not unless the job opts in, so the worker can run before the data it needs is visible.

  • Why can perform_now take an unsaved Active Record object when perform_later raises?
    `perform_now` never serializes its arguments; the object reaches `perform` unchanged in the same process. `perform_later` serializes each argument, and an Active Record object becomes a GlobalID built from its id. An unsaved record has no id, so Active Job raises `ActiveJob::SerializationError` ("Maybe you forgot to call save?") in the caller, before anything is queued.
  • What happens to perform_later in development if nobody configured a queue adapter?
    It uses `:async`, Rails' fallback outside the test environment: a thread pool inside the running server. The job does run in the background, so the request does not wait, but nothing is persisted. Restarting the server drops every pending or scheduled job, which is why production gets `:solid_queue` instead.
  • How does the caller find out that perform_later did not enqueue the job?
    The return value is `false` instead of the job instance. That happens when a `before_enqueue` callback throws `:abort`, or when the adapter raises `ActiveJob::EnqueueError`, which Active Job stores on `job.enqueue_error`. The block form yields the job after the attempt, so `job.successfully_enqueued?` can be checked in place.

  • perform_now still goes through the queue adapter, just with no delay
  • perform_later returns the value perform computes once the worker is done
  • perform_later makes the request wait until the job has finished
  • The :async adapter persists jobs, so it is fine for production
  • perform_now serializes and reloads its arguments exactly like perform_later
open as a page

In a new Rails 8.1 app, which Active Job backend runs jobs in production, where does it keep them, and what starts its workers?

level: juniorimportance: must knowfreq 55%

basics

~20 s

Solid Queue: rails new installs it, stores jobs as rows in a separate queue database and sets it as the production adapter. bin/jobs starts its supervisor, or Puma starts it through plugin :solid_queue when SOLID_QUEUE_IN_PUMA is set.

open as a page

For a Rails job calling a flaky shipping-label API, which errors belong in retry_on, which in discard_on, and what do retry_on's defaults do?

level: middleimportance: must knowfreq 62%

basics

~20 s

retry_on takes transient errors such as timeouts and rate limits; discard_on takes errors a retry cannot fix, such as an invalid address. By default retry_on allows 5 attempts in total, about 3 seconds apart plus up to 15% jitter, then re-raises.

open as a page

In a Rails 8.1 app, what changes when Sidekiq runs jobs through Active Job's :sidekiq adapter rather than as native Sidekiq::Job classes?

level: middleimportance: must knowfreq 58%

basics

~10 s

With config.active_job.queue_adapter = :sidekiq, ApplicationJob classes keep perform_later, GlobalID arguments, callbacks and retry_on, and Sidekiq runs them inside a wrapper job. Native Sidekiq::Job classes skip Active Job: JSON-only arguments, Sidekiq's own API, less overhead.

open as a page

With Sidekiq 8 in a Rails app, how is a job whose perform raises retried, and when does it reach the dead set?

level: middleimportance: must knowfreq 60%

basics

~20 s

Sidekiq puts a failed job in its retry set and reruns it with growing delays, 25 times over about three weeks by default. When retries run out it moves the job to the dead set, which keeps 10,000 jobs for six months.

open as a page

With Solid Queue, what do the workers and dispatchers entries in config/queue.yml do, and what do threads, processes and polling_interval control?

level: middleimportance: must knowfreq 48%

basics

~20 s

In Solid Queue, workers poll their queues for ready jobs and run them in a thread pool; dispatchers move due scheduled jobs to ready and maintain concurrency limits. threads sizes each pool, processes forks worker copies, polling_interval spaces the polls.

open as a page

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%

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.

open as a page

In a Rails 8.1 app on Solid Queue, what happens to an Active Job whose perform raises when the job declares no retry_on?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Nothing retries it. Active Job runs any after_discard callbacks and re-raises, and Solid Queue records a failed execution holding the error class, message and backtrace. The job waits there until someone retries or discards it, from Mission Control Jobs or the console.

open as a page

In a Rails app using Sidekiq 8, how do you define a native Sidekiq::Job, enqueue it with perform_async, and which arguments may it take?

level: juniorimportance: should knowfreq 50%

basics

~20 s

A native job is a plain class that includes Sidekiq::Job and defines perform; ThumbnailJob.perform_async(photo.id, "medium") pushes it to Redis and returns a job id. Arguments must be plain JSON: strings, numbers, booleans, nil, arrays and string-keyed hashes.

open as a page

When a Rails job receives an Active Record object through perform_later, how does GlobalID carry it, and when is ActiveJob::DeserializationError raised?

level: middleimportance: should knowfreq 55%

basics

~20 s

Active Job stores an Active Record argument as a GlobalID string such as gid://academy/Enrollment/42 and reloads it with find when the job runs; if that lookup fails, typically because the row was deleted, ActiveJob::DeserializationError is raised before perform starts.

open as a page

In a Rails job class, how do queue_as, queue_with_priority and set(wait:, wait_until:, queue:, priority:) decide where and when an Active Job runs?

level: middleimportance: should knowfreq 45%

basics

~20 s

queue_as and queue_with_priority set a job class's default queue and priority; set(...) overrides them for one enqueue and adds a delay through wait: or wait_until:, which becomes scheduled_at. How priority is honoured is up to the adapter.

open as a page

In an Active Job class, when an exception matches several retry_on, discard_on or rescue_from declarations, which one handles it, and why does order matter?

level: middleimportance: should knowfreq 32%

basics

~20 s

retry_on and discard_on are built on rescue_from, and Active Job checks handlers from the last declared upward, the job's own before ApplicationJob's. The first whose class matches wins, so a broad rule declared after a narrow one hides it.

open as a page

A new Rails 8.1 app ships with Solid Queue; when would you still choose Sidekiq for background jobs, and what do you give up?

level: middleimportance: should knowfreq 52%

basics

~20 s

Choose Sidekiq when job volume or latency outgrows a database-backed queue, when Redis already runs, or when you want its automatic retries, dead set and Web UI. You give up Solid Queue's no-Redis setup, recurring.yml and concurrency limits, and Mission Control.

open as a page

In config/sidekiq.yml, how do queue weights change the order a Sidekiq 8 process fetches from its queues, and when can a queue starve?

level: middleimportance: should knowfreq 42%

basics

~20 s

Without weights, Sidekiq checks queues strictly in listed order, so a busy first queue starves the rest. With weights, it reshuffles the list on every fetch so each queue is checked first in proportion to its weight. Unlisted queues are never fetched.

open as a page

With Solid Queue, how do you declare a nightly job in config/recurring.yml, and which process enqueues it when it is due?

level: middleimportance: should knowfreq 40%

basics

~20 s

Add a task under the environment key with class: (or command:), optional args:, queue: and priority:, and a schedule: such as every day at 6am. Solid Queue's scheduler process, started by the supervisor, enqueues the job each time it falls due.

open as a page

A Rails job buys a shipping label, and retry_on reruns it after a Net::ReadTimeout; how do you stop a retry from buying a second label?

level: seniorimportance: should knowfreq 48%

basics

~20 s

Treat every run as possibly repeated: a read timeout can follow a purchase that succeeded. Skip the call when the order already has a label, send the vendor a key derived from the order, and back the saved label with a unique index on order_id.

open as a page

After raising a Sidekiq process's concurrency to 25 in a Rails 8.1 app, jobs start failing with ActiveRecord::ConnectionTimeoutError; why, and how do you size it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Each Sidekiq thread that queries needs its own Active Record connection, but the pool still holds the generated five, so waiting threads time out after checkout_timeout. Run Sidekiq with RAILS_MAX_THREADS=25 so concurrency and max_connections match.

open as a page

With Solid Queue, how does limits_concurrency on a job class work, and what do its key:, to:, duration: and on_conflict: options do?

level: seniorimportance: should knowfreq 30%

basics

~20 s

limits_concurrency lets Solid Queue run at most to: jobs with the same computed key at once; extras are blocked until one finishes, or dropped with on_conflict: :discard. duration: (3 minutes by default) is a failsafe for semaphores nobody released.

open as a page

In a Rails 8.1 app, what does plugin :solid_queue in config/puma.rb do when SOLID_QUEUE_IN_PUMA is set, and when should jobs move to a separate bin/jobs process?

level: seniorimportance: should knowfreq 35%

basics

~20 s

With SOLID_QUEUE_IN_PUMA set, Puma loads the plugin, which forks the Solid Queue supervisor after boot and stops it with Puma, so one container serves web and jobs. Move jobs to bin/jobs once you add servers or jobs compete with requests.

open as a page

In Rails 8.1, how do you let an Active Job accept a custom value object as an argument, and what must its serializer implement?

level: middleimportance: nice to knowfreq 18%

basics

~10 s

Write a subclass of ActiveJob::Serializers::ObjectSerializer with serialize, deserialize and a public klass method, then register it through config.active_job.custom_serializers. Without one, perform_later raises ActiveJob::SerializationError for the unsupported type.

open as a page

In Rails 8.1 Active Job, when does an after_discard callback run, and how does it differ from retry_on's final-attempt block?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

after_discard runs whenever Active Job gives a job up: discard_on matches, retry_on runs out of attempts, or an error no handler matches escapes. retry_on's block covers only that rule's exhaustion and replaces the re-raise; after_discard still runs after it.

open as a page

In a Rails 8.1 app on Solid Queue, how do you add the Mission Control Jobs dashboard, and how is it protected by default?

level: middleimportance: nice to knowfreq 25%

basics

~20 s

Add the mission_control-jobs gem and mount MissionControl::Jobs::Engine in config/routes.rb. It ships with HTTP basic authentication enabled and closed: until credentials are configured every request gets 401, and base_controller_class lets it use your app's own login instead.

open as a page

In Rails 8.1, how does ActiveJob::Continuable let a long-running job resume after a deploy stops its worker, and what must the job's code do for it to work?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Including ActiveJob::Continuable lets perform declare steps with an optional cursor; at each checkpoint the job asks the adapter whether it is stopping and, if so, saves its progress into the job data and re-enqueues itself to resume from that point.

open as a page