Asynchronous Job Processing in Rails with Sidekiq

Photo by Solomon Hsu on Unsplash

Every now and then we are in need of background jobs in Rails. Rails have a framework for easily writing background jobs

Active Jobs 
https://guides.rubyonrails.org/v4.2/active_job_basics.html

But Active jobs are useless without a queuing backend as they will run like normal logic otherwise. I used Sidekiq for the same purpose and documenting my implementation herein.

Here is a short read about sidekiq gem https://github.com/mperham/sidekiq

Include Sidekiq gem in your Gemfile —

gem "sidekiq"

Run bundle install and generate your first worker with following command —

rails g sidekiq:worker Report

The above command will generate class ReportWorker.rb in your application. You write logic to be executed in def perform method of class and call the method from your controller like this —

ReportWorker.perform_async()

Note one can add parameters in perform function as required and pass them from controller accordingly

Sidekiq uses redis as backend, hence its important for the same to be installed in your system. Use following command to install redis

#for mac 
brew install redis
#for ubuntu like os
sudo apt install redis-server

Start redis with following command, by default redis is started at port 6379

redis-server

Include following configuration files in your system

  • config/initializer — sidekiq.rb
  • config — sidekiq.yml

Its important to mention some basic configurations

following are my configuration files, one can alter it according to ones requirement

sidekiq.rb

Sidekiq.configure_server do |config|
config.redis = { db:1, url: 'redis://127.0.0.1:6379/' }
end
Sidekiq.configure_client do |config|
config.redis = { db:1, url: 'redis://127.0.0.1:6379/' }
end

sidekiq.yml

:concurrency: 1
:pidfile: tmp/pids/sidekiq.pid
:logfile: log/sidekiq.log
staging:
:concurrency: 2
production:
:concurrency: 1
:queues:
- default

Start sidekiq with following command

bundle exec sidekiq -d -L log/sidekiq.log

Keep checking the logs to see sidekiq is up and running

Thats it !! Voila !! Your application is all good to use sidekiq to run your background job.