DEV Community

Cover image for Learn Rails 8 by Building Study Flow, Part 6: Background Jobs with Active Job and Solid Queue
Shrouk Abozeid
Shrouk Abozeid

Posted on AI-assisted

Learn Rails 8 by Building Study Flow, Part 6: Background Jobs with Active Job and Solid Queue

So far, everything in Study Flow happens when you click. But a study app should also nudge you: "Don't forget to study today!" Nobody is clicking at 8am, so something has to run on its own.

That something is a background job, a piece of Ruby that runs outside the web request, in its own process. In this post we write two jobs, run them with Rails 8's built-in Solid Queue, and schedule one to repeat every day.

What you'll learn

  • Why we use background jobs
  • Active Job vs Solid Queue: who does what
  • Writing a job and enqueueing it with perform_later
  • Configuring and running Solid Queue (no Redis!)
  • Recurring jobs with config/recurring.yml
  • What happens when a job fails

Why jobs?

A web request should be quick. Sending emails, generating reports and calling slow services don't belong in the middle of it, because your user would stare at a spinner. Instead, the request says "please do this later" and returns immediately. A separate worker does the slow part.

Think of a restaurant again: the waiter (web process) writes your order on a ticket and hangs it in the kitchen (the queue). The cooks (workers) pick up tickets when they're free.

Two names to keep apart:

  • Active Job is Rails' common interface for writing jobs (perform, perform_later). It doesn't run anything by itself.
  • Solid Queue is the backend that stores the tickets and runs them. In Rails 8 it's the default, and it keeps jobs in your database. No Redis, no extra service.

Step 1: Give the queue its own database

Solid Queue's tables live in a separate database, so heavy job traffic never competes with your app's data. Look at config/database.yml in development:

development:
  primary: &primary_development
    <<: *default
    database: study_flow_development
  queue:
    <<: *primary_development
    database: study_flow_development_queue
    migrations_paths: db/queue_migrate
Enter fullscreen mode Exit fullscreen mode

and tell Rails to use Solid Queue, and where it lives, in config/environments/development.rb:

config.active_job.queue_adapter = :solid_queue
config.solid_queue.connects_to = { database: { writing: :queue } }
Enter fullscreen mode Exit fullscreen mode

Create the second database and load its tables from db/queue_schema.rb:

bin/rails db:prepare
Enter fullscreen mode Exit fullscreen mode

If you peek at the new database, you'll find tables like solid_queue_jobs, solid_queue_ready_executions and solid_queue_failed_executions. That's the queue: ordinary rows.

Step 2: Tell Solid Queue how to work

config/queue.yml sets how many workers run:

default: &default
  dispatchers:
    - polling_interval: 1
      batch_size: 500
  workers:
    - queues: "*"
      threads: 3
      processes: <%= ENV.fetch("JOB_CONCURRENCY", 1) %>
      polling_interval: 0.1
Enter fullscreen mode Exit fullscreen mode

In plain words:

  • Workers pick up jobs and run them. queues: "*" means every queue; threads: 3 means three jobs at once per process.
  • Dispatchers move jobs that were scheduled for later (for example, "in 5 minutes") into the ready list when their time comes.
  • polling_interval is how often (in seconds) they check for work.

The defaults are fine for us.

Step 3: Run a worker next to the web server

A job only runs if a worker process is alive. Our Procfile.dev now has three processes:

web: bin/rails server
css: bin/rails tailwindcss:watch
worker: bundle exec rake solid_queue:start
Enter fullscreen mode Exit fullscreen mode

bin/dev starts all three. (bin/jobs does the same as the worker line; it's the entry point Rails 8 generates.)

Step 4: Write your first job

The reminder has two parts: one job looks at which users need a reminder, and a second job does the work for one user. Splitting them keeps each job small, and a failure for one user doesn't stop the others.

# app/jobs/daily_reminder_job.rb
class DailyReminderJob < ApplicationJob
  queue_as :default

  def perform
    User.where.associated(:study_plans).distinct.find_each do |user|
      NotificationJob.perform_later("Notification::DailyReminder", user.id)
    end
  end
end
Enter fullscreen mode Exit fullscreen mode
# app/jobs/notification_job.rb
class NotificationJob < ApplicationJob
  queue_as :default

  def perform(notification_class, user_id)
    notification = notification_class.constantize.create_for_user!(user: User.find(user_id))
    UserMailer.with(notification:).notification_email.deliver_now
  end
end
Enter fullscreen mode Exit fullscreen mode

The pieces:

  • A job is a class inheriting from ApplicationJob, with a perform method.
  • queue_as :default names the queue. Different names let you prioritize some work later.
  • perform_later puts a ticket in the queue and returns immediately. perform_now runs the job right here, right now, which is handy in tests and the console.
  • find_each loads users in batches of 1,000 instead of all at once, so a million users won't fill your memory.
  • where.associated(:study_plans) keeps only users that have at least one plan, and distinct prevents a user with three plans from getting three reminders.

Pass ids, not whole objects

We enqueue user.id and look the user up inside the job. The arguments are saved in the database as JSON, so they must be simple values. Active Job can also serialize Active Record objects for you (it stores a reference and reloads the record when the job runs), but ids keep the data small, and the job always works with the current version of the record.

(notification_class.constantize turns a string like "Notification::DailyReminder" into a class. That's fine because only our own code enqueues this job. Never constantize a string that came from a user.)

Step 5: The two things the job needs

NotificationJob uses a Notification model and a mailer, and we'll explore both in Part 7. For now, add the short versions so the job runs.

bin/rails generate model Notification title:string content:text user:references
bin/rails generate mailer User notification_email
Enter fullscreen mode Exit fullscreen mode

Make title and content null: false in the migration, run bin/rails db:migrate, and add has_many :notifications, dependent: :destroy to User. Then:

# app/models/notification.rb
class Notification < ApplicationRecord
  belongs_to :user
  validates :title, :content, presence: true
end
Enter fullscreen mode Exit fullscreen mode
# app/models/notification/daily_reminder.rb
class Notification::DailyReminder < Notification
  def self.title
    "Daily Reminder"
  end

  def self.content(user:)
    return unless user&.study_plans.exists?

    <<~TEXT
      Don't forget to check your study plan today!
      You have #{user.study_plans.count} study plans
      and #{user.study_sessions.active.count} active sessions.
    TEXT
  end

  def self.create_for_user!(user:)
    create!(user:, title:, content: content(user:))
  end
end
Enter fullscreen mode Exit fullscreen mode
# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
  def notification_email
    @notification = params[:notification]
    mail(to: @notification.user.email_address, subject: @notification.title)
  end
end
Enter fullscreen mode Exit fullscreen mode
<%# app/views/user_mailer/notification_email.html.erb %>
<h1><%= @notification.title %></h1>
<p><%= @notification.content %></p>
Enter fullscreen mode Exit fullscreen mode

(Create the .text.erb twin with the same two lines of text. Mailers like to send both versions.)

Step 6: Run it

Start everything:

bin/dev
Enter fullscreen mode Exit fullscreen mode

Open a console in another terminal:

bin/rails console
Enter fullscreen mode Exit fullscreen mode
user = User.first
NotificationJob.perform_later("Notification::DailyReminder", user.id)
Enter fullscreen mode Exit fullscreen mode

Watch the terminal running bin/dev. A second later the worker prints a line like Performing NotificationJob ... Performed NotificationJob, and the email appears in the log. (In development nothing is actually delivered, and the message just shows up in log/development.log.) Check the results:

user.notifications.last.title   # => "Daily Reminder"
SolidQueue::Job.order(:id).last.finished_at   # => a timestamp, so the job is done
Enter fullscreen mode Exit fullscreen mode

Now run the dispatcher job that fans out to every user:

DailyReminderJob.perform_later
Enter fullscreen mode Exit fullscreen mode

Step 7: Watching a job fail

Our first version of DailyReminderJob looped over User.find_each, with no filter. Try it for yourself and see what happens. Create a user with no study plans, then run the loop without the where.associated line:

User.create!(email_address: "empty@example.com", password: "secret123")
NotificationJob.perform_later("Notification::DailyReminder", User.last.id)
Enter fullscreen mode Exit fullscreen mode

content returns nil for a user with no plans, create! raises ActiveRecord::RecordInvalid, and the job fails. Solid Queue doesn't lose it. It records it:

SolidQueue::FailedExecution.last.error
# => the exception class, message and backtrace
Enter fullscreen mode Exit fullscreen mode

Three things to know:

  • A failed job doesn't crash your app, because it's isolated in the worker.
  • Jobs are not retried unless you ask. In ApplicationJob you can declare how to react:
  retry_on ActiveRecord::Deadlocked, wait: 5.seconds, attempts: 3
  discard_on ActiveJob::DeserializationError   # the record was deleted, so give up quietly
Enter fullscreen mode Exit fullscreen mode
  • The best fix is usually to prevent the bad case, which is why the final DailyReminderJob only selects users with plans. The jobs should also be safe to run twice, since retries and double-clicks happen.

Step 8: Make it repeat: recurring jobs

We don't want to type DailyReminderJob.perform_later every morning. Solid Queue has a scheduler built in, configured in config/recurring.yml:

development:
  daily_reminder:
    class: DailyReminderJob
    schedule: every day at 8am
Enter fullscreen mode Exit fullscreen mode

Each entry has a name, the job class, and a human-friendly schedule. Other valid schedules:

schedule: every hour
schedule: every 5 minutes
schedule: at 5am every day
schedule: every hour at minute 12
Enter fullscreen mode Exit fullscreen mode

Entries can also run a Ruby line with command: instead of a class, and pass args: and queue:. The scheduler process starts together with the workers, so no extra setup is needed.

Be careful with one thing: "8am" is the server's time zone, not each user's. That's fine for now. In Part 10 we'll let every user choose their own time.

To see it work today without waiting until tomorrow, temporarily change the schedule to every minute, restart bin/dev, and watch the reminders arrive.

✅ How to test this

Manual checks:

  1. With bin/dev running, enqueue a job in the console and confirm finished_at gets filled.
  2. Stop the worker (comment out the worker: line, or stop it), enqueue a job, and look: it waits in the queue as a row. Start the worker and it runs. This shows the queue works as a buffer.
  3. Temporarily set the schedule to every minute and watch the log.

Automated tests. Jobs are easy to test because Rails swaps in a fake in-memory queue (ActiveJob::TestCase).

test/jobs/daily_reminder_job_test.rb:

require "test_helper"

class DailyReminderJobTest < ActiveJob::TestCase
  test "enqueues a notification only for users that have study plans" do
    with_plan = User.create!(email_address: "a@example.com", password: "secret123")
    with_plan.study_plans.create!(name: "Learn SQL")
    User.create!(email_address: "b@example.com", password: "secret123")

    assert_enqueued_jobs 1, only: NotificationJob do
      DailyReminderJob.perform_now
    end

    assert_enqueued_with(job: NotificationJob, args: [ "Notification::DailyReminder", with_plan.id ])
  end

  test "enqueues one reminder even with several plans" do
    user = User.create!(email_address: "a@example.com", password: "secret123")
    user.study_plans.create!(name: "One")
    user.study_plans.create!(name: "Two")

    assert_enqueued_jobs 1, only: NotificationJob do
      DailyReminderJob.perform_now
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

test/jobs/notification_job_test.rb:

require "test_helper"

class NotificationJobTest < ActiveJob::TestCase
  setup do
    @user = User.create!(email_address: "me@example.com", password: "secret123")
    @user.study_plans.create!(name: "Learn SQL")
  end

  test "creates a notification and delivers its email" do
    assert_difference -> { @user.notifications.count }, 1 do
      assert_difference -> { ActionMailer::Base.deliveries.size }, 1 do
        NotificationJob.perform_now("Notification::DailyReminder", @user.id)
      end
    end

    assert_equal "Daily Reminder", @user.notifications.last.title
    assert_equal [ "me@example.com" ], ActionMailer::Base.deliveries.last.to
  end

  test "fails for a user with nothing to remind about" do
    empty = User.create!(email_address: "empty@example.com", password: "secret123")

    assert_raises(ActiveRecord::RecordInvalid) do
      NotificationJob.perform_now("Notification::DailyReminder", empty.id)
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

And a small guard that the schedule points at a real job:

# test/jobs/recurring_jobs_configuration_test.rb
require "test_helper"
require "yaml"

class RecurringJobsConfigurationTest < ActiveSupport::TestCase
  test "the daily reminder is scheduled in development" do
    task = YAML.safe_load_file(Rails.root.join("config/recurring.yml")).dig("development", "daily_reminder")

    assert_equal "every day at 8am", task["schedule"]
    assert task["class"].constantize < ApplicationJob
  end
end
Enter fullscreen mode Exit fullscreen mode
bin/rails test
Enter fullscreen mode Exit fullscreen mode

In tests, perform_later does not run anything: the job lands in a test queue that you inspect with assert_enqueued_with. When you want it to run, call perform_now, or wrap the code in perform_enqueued_jobs do ... end.

Common mistakes

  • "I enqueued it and nothing happens." No worker is running. Is the worker: line in Procfile.dev, and did you start with bin/dev, not bin/rails server?
  • PG::UndefinedTable: solid_queue_jobs. You skipped bin/rails db:prepare, so the queue database has no tables.
  • Passing objects that can't be serialized. Stick to ids, strings, numbers, booleans, hashes and arrays of those.
  • Changing a job's arguments with jobs still waiting. Old tickets keep their old arguments, so a renamed argument breaks them. Deploy argument changes carefully.
  • Doing everything in one big job. If it fails halfway, you can't tell what was done. Fan out to small jobs, as we did.
  • Forgetting recurring.yml has one section per environment. An entry under production: doesn't run in development.

Recap

  • Background jobs move slow or scheduled work out of the request.
  • Active Job is the interface (perform, perform_later); Solid Queue is the backend that stores and runs jobs in your database.
  • bin/dev starts a worker through Procfile.dev; config/queue.yml controls its size.
  • config/recurring.yml schedules jobs with plain-English schedules.
  • Failed jobs are recorded, not retried by default. Prevent bad cases and use retry_on / discard_on on purpose.

Next up

The job already creates notifications and sends mail, but we rushed through both. In Part 7 we'll slow down: how mailers work, how to show notifications in the app with an unread counter, and how to add custom member and collection routes for "mark as read".

Top comments (0)