skip to content

Retries & Discards

A job's retry_on reschedules it with polynomial backoff and jitter, discard_on drops it, and after_discard runs once it is given up. Interviewers probe which errors to retry and idempotent jobs.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

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%

answer

  1. transient vs permanent errors
  2. attempts: 5 counts the first run
  3. wait: 3.seconds, jitter 0.15
  4. :polynomially_longer is executions ** 4 + 2
  5. exhausted: block, or re-raise to the backend

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.

solid answer

~50 s

Sort errors by whether time can fix them. Timeouts (`Net::OpenTimeout`, `Net::ReadTimeout`), rate limits and server errors go in `retry_on`; an invalid address, a cancelled order or a record that no longer matters go in `discard_on`. `retry_on` registers a `rescue_from` handler that re-enqueues the same job with a delay until it has run `attempts:` times, default 5 including the first run. The default `wait:` is 3 seconds; `wait: :polynomially_longer` waits `executions ** 4 + 2` seconds (about 3, 18, 83, 258). A random `jitter:` of up to 15% of the delay is added, the class-wide `retry_jitter` that `load_defaults` sets. After the last attempt, a block given to `retry_on` runs instead of re-raising; without one, the error escapes to the backend. `discard_on` ends the job quietly unless a block or, since Rails 8.1, `report: true` makes it louder.

go deeper

for a junior

Know that retry_on reruns a job after transient errors and discard_on drops it when retrying cannot help, and that each names exception classes.

for a middle

Explain the defaults: 5 attempts including the first, 3 seconds, 15% jitter, the polynomial wait formula, and what happens with and without a block when attempts run out.

for a senior

Design per-error policies around a vendor's real failure modes, keep discards visible with blocks or report: true, and avoid blanket StandardError retries.

for a principal

Set the organisation's retry conventions: which errors are transient, how long retries may stretch, and how discarded work is surfaced to the people who must act.

## Sorting the errors first An online print shop's `ShippingLabelJob` buys a label from a carrier's API once an order is packed. Each error the API client can raise needs one of three answers, and the question to ask is: **will running the same job later succeed?** | Error | Rule | Why | |---|---|---| | `Net::OpenTimeout`, `Net::ReadTimeout` | `retry_on` with backoff | the network or the vendor will usually recover | | `LabelClient::RateLimited` (HTTP 429) | `retry_on` with a longer wait | the limit resets after a while | | `LabelClient::ServerError` (HTTP 5xx) | `retry_on` with backoff | a vendor outage is temporary | | `LabelClient::InvalidAddress` | `discard_on`, plus a follow-up action | the address will not fix itself | | `LabelClient::ShipmentCancelled` | `discard_on` | the customer cancelled; nothing to ship | | an unexpected `NoMethodError` | neither | a bug; let it fail visibly and fix it | `LabelClient` is the application's own API wrapper; the point is that it raises **distinct exception classes** so the job can route them. A single generic error class would force one rule onto failures that need opposite treatment. ```ruby class ShippingLabelJob < ApplicationJob retry_on Net::OpenTimeout, Net::ReadTimeout, wait: :polynomially_longer, attempts: 8 retry_on LabelClient::RateLimited, wait: 1.minute, attempts: 10 discard_on LabelClient::InvalidAddress do |job, error| job.arguments.first.update!(label_state: "needs_address_fix") end def perform(order) LabelPurchase.new(order).call end end ``` ## What retry_on does on each failure 1. `perform` raises an exception matching the rule (by `is_a?`, so subclasses count). 2. The handler increments a counter kept **per `retry_on` declaration**: one rule listing two exception classes shares one counter between them. 3. If the count is below `attempts:`, it calls `retry_job` with the computed delay, which enqueues the **same job** (same `job_id`, same arguments) to run later. The current run then ends normally. 4. If the count has reached `attempts:`, the rule is exhausted (see below). ## The options and their defaults | Option | Default | Effect | |---|---|---| | `attempts:` | `5` | total runs, the first one included; `:unlimited` never gives up | | `wait:` | `3.seconds` | a fixed duration, `:polynomially_longer`, or a proc given the execution count | | `jitter:` | the class's `retry_jitter` (0.15 under current defaults) | adds a random 0-15% of the delay; not applied to a proc | | `queue:` / `priority:` | unchanged | re-enqueue somewhere else, for example a slower queue | | `report:` | `false` | since Rails 8.1, reports each retried error to `Rails.error` first | `:polynomially_longer` computes `executions ** 4 + 2` seconds: about 3, 18, 83, 258 and 627 seconds for the first five retries, before jitter. It replaced the misleading name `:exponentially_longer`, which Rails 7.2 removed. Jitter only ever **adds** time, so retries of many jobs that failed together spread out instead of hitting the recovering vendor at the same instant. ## Choosing attempts and waits - Size the **total retry window** to the outages you expect: with `:polynomially_longer`, `attempts: 8` gives seven retries spread over roughly 80 minutes before jitter. - For rate limits, a **fixed wait** close to the vendor's limit window beats a growing one. - Keep attempts low where a person is waiting for the result, and let a later manual retry cover long outages. - Send retries to a slower queue with `queue:` when they would otherwise compete with fresh work. - Use `attempts: :unlimited` only together with an alert, or a stuck vendor keeps the job alive for ever. ## When the attempts run out - **No block:** Active Job runs `after_discard` callbacks and re-raises. On Solid Queue the job becomes a failed execution; on a backend with its own retries, those may now begin. - **With a block:** the block receives the job and the error and runs **instead of** the re-raise; `after_discard` callbacks run after it. The job then ends as handled. ## discard_on `discard_on` registers a handler that does nothing but end the job: no retry, no error escaping, no failed execution. That silence is the risk. Give it a block to record the outcome (above, marking the order for an address fix) or `report: true` so the error reaches the error reporter. Use it for failures where a retry can never help and losing the job is acceptable.

  • Why is retry_on StandardError in ApplicationJob a poor default?
    It retries bugs and permanent failures exactly like transient ones, so a `NoMethodError` or an invalid address runs five times, with any side effects repeated, before failing. It also shadows narrower rules declared earlier in the same class, since later declarations are checked first. List the transient classes explicitly and let everything else fail visibly.
  • How would you honour a vendor's Retry-After header instead of a fixed wait?
    Raise an exception that carries the header value, then either rescue it with `rescue_from` and call `retry_job wait: error.retry_after` yourself, or use `retry_on` with a proc only if the delay can be computed from the execution count. The proc receives only the execution count, not the error, so a server-supplied delay needs the `rescue_from` plus `retry_job` route.

  • Putting LabelClient::InvalidAddress in retry_on and hoping it passes later
  • Saying attempts: 5 means five retries after the first run
  • Writing wait: :exponentially_longer as the current option name
  • Believing discard_on records the job as failed for later review
  • Claiming jitter can make a retry run earlier than the base wait

Assumes Rails 8.1: :polynomially_longer replaced :exponentially_longer (removed in 7.2), jitter 0.15 comes from load_defaults, and retry_on/discard_on gained report: in 8.1.

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 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 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

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