Skip to content

Instantly share code, notes, and snippets.

@jameslafa
Created December 2, 2016 09:40
Embed
What would you like to do?

In case Redis is down, the job will be perform synchronously instead of crashing.

On your job, use perform_later_with_failover instead of perform_later.

Take this into account:

  1. You should find a way to monitor that Redis/Sidekiq is down and be alerted. You will be in a degraded mode if the task are executed synchronously and you should be aware of this as soon as possible
  2. You should use perform_later_with_failover only if you expect the execution time of the task to be fairly short (send email, slack notification, etc.) If you know the task requires time to be perform, it's not a good solution because your user's browser will be blocked.
# lib/active_job_with_failover.rb
class ActiveJob::Base
# In case Redis is down, it will perform the job synchronously
# Instead of crashing
def self.perform_later_with_failover(*args)
redis_available = true
Sidekiq.redis do |connection|
begin
connection.info
rescue Redis::CannotConnectError
redis_available = false
end
end
if redis_available || Rails.application.config.active_job.queue_adapter == :test
# process the job asynchronously
perform_later(*args)
else
# otherwise, instantiate and perform synchronously
perform_now(*args)
end
end
end
# Add the following line in config/environment.rb
require 'active_job_with_failover'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment