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
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 } }
Create the second database and load its tables from db/queue_schema.rb:
bin/rails db:prepare
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
In plain words:
-
Workers pick up jobs and run them.
queues: "*"means every queue;threads: 3means 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_intervalis 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
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
# 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
The pieces:
- A job is a class inheriting from
ApplicationJob, with aperformmethod. -
queue_as :defaultnames the queue. Different names let you prioritize some work later. -
perform_laterputs a ticket in the queue and returns immediately.perform_nowruns the job right here, right now, which is handy in tests and the console. -
find_eachloads 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, anddistinctprevents 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
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
# 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
# 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
<%# app/views/user_mailer/notification_email.html.erb %>
<h1><%= @notification.title %></h1>
<p><%= @notification.content %></p>
(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
Open a console in another terminal:
bin/rails console
user = User.first
NotificationJob.perform_later("Notification::DailyReminder", user.id)
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
Now run the dispatcher job that fans out to every user:
DailyReminderJob.perform_later
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)
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
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
ApplicationJobyou 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
- The best fix is usually to prevent the bad case, which is why the final
DailyReminderJobonly 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
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
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:
- With
bin/devrunning, enqueue a job in the console and confirmfinished_atgets filled. - 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. - Temporarily set the schedule to
every minuteand 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
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
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
bin/rails test
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 inProcfile.dev, and did you start withbin/dev, notbin/rails server? -
PG::UndefinedTable: solid_queue_jobs. You skippedbin/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.ymlhas one section per environment. An entry underproduction: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/devstarts a worker throughProcfile.dev;config/queue.ymlcontrols its size. -
config/recurring.ymlschedules jobs with plain-English schedules. - Failed jobs are recorded, not retried by default. Prevent bad cases and use
retry_on/discard_onon 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)