skip to content

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%

answer

  1. added in Rails 7.1
  2. three ways a job is given up
  3. receives the job and the exception
  4. the retry_on block replaces the re-raise
  5. not run when rescue_from swallows

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.

solid answer

~50 s

`after_discard` (added in Rails 7.1) registers a block that receives the job and the exception whenever Active Job **gives the job up**. That happens in three places: a `discard_on` rule matches; a `retry_on` rule has used its last attempt; or the error matches no handler at all and is about to be re-raised to the backend. It does **not** run when `retry_on` schedules another attempt, or when a `rescue_from` block handles the error without raising. The block passed to `retry_on` is narrower: it runs only when **that** rule is exhausted, and it replaces the re-raise, so the job ends as handled; `after_discard` callbacks still run afterwards. Use the `retry_on` block for rule-specific recovery, and `after_discard` for one place that marks the record and notifies people, whatever the reason. Note that "discarded" is Active Job's view: Solid Queue may still keep a failed execution that someone later retries.

go deeper

for a junior

Know that after_discard is a job callback that runs with the job and the error when Active Job stops retrying the job.

for a middle

List exactly when it runs and when it does not, and contrast it with retry_on's block, which replaces the re-raise for one rule.

for a senior

Centralise failure handling in after_discard, keep it idempotent because backends may still retry, and prefer report: true for error reporting.

for a principal

Define a consistent give-up contract for jobs, so every job leaves its records in a known state and the right people hear about it.

## What after_discard is for A job that gives up usually leaves something behind: an order still waiting for a shipping label, a customer who was promised an email. Before Rails 7.1 the clean-up had to be repeated in every `discard_on` block, every `retry_on` block and a `rescue_from` catch-all. **`after_discard`**, added in Rails 7.1, gives one hook for all of them: ```ruby class ShippingLabelJob < ApplicationJob retry_on Net::ReadTimeout, wait: :polynomially_longer, attempts: 6 discard_on LabelClient::InvalidAddress after_discard do |job, exception| order = job.arguments.first order.update!(label_state: "failed") OpsMailer.label_failed(order, exception.class.name).deliver_later end def perform(order) LabelPurchase.new(order).call end end ``` The block receives the **job instance** and the **exception**, and runs in the job's context. Several `after_discard` blocks may be declared, including inherited ones from `ApplicationJob`; they run in declaration order. ## When it runs, and when it does not | Situation | Does `after_discard` run? | |---|---| | `discard_on` matches (after its block, if any) | yes | | `retry_on` exhausted, no block: just before the error is re-raised | yes | | `retry_on` exhausted, with a block: after the block | yes | | an exception no handler matches, before it is re-raised | yes | | `retry_on` schedules another attempt | no | | a `rescue_from` block handles the error and returns | no | | `perform` succeeds | no | The common thread: it runs when Active Job stops trying, never while a retry is still pending and never when application code has declared the error handled. ## How the retry_on block differs The block given to `retry_on` and an `after_discard` callback both run at the end, but they differ in scope and effect: - **Scope.** The `retry_on` block belongs to one rule and fires only when that rule's attempts are exhausted. `after_discard` fires for every way the job can be given up. - **Effect on the outcome.** Without a block, an exhausted `retry_on` re-raises, so the backend sees a failure. With a block, the block runs **instead of** the re-raise and the job ends as handled. `after_discard` never changes the outcome by itself; it observes it. - **Order.** For an exhausted rule with a block, the block runs first and the `after_discard` callbacks run after it. So a rule-specific fallback, such as switching to a second carrier once the first keeps timing out, belongs in the `retry_on` block; the shared "mark the order and tell someone" logic belongs in `after_discard`. ## A worked timeline Follow one order through the job above while the carrier is down for a day: 1. Runs 1 to 5 raise `Net::ReadTimeout`; each time `retry_on` schedules another attempt and `after_discard` stays silent. 2. Run 6 raises again; the rule is exhausted and has no block, so the `after_discard` block sets `label_state` to `"failed"` and emails operations. 3. Active Job re-raises; Solid Queue records a failed execution. 4. The next morning the carrier is back, and someone retries the job from Mission Control Jobs; its counters are reset. 5. The job succeeds and `LabelPurchase` sets `label_state` to `"purchased"`, overwriting the failure mark. Step 5 only works because the success path writes the state again; a callback that also cancelled the order would have made the late success harmful. ## Edge cases worth knowing 1. **Errors inside the callbacks.** Every `after_discard` block runs even if an earlier one raises; afterwards the last error raised is re-raised, so a failing notification does not stop the record update, but the job does end with that error. 2. **Discarded is not deleted.** When the error escapes, Active Job considers the job discarded, but the backend decides what happens next. Solid Queue keeps a failed execution, and if someone retries it from Mission Control Jobs, the job runs again after `after_discard` already marked the order as failed. Make the callback idempotent and let a later success overwrite the state. 3. **Reporting.** Since Rails 8.1, `retry_on` and `discard_on` take `report: true` to send the error to the Rails error reporter; that is often simpler than reporting from `after_discard`. 4. **Do not retry from here.** Calling `retry_job` inside `after_discard` fights the rules that just gave up; change the `retry_on` settings instead.

  • A job has after_discard and the backend is Sidekiq. Can the job run again after the callback fired?
    Yes. When no handler matches, or retry_on is exhausted without a block, Active Job runs after_discard and then re-raises. Sidekiq sees an ordinary failure and applies its own retry policy, so the job may run again later. The callback means Active Job has given up, not that the backend has; design it to be safe if a later run succeeds.
  • Where should a shared failure notification live: ApplicationJob's rescue_from(StandardError) or after_discard?
    after_discard. A catch-all rescue_from that notifies and re-raises works, but it also fires on errors that a retry_on rule would have retried, if it is checked first, and it is easy to forget the re-raise. after_discard runs only once the job is truly given up, after the specific rules have had their say.

  • Saying after_discard runs only when a discard_on rule matches
  • Expecting after_discard to run before each retry_on attempt
  • Believing after_discard runs after a rescue_from block swallows the error
  • Claiming a retry_on block re-raises the error once it finishes
  • Treating after_discard as proof the backend will never run the job again

Assumes Rails 8.1; after_discard exists since Rails 7.1, and the report: option of retry_on and discard_on since 8.1.