Skip to content

Instantly share code, notes, and snippets.

@jameslafa
Created December 2, 2016 09:40
Show Gist options
  • Select an option

  • Save jameslafa/dbf9c2578015d0204610e8f512d0b1c0 to your computer and use it in GitHub Desktop.

Select an option

Save jameslafa/dbf9c2578015d0204610e8f512d0b1c0 to your computer and use it in GitHub Desktop.

Revisions

  1. jameslafa created this gist Dec 2, 2016.
    8 changes: 8 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    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.
    23 changes: 23 additions & 0 deletions active_job_with_failover.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    # 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
    2 changes: 2 additions & 0 deletions environment.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    # Add the following line in config/environment.rb
    require 'active_job_with_failover'