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?
answer
- a timeout hides a possible success
- job_id survives retry_on
- executions changes, arguments do not
- check before calling, unique index after
- key the vendor call by the order
basics
~20 sTreat 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.
solid answer
~50 sA `Net::ReadTimeout` means the client stopped waiting, not that the vendor did nothing, so `retry_on` can rerun a purchase that already went through. `retry_job` re-enqueues the **same** job: the `job_id` and arguments are unchanged, while `executions` grows and the backend gives each attempt a new `provider_job_id`. The fix has three parts. First, look before buying: `return if order.shipping_label` at the top of `perform`. Second, make the vendor call repeatable: pass an idempotency key built from the order, such as `"label-order-#{order.id}"`, so the vendor returns the existing label instead of buying another; the order is a better key than `job_id`, because a second `perform_later` for the same order gets a new `job_id`. Third, let the database settle races: a unique index on `shipping_labels.order_id`, with `ActiveRecord::RecordNotUnique` rescued as "already done". Keep the HTTP call outside any open transaction.
go deeper
Remember that a retried job can run its side effects twice, so a job should check whether its work is already done before doing it.
Explain which Active Job values survive retry_on: job_id and arguments stay, executions and provider_job_id change, and why a business key beats job_id.
Layer the defences: a check before the call, an idempotency key on the remote API, a unique index with RecordNotUnique, and no transaction around HTTP.
Set conventions for side-effecting jobs: which vendors must support idempotency keys, how retries are scoped, and how duplicates are detected and reconciled.
## Why retries duplicate side effects An online print shop's `ShippingLabelJob` calls a carrier API that charges for every label it creates. The job declares `retry_on Net::ReadTimeout`. Consider one bad run: 1. The job sends the purchase request. 2. The carrier creates and bills the label. 3. The response is slow, and the client raises `Net::ReadTimeout` before it arrives. 4. `retry_on` schedules the job again, and the next run buys a **second** label. The retry rule did exactly what it was told. The problem is that the job assumed "exception" meant "nothing happened". A job that `retry_on` may rerun has to be safe to run more than once, and Rails provides several of the pieces. ## What a retry keeps and what it changes `retry_on` calls `retry_job`, which enqueues the current job object again with a delay. That determines what the next run can rely on: | Value | Across `retry_on` retries | Across a manual retry of a failed execution | |---|---|---| | `job_id` | unchanged | unchanged | | `arguments` (the order's GlobalID) | unchanged | unchanged | | `executions` | incremented on every run | reset to 0 | | `exception_executions` | per-rule counters grow | reset | | `provider_job_id` | new backend id per enqueue | unchanged on Solid Queue, which reuses the job row | So `job_id` identifies one logical job through all its attempts. It does **not** identify the business operation: a double click that calls `ShippingLabelJob.perform_later(order)` twice produces two jobs with different `job_id`s, and both would buy a label. That is why the guard below keys on the **order**, not the job. ## Three layers of protection ```ruby class ShippingLabelJob < ApplicationJob retry_on Net::OpenTimeout, Net::ReadTimeout, wait: :polynomially_longer, attempts: 6 def perform(order) return if order.shipping_label # done by an earlier run label = LabelClient.purchase(order, idempotency_key: "label-order-#{order.id}") order.create_shipping_label!(carrier_label_id: label.id, pdf_url: label.pdf_url) rescue ActiveRecord::RecordNotUnique # a concurrent run saved the label first; nothing left to do end end ``` 1. **Check first.** If an earlier attempt finished and saved the label, a retry returns immediately. Cheap, and it covers most reruns. 2. **Make the remote call repeatable.** The check cannot help when the first attempt timed out before saving anything. Sending a stable key lets the carrier recognise the repeat and return the label it already made, if the API supports such keys. Without one, the job can first look the label up by the order reference before buying. 3. **Let the database decide races.** Two runs (a retry and a duplicate enqueue, say) can both pass the check at once. A unique index on `shipping_labels.order_id` makes the second insert raise `ActiveRecord::RecordNotUnique`, which the job treats as success. A model-level `validates :order_id, uniqueness: true` alone does not close the race, because both runs can validate before either inserts. ## Jobs with more than one side effect The print shop's job might also email the customer once the label exists. A retry after the email was sent would repeat it, so treat each side effect as its own step: - record progress on the order (`label_state`, `label_emailed_at`) and skip any step already recorded; - or enqueue the email as a separate job only after the label row is saved, so retrying the label job never touches it; - keep each step's retry rules on the job that owns that step. The smaller each job's side effect, the easier it is to make a rerun harmless. ## Mistakes that undo it - **Wrapping the HTTP call in a transaction** to "roll back" on failure: a rollback cannot un-buy a label, and the open transaction holds a database connection for the whole slow call. - **Keying on `executions`** or on `provider_job_id`: both change between attempts. - **Keying on `job_id` alone** when the same order can be enqueued twice. - **Retrying broad errors**: `retry_on StandardError` turns a bug that fires after the purchase into repeated purchases. - **Assuming the backend prevents duplicates**: neither `perform_later` nor `retry_on` deduplicates jobs. ## Where this sits The general theory of idempotency keys and deduplication stores is broader than Rails; what is specific here is knowing which Active Job values survive a retry, using `retry_on` only for errors where a rerun is safe, and leaning on Active Record's unique-index errors to settle races.
- Why not wrap the purchase and the insert in one transaction?A transaction can roll back the `shipping_labels` insert but not the carrier's charge, so it gives no protection against the duplicate. It also holds a database connection, and any row locks, open for the length of a slow HTTP call, which starves other threads. Make the remote call idempotent, then record the result in a short write.
- Could limits_concurrency in Solid Queue replace these guards?It can stop two jobs for the same order from running at the same moment, which narrows the race, but it does nothing about a retry after a timeout: that rerun happens later, alone, and buys again. Concurrency limits complement the check-first guard and the idempotency key; they do not replace them.
A read timeout is like a phone line dropping right after you order a print job by phone: you cannot tell whether the shop heard you. Calling back and ordering again risks two jobs; calling back and quoting your order number lets the shop say it already has it.
- Assuming a Net::ReadTimeout means the label was not purchased
- Using executions or provider_job_id as the idempotency key
- Relying on validates uniqueness: true to stop concurrent inserts
- Wrapping the carrier call in a transaction to undo a purchase
- Expecting perform_later to skip a duplicate job for the same order