Skip to content

Sidekiq for Rails — background jobs, queues, and the production checklist

Wiring Sidekiq into a Rails app — Redis backend, worker classes, queue priorities, retries, scheduled jobs, and the operational settings an MSP applies.

Sidekiq is the default background-job processor for Rails — Ruby gem, Redis-backed, multi-threaded workers, web UI for inspection. This article is the Sidekiq install we run for Rails clients: gem in the Gemfile, Redis pointed at correctly (and isolated from cache), priority queues set up so emails do not starve waiting on a slow report job, retries and dead-jobs configured, and a sane systemd unit so the worker survives a reboot. The objective is a background-job tier the Rails team can ship work to and an MSP can keep healthy.

How to verify

Sidekiq needs Ruby, Redis, and a Rails app. Confirm versions and Redis layout:

ruby --version
bundle exec rails --version
redis-cli INFO server | grep redis_version
redis-cli CONFIG GET maxmemory-policy   # MUST be noeviction for the Sidekiq DB
bundle exec sidekiq --version 2>/dev/null || echo "not installed yet"

If Sidekiq shares a Redis with Rails cache, you must isolate them (separate DB number, separate Redis instance, or a Redis ACL with key prefix scoping). Cache can run allkeys-lru; Sidekiq cannot.

What’s happening

Sidekiq workers (called jobs or workers depending on era — ActiveJob and Sidekiq::Worker both exist) are Ruby classes with a perform method. The client (MyWorker.perform_async(args)) serializes the arguments to JSON and pushes them onto a Redis list keyed queue:<name>. The Sidekiq process pops jobs from configured queues, deserializes, and runs perform in a thread pool.

The architecture:

  • Redis lists — one list per queue. Sidekiq uses BRPOP to atomically pop with a timeout.
  • Sorted sets — schedule (for jobs delayed by perform_in), retry (for failed jobs awaiting redelivery), dead (for jobs that have exhausted retries).
  • Hashes — job payloads, worker stats, processes registry.

Priority queues. Sidekiq accepts a list of queues with weights: bundle exec sidekiq -q critical,4 -q default,2 -q low,1. The weights bias the BRPOP probability but not strictly — under saturation, all queues get some pick. For strict priority, list queues without weights: -q critical -q default -q low polls strictly in that order until critical is empty.

Retries. Default retry count is 25, with exponential backoff ((retry_count^4) + 15 seconds + jitter). A job that has exhausted retries goes to the dead set, where it stays for the configured dead_timeout_in_seconds (default 6 months) before being deleted permanently. Workers that raise an exception go through the retry path; workers that swallow errors silently are bugs.

Scheduled and recurring jobs. perform_in(10.minutes, args) and perform_at(time, args) push into the schedule sorted set; Sidekiq polls it every few seconds and promotes ready jobs to their queue. For cron-style recurring jobs, use sidekiq-cron or sidekiq-scheduler gems.

The procedure

  1. Add Sidekiq to the Gemfile:

    gem 'sidekiq', '~> 7.2'
    gem 'sidekiq-cron'           # optional, for cron-style recurring jobs
    bundle install
  2. Configure the Redis connection in config/initializers/sidekiq.rb:

    require 'sidekiq'
    
    Sidekiq.configure_server do |config|
      config.redis = {
        url: ENV.fetch('SIDEKIQ_REDIS_URL'),
        network_timeout: 5,
        reconnect_attempts: 3,
        size: 10
      }
    end
    
    Sidekiq.configure_client do |config|
      config.redis = {
        url: ENV.fetch('SIDEKIQ_REDIS_URL'),
        size: 2
      }
    end

    Use a separate Redis DB (redis://redis:6379/2) or a dedicated Redis instance. size is the connection pool — server-side bigger than client-side because workers need a connection each.

  3. Write a worker class:

    # app/workers/welcome_email_worker.rb
    class WelcomeEmailWorker
      include Sidekiq::Worker
    
      sidekiq_options queue: 'mailers',
                      retry: 5,
                      dead: true,
                      backtrace: 10,
                      lock: :until_executed   # if you use the sidekiq-unique-jobs gem
    
      def perform(user_id)
        user = User.find(user_id)
        UserMailer.welcome(user).deliver_now
      end
    end
  4. Enqueue from controllers or models:

    WelcomeEmailWorker.perform_async(user.id)
    WelcomeEmailWorker.perform_in(10.minutes, user.id)
  5. Write the Sidekiq config at config/sidekiq.yml:

    :concurrency: 10
    :timeout: 25
    :max_retries: 25
    :queues:
      - [critical, 4]
      - [mailers, 3]
      - [default, 2]
      - [low, 1]
  6. Write a systemd unit at /etc/systemd/system/sidekiq.service:

    [Unit]
    Description=Sidekiq
    After=network-online.target redis-server.service
    
    [Service]
    Type=notify
    NotifyAccess=all
    WatchdogSec=10
    User=app
    Group=app
    WorkingDirectory=/srv/myapp/current
    Environment="RAILS_ENV=production"
    EnvironmentFile=/etc/myapp.env
    ExecStart=/usr/local/bin/bundle exec sidekiq -e production -C config/sidekiq.yml
    ExecReload=/bin/kill -TSTP $MAINPID
    ExecStop=/bin/kill -TERM $MAINPID
    TimeoutStopSec=60
    Restart=always
    RestartSec=10
    LimitNOFILE=65536
    
    [Install]
    WantedBy=multi-user.target

    Type=notify requires Sidekiq’s systemd integration (gem ships it). ExecReload=TSTP is the canonical “stop accepting new jobs but finish what is in flight” signal.

  7. Enable and start:

    sudo systemctl daemon-reload
    sudo systemctl enable --now sidekiq
    sudo systemctl status sidekiq --no-pager
    sudo journalctl -u sidekiq -n 50 --no-pager
  8. Mount the Sidekiq web UI in config/routes.rb, behind your existing auth:

    require 'sidekiq/web'
    require 'sidekiq-cron'
    
    Rails.application.routes.draw do
      authenticate :user, ->(u) { u.admin? } do
        mount Sidekiq::Web => '/admin/sidekiq'
      end
    end

    Hit /admin/sidekiq and you see queues, busy workers, retries, scheduled, dead — the operator dashboard.

Operational notes

  • The dead set keeps poison jobs visible for triage; do not auto-clear it. A weekly review of dead jobs is a real ops practice for any Rails app with serious background work.
  • concurrency: 10 is per-process — three Sidekiq processes at concurrency 10 give you 30 concurrent threads. Match this to your DB connection pool (pool: 30 in database.yml) or you get “could not check out a connection” errors.
  • Long-running jobs are an antipattern; if perform takes more than a few minutes, you cannot deploy without TSTP + wait, and the timeout heuristics get fuzzy. Break into a state-machine of smaller jobs.
  • The Sidekiq client serializes job arguments via JSON — passing complex objects (a full ActiveRecord model) silently loses type information. Pass IDs and let perform reload.
  • sidekiq-cron triggers based on the worker host’s clock; UTC-pin the server timezone (Rails.application.config.time_zone = 'UTC') and use explicit timezone fields for user-facing scheduling.

Stack Harbor stands up Sidekiq as the background-job tier for Rails clients — workers under systemd, Redis isolated from the cache, dead-job triage on a runbook, and dashboards on queue depth and busy-thread counts. If your Sidekiq install grew from a tutorial into the engine of your async work, this is the work covered by our Managed Operations practice.