skip to content

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%

answer

  1. include a module, define perform
  2. class-level perform_async returns a jid
  3. perform_in and perform_at schedule
  4. strict JSON arguments since Sidekiq 7
  5. pass photo.id and "medium", not records or symbols

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.

solid answer

~40 s

A native job is a plain Ruby class that does `include Sidekiq::Job` (`Sidekiq::Worker` is the old alias for the same module) and defines an instance method `perform`; `bin/rails generate sidekiq:job thumbnail` writes one to `app/sidekiq/thumbnail_job.rb`. You enqueue it with class methods: `ThumbnailJob.perform_async(photo.id, "medium")` pushes a JSON payload onto the job's Redis queue and returns the job id (`jid`), while `perform_in(10.minutes, ...)` and `perform_at(time, ...)` schedule it. Arguments are stored as plain JSON, and since Sidekiq 7 the client raises `ArgumentError` for anything other than strings, numbers, booleans, `nil`, arrays and string-keyed hashes. So you pass `photo.id`, not the record, and `"medium"`, not `:medium`. A separate `bundle exec sidekiq` process later runs `perform` on one of its threads.

code

ruby · 12 lines
ruby
# Enqueue from a controller after an upload
class PhotosController < ApplicationController
  def create
    @photo = Current.user.photos.create!(photo_params)
    ThumbnailJob.perform_async(@photo.id, "medium")       # => "b3f2c1..." (the jid)
    ThumbnailJob.perform_in(10.minutes, @photo.id, "large")
    redirect_to @photo
  end
end

# Raises ArgumentError under Sidekiq's strict arguments:
# ThumbnailJob.perform_async(@photo, :medium)

go deeper

for a junior

Recall the shape: include Sidekiq::Job, an instance perform, perform_async on the class returning a jid, and arguments limited to simple JSON values such as ids and strings.

for a middle

Explain why arguments are restricted: the payload is JSON in Redis, strict mode rejects symbols, times and records, and passing ids makes the job read fresh data.

for a senior

Show judgment on enqueue volume and payload design: perform_bulk for backfills, small payloads, find_by for rows that may vanish, and scheduled jobs for deferred work.

for a principal

Weigh when native jobs are worth stepping outside Active Job: fewer abstractions and lower overhead, at the cost of a second job API for the team to learn and test.

## What a native Sidekiq job is **Sidekiq** is a background-job library for Ruby that keeps its queues in **Redis** and runs jobs on threads inside separate worker processes. A Rails app can reach it in two ways: through Active Job (`perform_later` with the `:sidekiq` adapter), or with **native Sidekiq jobs**, which skip Active Job entirely. A native job is any class that mixes in `Sidekiq::Job` and defines an instance method called `perform`: ```ruby # app/sidekiq/thumbnail_job.rb on a stock-photo site class ThumbnailJob include Sidekiq::Job sidekiq_options queue: "thumbnails" def perform(photo_id, size) photo = Photo.find_by(id: photo_id) return unless photo # deleted since the upload ThumbnailRenderer.new(photo).render(size) end end ``` There is no base class to inherit from; the module adds the class methods that enqueue jobs and the `sidekiq_options` macro that sets per-class options such as the queue and the retry count. `Sidekiq::Worker` still works, but it is only an alias kept from before Sidekiq 6.3, so new code says `Sidekiq::Job`. The gem's generator, `bin/rails generate sidekiq:job thumbnail`, writes the class into `app/sidekiq/` plus a test. ## Enqueuing: perform_async and its siblings Each push method builds a hash (the class name, the argument array, the queue, a fresh `jid`), runs client middleware and pushes the JSON into Redis. The web request that called it carries on at once. | Call | What it does | Returns | |---|---|---| | `ThumbnailJob.perform_async(42, "medium")` | pushes onto the job's queue now | the `jid` string | | `ThumbnailJob.perform_in(10.minutes, 42, "large")` | adds it to the scheduled set, due in ten minutes | the `jid` | | `ThumbnailJob.perform_at(time, 42, "large")` | the same, at an absolute time | the `jid` | | `ThumbnailJob.set(queue: "bulk").perform_async(42, "small")` | overrides options for this one push | the `jid` | | `ThumbnailJob.perform_bulk([[1, "small"], [2, "small"]])` | pushes many jobs in batches of 1,000 | an array of `jid`s | | `ThumbnailJob.perform_inline(42, "small")` | runs `perform` right here, mostly for tests and consoles | `true`, or `nil` if middleware stopped it | Scheduled jobs wait in a Redis sorted set; a poller inside each Sidekiq process moves them onto their queue once they are due. ## Arguments must be plain JSON The argument array is serialized with JSON and parsed back in the worker. Since Sidekiq 7 the client checks every argument before pushing and, by default, raises `ArgumentError` when one would not survive the round trip. Allowed types: - `String`, `Integer`, `Float`, `true`, `false` and `nil`; - arrays of those; - hashes whose **keys are strings** and whose values are allowed types. Rejected, with an error naming the offending value: - **symbols**, such as `:medium`, because JSON would turn them into strings; - **symbol-keyed hashes**, such as `{ width: 300 }`, for the same reason; - `Time`, `Date` and `ActiveSupport::Duration` values; - **Active Record objects**: a native job does not use GlobalID, so a `Photo` is rejected rather than turned into a reference. The check can be relaxed with `Sidekiq.strict_args!(false)` in an initializer, but that only hides the conversion. The idiom is to pass identifiers and look the record up inside `perform`, which also means the job reads the current row rather than a copy taken when the job was pushed. ## Running the job 1. A worker process is started with `bundle exec sidekiq`; in a Rails app it boots the application so `Photo` and `ThumbnailRenderer` load. 2. Each processor thread blocks on Redis waiting for a job from the queues that process was told to watch. 3. The thread builds a new `ThumbnailJob` instance, calls `perform(42, "medium")` with the parsed arguments and discards the instance afterwards. 4. If `perform` raises, Sidekiq's retry machinery takes over by default instead of the job simply vanishing. ## Common mistakes - Writing `def self.perform`: Sidekiq instantiates the class and calls the **instance** method. - Calling `perform_later`, which belongs to Active Job and does not exist on a native job. - Expecting `perform_async` to return the job's result. It returns as soon as the push is done, so the caller only gets the `jid`. - Passing a hash built with symbol keys and reading `args[:width]` in `perform`. - Assuming a queue named in `sidekiq_options` is processed automatically; the worker process must be told to watch it.

  • Why look the photo up by id inside perform instead of passing the record?
    The payload is JSON in Redis, so a native job cannot carry an Active Record object at all. Looking the row up in `perform` also means the job sees the photo as it is when it runs, which may be minutes or retries later. If the row may be deleted in between, use `find_by` and return early rather than letting `find` raise `ActiveRecord::RecordNotFound` on every retry.
  • How do you enqueue thumbnails for 200,000 existing photos without 200,000 Redis round trips?
    Use `ThumbnailJob.perform_bulk(ids.map { |id| [id, "small"] })`. It goes through `Sidekiq::Client.push_bulk`, which pushes the payloads in batches of 1,000 by default (100 when an `at:` schedule is given), so the cost is a few hundred Redis calls rather than one per job. Iterate the ids with `in_batches` or `pluck` in slices so the array itself stays bounded.

  • Passing the Photo record to perform_async as if GlobalID serialized it
  • Defining perform as a class method with def self.perform
  • Saying perform_async runs the job and returns perform's result
  • Treating Sidekiq::Worker and Sidekiq::Job as two different APIs
  • Calling perform_later on a class that only includes Sidekiq::Job
  • Passing :medium or symbol-keyed hashes and expecting symbols back