ruby
31 lines · 8 steps
Resilient background jobs with retry_on in Rails
An ActiveJob that syncs supplier inventory, retrying transient failures and discarding unrecoverable ones.
Explained by
highlit
1class SyncInventoryJob < ApplicationJob
2 queue_as :integrations
3
4 retry_on Faraday::TimeoutError,
5 Faraday::ConnectionFailed,
6 SupplierClient::RateLimited,
7 wait: :polynomially_longer,
8 attempts: 6,
9 jitter: 0.3
10
11 discard_on ActiveRecord::RecordNotFound
12 discard_on SupplierClient::UnknownSku
13
14 def perform(product_id)
15 product = Product.find(product_id)
16 client = SupplierClient.new(product.supplier)
17
18 snapshot = client.fetch_inventory(sku: product.sku)
19
20 product.update!(
21 stock_quantity: snapshot.available,
22 backorderable: snapshot.backorderable?,
23 inventory_synced_at: Time.current
24 )
25
26 LowStockNotifier.check(product) if snapshot.available <= product.low_stock_threshold
27 rescue SupplierClient::AuthenticationError => e
28 IntegrationAlert.raise!(product.supplier, error: e)
29 raise
30 end
31end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Separate transient errors (retry) from permanent ones (discard) so the queue self-heals without piling up doomed work.
- 2Exponential backoff with jitter spreads retries out and avoids hammering a struggling upstream service.
- 3Rescue-and-re-raise lets you alert on a specific failure while still letting the job's retry machinery run.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/resilient-background-jobs-with-retry_on-in-rails-explained-ruby-8f93/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.