Using Sidekiq to Handle Background Tasks

What is sidekiq?

Sidekiq let you run background tasks with your Rails application. It uses a Redis database as a queue to process background jobs.

Requirements

Your application should have access to a Redis instance, like the one provided by the Redis Addon

Adding sidekiq to your Project

To get started using Sidekiq, you need to configure your application.

gem 'sidekiq'

Then, run bundle install to install the gem.

That’s it your application is ready, you can find more information on their Github page

Configure Sidekiq

Create a file in config/initializers/sidekiq.rb with the following content:

Sidekiq.configure_server do |config|
  config.redis = { url: (ENV["REDIS_URL"] || 'redis://localhost:6379/0'), namespace: "sidekiq-#{Rails.env}" }
end

Sidekiq.configure_client do |config|
  config.redis = { url: (ENV["REDIS_URL"] || 'redis://localhost:6379/0'), namespace: "sidekiq-#{Rails.env}" }
end

These instruction will configure Sidekiq to use your local database when working locally, and configure the redis instance from the environment variable REDIS_URL when used in production, deployed on the platform.

Adding ‘worker’ container type in your Procfile

Once sidekiq has been installed, you need to add a new type of containers in your application which will actually start sidekiq. Add the following line to the Procfile of your project. Create the file if it doesn’t exist.

worker: bundle exec sidekiq

All you have to do now is to write your workers by following Sidekiq documentation and deploy your code:

git add Gemfile Gemfile.lock Procfile
git commit -m "Add Sidekiq"
git push scalingo master

The process won’t be started directly, but by going to the dashboard of your application or by running the scalingo ps command, you’ll see that’s the new container type is present, just scale it to 1 to start it.

schedule 02 May 2016