Using Sidekiq to Handle Background Tasks

What is sidekiq?

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


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

Adding sidekiq to your Project

To get started using Sidekiq, you need to configure your application. Add the following to your Gemfile:

gem "sidekiq"
gem "redis-namespace"

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}" }

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

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 the new container type is present. Scale it to 1 to start it.

Suggest edits

Using Sidekiq to Handle Background Tasks

©2024 Scalingo