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?
answer
- transient vs permanent errors
- attempts: 5 counts the first run
- wait: 3.seconds, jitter 0.15
- :polynomially_longer is executions ** 4 + 2
- exhausted: block, or re-raise to the backend
basics
~20 sretry_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 sSort 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
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.
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.
Design per-error policies around a vendor's real failure modes, keep discards visible with blocks or report: true, and avoid blanket StandardError retries.
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.