8 min readAlvin

Not every background job deserves the same retry policy

engineeringrails

Out of the box, Sidekiq treats every job the same way. A failure gets retried 25 times on an exponential backoff, and the last retry fires about three weeks after the first failure. When it fails that time, the job moves to the Dead tab and nobody is told.

That default is reasonable for a library and wrong for an application. A job that sends an agency its client's booking confirmation and a job that warms a cache are not equally important. They shouldn't wait the same amount of time, and they shouldn't fail with the same amount of noise.

GalaFlow is our SaaS for travel agencies, built on a Rails 8 API with Sidekiq for background work. We set its retry policy before the first real job existed, because a policy is much easier to set while nothing depends on it yet. This post covers what we chose and the two Sentry details that would have quietly broken it.

Twenty days is a long time to be wrong

Sidekiq's backoff is count**4 + 15 seconds plus jitter, where count starts at zero. The first few retries come quickly. After that the gaps grow fast:

RetryDelay before it (base)Cumulative
115s15s
216s31s
331s~1 min
496s~2.5 min
5271s~7 min
25~3.8 days~20 days

Retries are good at one kind of failure: a transient one. An upstream timeout, a dropped connection or a brief rate limit usually clears within a few minutes, and the first handful of retries covers that window. A job that is still failing after an hour is usually failing for a reason a retry can't fix, such as bad data, a revoked credential or a bug. From then on the remaining retries are just a slow way of not telling anyone.

So the first decision was a global ceiling:

# config/sidekiq.yml
:concurrency: <%= ENV.fetch("SIDEKIQ_CONCURRENCY", 5) %>
:max_retries: 5
:queues:
  - [critical, 10]
  - [default, 5]
  - [low, 1]

No job in GalaFlow is retried more than five times, which means no job goes more than about seven minutes between its first failure and its death.

Three queues, weighted rather than strict

The queues are declared with weights, not in strict order. With strict ordering, Sidekiq drains critical completely before it looks at default, and default completely before low. That's fine until something floods the top queue, and then the bottom queues stop moving altogether.

With weights of 10:5:1, each fetch shuffles the queue list with those weights, so critical is checked first most of the time but not every time, and an empty queue costs nothing. low work keeps moving even when everything above it is busy.

The trade-off is that order is no longer guaranteed. A low job can sometimes finish before a critical job that was enqueued alongside it, and that's correct behaviour. Our end-to-end check, which drains a job through all three queues on a real worker, asserts that every job completed and that each one ran on the right queue. It doesn't assert the order they ran in, because that test would fail a few percent of the time with nothing actually wrong.

A tier is one line on the job

A queue and a retry count that are set separately will eventually disagree. So in GalaFlow they're set together, by a single class macro on ApplicationJob:

class ApplicationJob < ActiveJob::Base
  TIER_RETRIES = { critical: 5, default: 3, low: 2 }.freeze
 
  queue_as :default
 
  def self.queue_tier(tier, alert_on_death: tier == :critical)
    retries = TIER_RETRIES.fetch(tier) do
      raise ArgumentError,
        "unknown queue tier #{tier.inspect}, expected one of #{TIER_RETRIES.keys.inspect}"
    end
 
    queue_as tier
    sidekiq_options retry: retries, alert_on_death: alert_on_death
  end
end

A job declares queue_tier :critical and gets the queue, the retry count and the alerting behaviour in one line. A typo like :critcal raises an error when the class loads, instead of silently creating a fourth queue that no worker polls. A spec checks that every tier stays at or under the global :max_retries, so the ceiling in the YAML and the counts in Ruby can't drift apart.

In practice: a low job dies about 30 seconds after its first failure, a default job after about a minute, and a critical job after about seven.

We let Sidekiq handle retries, not ActiveJob's retry_on. With retry_on, ActiveJob re-enqueues the job itself, so Sidekiq sees a series of new jobs that each succeeded, and its Retries tab stays empty. Leaving retries to Sidekiq keeps the failing job in one place, with its error and backtrace, where the person on call will look for it.

The same reasoning applies to backoff. There's no sidekiq_retry_in anywhere in the codebase. Defining one replaces the exponential backoff entirely, and the default curve is the one we want.

Death is a different signal from failure

Every failed attempt already reaches Sentry: ApplicationJob has a rescue_from that captures the exception, tags it with the job class, id and queue, and re-raises it so Sidekiq can retry. That tells you a job is failing. It doesn't tell you that a job has stopped trying, and that is the event worth alerting on.

Sidekiq exposes that moment through death_handlers, so we register one:

# config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
  config.death_handlers << ->(job, exception) { DeadJobAlert.call(job, exception) }
end

alert_on_death was written into the job's Sidekiq payload by sidekiq_options, so the handler reads it straight from the hash Sidekiq gives it. A dead low job is visible in the Dead tab and nowhere else. A dead critical job goes to Sentry, and from there to our alerts channel.

There were two details here we would not have caught without tests.

Sentry drops the second capture of an exception. By the time a job dies, the rescue_from on its last attempt has already passed that exact exception object to Sentry.capture_exception. Sentry marks exceptions it has captured and returns early on a repeat. So the obvious handler, which captures the exception again, does nothing at all, and the critical-tier alert never fires. DeadJobAlert reports a message instead:

# simplified from lib/dead_job_alert.rb
Sentry.capture_message(
  "Dead job #{job_class}: #{exception.class}: #{exception.message}",
  level: :error,
  fingerprint: ["dead-job", job_class.to_s, exception.class.name],
  tags: { job_class: job_class, jid: job["jid"], job_id: active_job_id, queue: job["queue"] },
  extra: { retry_count: job["retry_count"], failed_at: job["failed_at"] }
)

It's a better event anyway. Failure and death are different things to know, so they belong in different Sentry issues. One spec stubs exception_captured? to true and asserts that the alert still goes out.

Sentry groups messages by their text. The text contains the exception message, and the exception message usually contains a record id. Without an explicit fingerprint, every death opens a new Sentry issue. Our alert rule fires on a newly seen issue, so we'd get one page per dead job and no history connecting them. Fingerprinting on job class and error class means deaths of the same job with the same error collect in a single issue, which pages once.

The tags carry both ids because they are different things. jid is Sidekiq's id; job_id is the one ActiveJob generates, and it's the one the earlier failure events were tagged with. Tagging both lets you trace a death back to the failures that came before it.

Testing the part nobody can click

None of this has an HTTP surface. Retry counts, payload options and death handlers all live inside the Sidekiq client and server. So the behaviour is covered by RSpec, and our Playwright plan runs those examples by name, one test per line of the plan, so a failure points at the plan line that broke.

One gotcha there: rspec -e "some example" exits with status 0 when the filter matches nothing. Rename an example and the test that runs it keeps passing while covering nothing. Each test therefore also asserts how many examples ran, so a silent rename shows up as a failure.

Where this stops working

A tier belongs to the class, not to a call. SomeJob.set(queue: :critical).perform_later moves that one run to the critical queue, but it keeps the class's retry count and alerting. If one job class needs different urgency depending on the caller, the honest fix is two classes.

Weights are priority, not isolation. Five threads are shared across all three queues. A burst of slow critical jobs can still occupy every thread. When that matters, the answer is a separate Sidekiq process, or a Sidekiq 7 capsule, for the work that has to keep moving. That costs more to run and we haven't needed it yet.

Retries assume the job is safe to repeat. A job that charges a card or emails a client and then fails on its next line will repeat the first half on every retry. The tiers decide how many times that happens. They don't decide whether it's safe, which is a property of the job and has to be designed into each one.

The tiers came before the jobs. Right now GalaFlow's background work is the infrastructure and its tests. The first real jobs will be where we find out whether three tiers is the right number, and which jobs really belong in critical. Starting that discussion with a ceiling, a single macro and an alert that works is a lot cheaper than reaching it after a job has spent three weeks failing with nobody told.

Building something and want a team that takes it from empty repo to shipped? We'd love to hear about it.