Integrating Sidekiq for Background Processing

Tutorial 3 of 5

Introduction

In this tutorial, you will learn how to integrate Sidekiq for background processing in a Rails application. Sidekiq is a robust background processing tool that, with the help of Redis, lets you handle asynchronous tasks efficiently in your application.

What you'll learn:

  1. Installing and setting up Sidekiq
  2. Configuring Redis for Sidekiq
  3. Creating and enqueuing jobs
  4. Testing and monitoring jobs with Sidekiq Web UI

Prerequisites:

  • Basic knowledge of Ruby on Rails
  • Rails application setup
  • Familiarity with Redis

Step-by-Step Guide

Installing and Setting up Sidekiq

Add the gem to your Gemfile:

gem 'sidekiq'

Then run the bundle command:

bundle install

Configuring Redis for Sidekiq

Create a config/initializers/sidekiq.rb file and add the following:

Sidekiq.configure_server do |config|
  config.redis = { url: 'redis://localhost:6379/0' }
end

Sidekiq.configure_client do |config|
  config.redis = { url: 'redis://localhost:6379/0' }
end

This tells Sidekiq where to find the Redis server.

Creating and Enqueuing Jobs

Jobs in Sidekiq are just plain old Ruby classes. Here's an example of a job that sends a welcome email:

class WelcomeEmailJob
  include Sidekiq::Worker

  def perform(user_id)
    user = User.find(user_id)
    UserMailer.welcome_email(user).deliver
  end
end

You enqueue a job by calling perform_async on the job class:

WelcomeEmailJob.perform_async(current_user.id)

Code Examples

Example 1: Creating a Job

class HardWorker
  include Sidekiq::Worker

  def perform(name, count)
    # This is where the background job happens
    puts "Doing hard work: #{name} #{count}"
  end
end

This job takes two arguments: name and count. The job simply prints these arguments.

Example 2: Enqueuing a Job

HardWorker.perform_async('bob', 5)

This will enqueue a HardWorker job with the arguments 'bob' and 5. Sidekiq will run this job in the background as soon as it can.

Summary

In this tutorial, we covered installing Sidekiq, setting it up with Redis, creating a background job, and enqueuing that job.

For further study, look into advanced topics like scheduled jobs, retries, and job prioritization.

Practice Exercises

  1. Create a different background job that sends an email to the user after they have made a purchase.
  2. Create a background job that updates the user's last seen time every time they visit a page.
  3. Create a scheduled job that runs a database cleanup task every night.

Solutions can vary but should follow the same basic structure as the examples above. Remember to test your jobs thoroughly before deploying them. Happy coding!