Job retries help your app try again if something goes wrong. Error handling lets you manage problems smoothly without crashing.
Job retries and error handling in Ruby on Rails
class MyJob < ApplicationJob retry_on SomeError, wait: 5.seconds, attempts: 3 def perform(*args) # job code here rescue AnotherError => e # handle specific error end end
retry_on tells Rails to retry the job if the specified error happens.
You can set how long to wait between retries and how many times to try.
class EmailJob < ApplicationJob retry_on Net::OpenTimeout, wait: 10.seconds, attempts: 5 def perform(user_id) user = User.find(user_id) UserMailer.welcome_email(user).deliver_now end end
class DataImportJob < ApplicationJob retry_on StandardError, wait: :exponentially_longer, attempts: 4 def perform(file_path) # import logic end end
class CleanupJob < ApplicationJob discard_on ActiveRecord::RecordNotFound def perform(record_id) record = Record.find(record_id) record.cleanup end end
This job is configured to retry_on RuntimeError with wait: 3.seconds and attempts: 2. Directly calling perform bypasses the ActiveJob queue and retry logic. In a real application, enqueue the job using perform_later(true) to see the retry behavior in action. The sample shows a single failure and a success case.
class RetryExampleJob < ApplicationJob retry_on RuntimeError, wait: 3.seconds, attempts: 2 def perform(should_fail) puts "Job started" if should_fail puts "Simulating failure" raise RuntimeError, "Something went wrong" end puts "Job succeeded" end end # Simulate running the job with failure job = RetryExampleJob.new begin job.perform(true) rescue RuntimeError => e puts "Job failed: #{e.message}" end # Run the job without failure job.perform(false)
Time complexity: Depends on job duration and retry count.
Space complexity: Minimal, just job data stored between retries.
Common mistake: Not handling specific errors, causing infinite retries.
Use retries for temporary errors; use discard_on for permanent failures.
Job retries let your app try again if a job fails temporarily.
Error handling helps manage problems without crashing your app.
Use retry_on and discard_on to control retry behavior in Rails jobs.