Background jobs, email and files in Rails, without things breaking
TL;DR
Difficulty: Intermediate
Move anything slow or anything that calls another company's server out of the request and into a background job.
- Let the database remember what must happen, and let the queue only make it happen sooner. A column such as ready_emailed_at plus a small sweep catches every lost job.
- Ask three questions of every job: could it run twice, could it run for nothing, could it never run.
- Where the queue lives matters: a queue in your own database rolls back with your data, a Redis queue needs enqueue after commit.
- Size retries by how long the result stays useful, use queues rather than priority numbers, and keep files in a private bucket behind your own login with links that expire.
A mechanic taps "ready" and the customer should get an email and a text. It sounds like one line of code, and it is where Rails applications most often break quietly. Here is how to do background jobs, email and file uploads properly in Rails 7.1, built on one bicycle workshop chain's real needs.
The question behind this article
A mechanic at Cogwell Cycles in Sheffield finishes a repair, taps "ready" on the workshop board, and the customer should get an email and a text message saying the bike can be collected. It sounds like one line of code. It is three or four places where things quietly go wrong: the email provider is slow, so the mechanic's screen hangs. The message goes out twice. The message goes out for a job card that was never actually saved. Or it never goes out at all, and nobody notices until the customer rings.
This article is about the slow, the foreign and the heavy work in a Rails application: sending email and text messages, storing photos, and running reports at night. It is the fifth chapter of the Rails series and builds on the models from Active Record done well and the live workshop board from Hotwire in Rails. Everything here is written for Rails 7.1 and Ruby 3.3, as they stand in February 2024.
The example is invented, as always. Cogwell Cycles (cogwellcycles.example) runs six workshops with 38 mechanics and about 1,150 repair bookings a week. Hannah founded it. Priya and Owen are building its application, and they chose Rails after building a two week spike in both frameworks, as the decision chapter tells.
The one rule: let the database remember, let the queue hurry
Here is the idea I would put above everything else in this chapter, because the rest follows from it.
A background job is a promise that some work will happen later. The usual advice treats the queue as the place where that promise lives. I think that is the wrong way round. The queue is a fast messenger, and messengers get lost. The database is where your business facts live, and it has transactions, backups and constraints. So:
- the database records what must happen (this job card is ready, and its customer has not been told yet)
- the queue only makes it happen sooner
- a small, boring sweep checks now and then that every recorded promise was kept.
If the queue loses a job, the sweep finds the promise in the database and sends it again. If the job runs twice, the database record says the work is done and the second run does nothing. If the transaction that marked the card ready is rolled back, there is no record, so there is nothing to send. One column in the right table answers most of the failure modes that whole blog posts are written about.
This is not a new invention. It is the same reasoning as the "transactionally staged job drain" Brandur Leach described for Postgres in 20171, shrunk down to the size of a small business application. What I add is the rule of thumb: whenever you write perform_later, ask which column in your own database proves the work was done. If there is no such column, you are trusting the messenger with the letter and the address book at once.
Example: the ready message, written down before it is sent
Priya adds two columns to the job cards table:
# db/migrate/20240227090000_add_ready_notifications_to_job_cards.rb
class AddReadyNotificationsToJobCards < ActiveRecord::Migration[7.1]
def change
add_column :job_cards, :ready_at, :datetime # when the card moved to "ready"
add_column :job_cards, :ready_emailed_at, :datetime # when the customer got the email
add_column :job_cards, :ready_texted_at, :datetime # when the customer got the text
add_index :job_cards, :ready_at
end
end
Now the business fact "Mrs Ellis has not yet been told her bike is ready" is a row where ready_at is set and ready_emailed_at is empty. That fact survives a crashed worker, a restarted Redis server and a deploy at the wrong moment. The rest of this chapter is about sending the message quickly and safely. The columns are about never forgetting it.
Nothing slow and nothing foreign inside the request
A web request is the moment between a person pressing a button and the page answering. Rails handles it on a web server process such as Puma, which has a fixed number of threads. Every second a thread spends waiting is a second it cannot serve anyone else.
My rule of thumb for what leaves the request: another company's server never sits inside your request. Sending an email over the Simple Mail Transfer Protocol (SMTP), calling a text message provider's API, uploading a file to a storage bucket, resizing an image: each of these waits on a network or a processor you do not control. Their speed on a good day tells you nothing about their speed on a bad one. Put them in a job, and the request only has to write a row and answer.
The second test is "does the person need the result right now to carry on?". A booking confirmation page needs the booking to exist. It does not need the confirmation email to have arrived.
Example: what the mechanic waits for
Owen times the "ready" button in development against the real providers' sandboxes. The numbers below are illustrative, made up for this example to show the shape of the difference, not measurements of any provider. Rendering the board update takes about 80 milliseconds. Sending the email over SMTP inline adds about 900 milliseconds on a normal day. Calling the text message API inline adds about 600 more.
On a Saturday morning, when 30% of the week's online bookings arrive between Friday 6pm and Saturday noon, the difference is not comfort. A provider having a slow hour would hold Puma threads hostage across all six workshops. With jobs, a slow provider means a message arrives a minute late, and the board keeps moving.
Three questions every job must answer
Brandur's essay names the three ways a job goes wrong when the queue and the database are separate systems1. I turn them into three questions to ask of every job before it ships:
- Could it run twice? Almost every backend promises "at least once", not "exactly once". Sidekiq's own wiki says it plainly and asks for jobs that are idempotent, which means safe to run more than once2.
- Could it run too early, or for nothing? If the job is enqueued inside a database transaction and the queue lives elsewhere, a worker can pick it up before the transaction commits (the record is not visible yet), or after it rolls back (the record never existed).
- Could it never run? If the job is enqueued after the commit and the process dies in between, the data is saved and the work is lost.
No single setting answers all three. Idempotency answers the first. Where and when you enqueue answers the second. The database column and a sweep answer the third.
Example: three ways Hannah hears about the ready message
- Twice. A worker sends the text message, then the server restarts during a deploy before the job is marked finished. The backend runs the job again. Mrs Ellis gets two texts. Mildly odd, harmless, and Hannah hears nothing.
- For nothing. Owen's first version enqueues the job inside the same transaction that saves the status. A validation fails on the invoice line, the transaction rolls back, but the job is already in Redis. Mrs Ellis is told her bike is ready. It is not. She drives across Sheffield. Hannah hears about this one.
- Never. The status is saved, the web process is killed by a memory limit before the enqueue call runs, and no message is sent. The bike sits in the "ready" column for two days. Hannah hears about this one too, later, and less politely.
The second and third are the expensive ones, and they are the ones the rule above (the database remembers) is built for.
Active Job: one interface, several engines
Active Job is the part of Rails that defines what a job looks like, independent of the system that runs it. The Rails Guides describe it as a common interface with built in adapters for several queuing backends, including Sidekiq, Resque and Delayed Job3. You write a class with a perform method, call perform_later, and the configured adapter stores and runs it.
The key pieces, all from the Rails 7.1 Guides and API:
perform_later(args)puts the job in the queue, andperform_nowruns it straight away in the current process3.set(wait: 10.minutes)orset(wait_until: time)schedules it for later3.queue_as :namepicks the queue3.- Arguments that are Active Record objects are passed as GlobalID references, so the worker loads a fresh copy of the record from the database instead of a stale snapshot3.
retry_onanddiscard_ondecide what happens when an error is raised4.- Rails 7.1 added
perform_all_laterto enqueue many jobs in one call, and anafter_discardcallback that runs when a job is about to be given up on5.
One default matters more than the others. Out of the box, Rails uses the :async adapter, which runs jobs in a thread pool inside the web process6. The Guides warn that jobs in that backend are lost on restart, and that most production applications need a persistent backend3. It is fine on a laptop. It is not a queue.
Example: Cogwell's first job
Owen generates a job with bin/rails generate job ready_email, and Rails creates the class and its test. This is the first, deliberately naive version. It works, and the next sections will show what it is missing.
# app/jobs/ready_email_job.rb
class ReadyEmailJob < ApplicationJob
queue_as :customer_messages
def perform(job_card)
# job_card arrives as a GlobalID and is loaded fresh from the database here
ReadyMailer.with(job_card: job_card).bike_ready.deliver_now
end
end
# somewhere in a controller, naive version
ReadyEmailJob.perform_later(@job_card)
Two details are already right. The job receives the record, not a hash of its attributes, so it reads the current state when it runs. And it calls deliver_now inside the job: the job itself is the background part, so there is no point queueing a second job from inside the first.
Choosing a backend in February 2024
Active Job is the interface. The backend is the engine that stores jobs and runs workers. In February 2024 these are the realistic choices for a new Rails application. Versions are those published on RubyGems at the date.
| Backend | Where jobs live | Latest at the date | What it is good at | What to watch |
|---|---|---|---|---|
| Sidekiq | Redis | 7.2.2 (16 February 2024)7 | Long established and widely used, very high throughput with threads, a mature web dashboard, paid Pro and Enterprise tiers add features | Enqueue is not part of your database transaction, the free version can lose a job that is running when the process crashes8 |
| GoodJob | PostgreSQL | 3.25.0 (22 February 2024)9 | No extra infrastructure if you already run PostgreSQL, built in cron style recurring jobs and a dashboard10 | Lower ceiling than Redis at very high volume, PostgreSQL only |
| Delayed Job | Your SQL database | 4.1.11 (September 2022)11 | Old, simple, well understood | Slow release cadence, polling based |
| Resque | Redis | 2.6.0 (August 2023)12 | Process per job isolation, long history | Forks a process per job, so heavier per job than threaded backends |
| Solid Queue | Your SQL database | 0.2.x, first public versions from December 202313 | New database backed backend from 37signals, published under the Rails organisation | Very young, not a Rails default, I would wait for it to settle before putting customer messages on it |
The Rails API keeps a table of what each adapter supports. For example, it lists Sidekiq's priorities as set per queue, Delayed Job's as set per job, and the built in async adapter's as not supported at all6.
The most useful column is the second one, and it is rarely discussed. Where your jobs live decides whether a job can see a rollback. If jobs are rows in the same PostgreSQL database as your job cards, as with GoodJob or Delayed Job on the same connection, then inserting a job inside a transaction is part of that transaction. A rollback removes the job with the data, and a commit makes both visible together. The "for nothing" and "too early" failures cannot happen. If jobs live in Redis, the enqueue happens immediately and outside your transaction, so you need to enqueue after the commit, and you need the database column and sweep for the "never" case.
Neither is wrong. Sidekiq has the higher ceiling and the longer track record. GoodJob trades some throughput for one fewer moving part.
Example: what Priya and Owen choose, and why
Cogwell's numbers make throughput a non question. Owen estimates the peak hour on a Saturday. Each repair produces about 15 jobs: one confirmation email, one ready email, one ready text, four photo analyses and eight preprocessed image variants (four photos, two variants each). The weekly job count is repairs times jobs per repair (Foundations: ratios and rates):
Here is the number of jobs a week, 1,150 the repairs a week and 15 the jobs per repair. Spread over roughly 60 opening hours, that is about 288 jobs an hour on average. Owen assumes the busiest hour carries three times the average, about 863 jobs. How busy does that make one worker process with five threads? The share of time the workers are busy, the utilisation, is the arrival rate times the average job time, divided by the number of workers (Foundations: ratios and rates):
Here is the utilisation between 0 and 1, the number of jobs arriving per second, the average seconds one job takes, and the number of jobs that can run at once. With jobs per second, an assumed second (image work dominates), and threads:
So : the workers are busy about 5% of the busiest hour. Cogwell does not have a capacity problem. It has a correctness problem: a handful of jobs that must never go out for nothing and never go missing.
That decides it. The application already runs PostgreSQL. GoodJob keeps jobs in the same database, so enqueueing inside a transaction is safe, cron style scheduling is included, and Hannah has one database to back up instead of two. If the live board from the Hotwire chapter had already brought Redis in for Action Cable, Sidekiq would cost nothing extra to run and would be an equally sound choice, with the after commit pattern below. That is a team's judgement call, not a verdict on either tool.
The setup is short:
# Gemfile
gem "good_job", "~> 3.25"
bundle install
bin/rails g good_job:install # creates the migration for the jobs tables
bin/rails db:migrate
# config/application.rb
config.active_job.queue_adapter = :good_job
# config/environments/production.rb
config.good_job.execution_mode = :external # a separate worker process runs the jobs
# the worker process, started next to the web process in production
bundle exec good_job start --queues="customer_messages:2;default:2;reports:1"
That --queues value gives two threads to customer messages, two to everything in the default queue and one to reports, using GoodJob's own syntax for queue pools10.
Enqueue after the commit, or inside it, but know which
A transaction groups several database writes so they all succeed or all fail. The Rails API documents after_commit callbacks as the place to talk to other systems, because they run only once the database is in a permanent state14. after_create_commit is the same, limited to creation14.
There are two safe patterns, and the backend decides which:
- Redis backed queue (Sidekiq, Resque): enqueue in
after_commit, never inside the transaction. Then add the sweep, because a crash between commit and enqueue loses the job. - Queue in the same database (GoodJob, Delayed Job): you may enqueue inside the transaction, and the job commits or rolls back with the data.
Rails 7.1 does not choose for you. It enqueues the moment you call perform_later, whatever transaction is open.
The pattern I prefer for application code is the one that is safe on both: mark the fact in the database inside the transaction, enqueue after commit, and let a sweep catch what was dropped. If the team later swaps GoodJob for Sidekiq, nothing silently breaks.
Example: marking a job card ready
# app/models/job_card.rb
class JobCard < ApplicationRecord
belongs_to :booking
has_one :customer, through: :booking
enum :status, { waiting: 0, in_repair: 1, ready: 2, collected: 3 }
# Runs only after the transaction that changed the status has committed.
after_update_commit :notify_customer_ready, if: :just_became_ready?
def mark_ready!
transaction do
update!(status: :ready, ready_at: Time.current)
booking.invoice&.finalise! # may raise, and then everything rolls back
end
end
private
def just_became_ready?
saved_change_to_status? && ready?
end
def notify_customer_ready
ReadyEmailJob.perform_later(self)
ReadyTextJob.perform_later(self)
end
end
If finalise! raises, the transaction rolls back, ready_at is never saved, the callback never fires, and Mrs Ellis is not sent across Sheffield for a bike that is not ready. If the transaction commits and the process dies before notify_customer_ready runs, the row still says "ready, not yet emailed", and the sweep below sends it.
Notice saved_change_to_status?. Inside an after_commit callback, saved_change_to_attribute? tells you what the last save changed. Without that guard, every later update of a ready card (a note, a price) would send the message again.
Example: the sweep that keeps the promise
# app/jobs/ready_notification_sweep_job.rb
class ReadyNotificationSweepJob < ApplicationJob
queue_as :default
# Anything ready for more than 10 minutes and still not told is a dropped job.
def perform
JobCard.ready
.where(ready_at: ..10.minutes.ago)
.where("ready_emailed_at IS NULL OR ready_texted_at IS NULL")
.find_each do |card|
ReadyEmailJob.perform_later(card) if card.ready_emailed_at.nil?
ReadyTextJob.perform_later(card) if card.ready_texted_at.nil?
end
end
end
It runs every 15 minutes (the schedule comes later in this chapter). On a normal day it finds nothing, which is the point. It can enqueue a job that is already waiting in the queue, so the jobs themselves must be safe to run twice. That is the next section.
Idempotent jobs: running twice must be harmless
An idempotent operation gives the same result however many times you run it. Setting a status to "ready" is idempotent. Sending a text message is not: every call sends another one.
There is no way to make "send a text message" exactly once across two systems you do not jointly control. The provider may accept the message and the network may drop its answer. Your job cannot tell "sent" from "not sent" in that moment. So you choose, per message, which failure you would rather have:
- at least once: retry when unsure, accept a rare duplicate
- at most once: never retry when unsure, accept a rare missing message.
For "your bike is ready", a duplicate costs a raised eyebrow and a missing message costs a customer who waits for days. At least once is the right side. For a payment or a refund, it would be the opposite, and you would need the provider's own idempotency support.
Within at least once, the job must still avoid the common duplicate: two copies of the same job running at the same moment (the sweep and the original), or a job that runs again after it had fully finished. The pattern is check, lock, send, record.
Example: the ready text, safe to run twice
# app/jobs/ready_text_job.rb
class ReadyTextJob < ApplicationJob
queue_as :customer_messages
# The message is only useful while the customer has not yet collected the bike.
retry_on Twilio::REST::RestError, wait: :polynomially_longer, attempts: 7
def perform(job_card)
job_card.with_lock do # SELECT ... FOR UPDATE on this one row
next if job_card.ready_texted_at # already sent: a second run does nothing
next unless job_card.ready? # collected or reopened since: do not send
SmsGateway.deliver(
to: job_card.customer.mobile,
body: "Hi #{job_card.customer.first_name}, your bike is ready at " \
"Cogwell Cycles #{job_card.booking.workshop.name}. See you soon."
)
job_card.update!(ready_texted_at: Time.current)
end
end
end
Step by step:
with_lockopens a transaction, reloads the row and locks it until the block ends. A second copy of this job for the same card waits at this line. Inside the block,nextleaves the block normally, so the transaction simply ends.- When the first copy finishes, the second copy gets the lock, sees
ready_texted_atis set, and returns. No duplicate. - If the card was collected before the job ran (a queue backlog, a long retry),
ready?is false and nothing is sent. - The only remaining duplicate is a crash after the provider accepted the message and before
update!committed. That is the at least once trade, chosen on purpose.
The lock is held while the provider's API answers, usually well under a second, on one row. For a table of job cards that is fine. For a hot row everyone writes to, I would claim the work with a conditional update instead and release the claim on failure.
The text goes through a small wrapper, so the provider is replaceable and tests can swap it out. Twilio is used here because its Ruby library is widely used. The call is the one in its README15.
# app/models/sms_gateway.rb
class SmsGateway
def self.deliver(to:, body:)
client.messages.create(from: credentials[:from], to: to, body: body)
end
def self.client
@client ||= Twilio::REST::Client.new(credentials[:account_sid], credentials[:auth_token])
end
def self.credentials
Rails.application.credentials.fetch(:twilio)
end
end
Phone numbers arrive in every shape. Rails 7.1's normalizes5 cleans them once, on the way in:
# app/models/customer.rb
class Customer < ApplicationRecord
# "07700 900123" becomes "+447700900123", the international form SMS providers expect
normalizes :mobile, with: ->(number) {
digits = number.gsub(/[^\d+]/, "")
digits.start_with?("0") ? "+44#{digits[1..]}" : digits
}
end
This simple version only knows UK numbers. If Cogwell ever takes bookings from abroad, a phone number library such as the phonelib gem is the better tool.
Retries and discard: size them by the message's shelf life
When perform raises an error, Active Job by default does not retry. You opt in per error class3:
retry_on SomeError, wait:, attempts:catches the error and enqueues the job again after a wait. The defaults are a 3 second wait and 5 attempts4. When the attempts run out, the API documentation says the error is allowed to bubble up to the backend, which may have its own retry mechanism or keep the job for inspection4.discard_on SomeErrordrops the job without retrying. The API documentation names the typical case: the record the job was about no longer exists4.wait: :polynomially_longerwaits longer after each failure. Rails 7.1 renamed it from:exponentially_longer, which still works but is deprecated16.
That last point about bubbling up deserves care. Sidekiq retries a failed job 25 times by default, spread over about three weeks17. If you write retry_on with 5 attempts and run on Sidekiq, a stubborn error gets 5 Active Job attempts and then 25 Sidekiq attempts on top. GoodJob, by contrast, does not retry unhandled errors by default and recommends declaring retries with retry_on in your job classes10. Same code, different behaviour. Decide on one layer and switch the other off.
How long do the retries take? The Rails 7.1 source computes the polynomial wait from the number of executions so far18. Ignoring the random jitter, the wait before retry number is seconds, and the total time from the first failure to the last attempt is
Here is the total waiting time in seconds, the number of attempts set with attempts:, and counts the retries, from the first () to the last (). Jitter, set to 15% in the current Rails defaults19, can add up to that share on top of each wait. The sum is ordinary addition of a growing series. The rate thinking behind it is in Foundations: ratios and rates.
Example: how many attempts for the ready text?
With the default of 5 attempts:
Each bracket is one retry, to , and is their total. The Rails documentation gives the same first steps, about 3, 18 and 83 seconds4. Six minutes covers a provider's brief hiccup and not much more. The addition is the same rate arithmetic as in Foundations: ratios and rates.
With 10 attempts the last one comes about four and a quarter hours later:
Here the nine retries run from to , and the fourth powers alone add up to 15,333 seconds (Foundations: ratios and rates).
A "your bike is ready" text that arrives four hours late, after the customer has rung the workshop, is worse than useless. So Priya sizes the retries by the shelf life of the message. Most customers collect the same day, so she wants the last attempt within roughly the first 40 minutes:
The six retries, to , wait 38 minutes in total, inside the shelf life (Foundations: ratios and rates). Seven attempts it is. That is the attempts: 7 in ReadyTextJob above. The nightly reorder report has a shelf life of a working morning, so it can afford 10. The rule of thumb: work out how late the result is still useful, then pick the number of attempts whose total wait fits inside it.
Cogwell's base class sets the shared rules:
# app/jobs/application_job.rb
class ApplicationJob < ActiveJob::Base
# A record deleted before the job ran: nothing left to do.
discard_on ActiveJob::DeserializationError
# Deadlocks are transient: try again shortly.
retry_on ActiveRecord::Deadlocked, wait: 5.seconds, attempts: 3
# Anything given up on must be visible, never silent.
after_discard do |job, error|
Rails.logger.error("Job given up: #{job.class.name} #{job.job_id}: #{error.class}: #{error.message}")
end
end
The first two lines are the ones Rails 7.1 puts, commented out, into a new application's ApplicationJob. Turning them on is a decision, not a default, so make it deliberately. The after_discard hook is new in Rails 7.15. In production it would report to your error monitoring service as well as the log.
Queues and priorities: use queues, not numbers
A queue is a named line of jobs. A priority is a number that reorders jobs within a line. The trouble with priorities is that the number means different things in different backends: some adapters support them per job, some only per queue, some not at all6, and even the direction varies. In GoodJob 3, a higher number runs first, and the README announces that version 4 will flip that so a smaller number runs first10. A number that silently changes meaning on an upgrade is not something I want customer messages to depend on.
Queues are explicit and portable. Every backend in the table supports them. You give each queue its own workers, and a slow report can never stand in front of a customer's text.
Example: Cogwell's three queues
| Queue | What goes in it | Threads | Why |
|---|---|---|---|
customer_messages | ready email, ready text, booking confirmation | 2 | A customer is waiting, must never queue behind anything slow |
default | photo analysis and variants, the sweep | 2 | Useful soon, not urgent |
reports | nightly reorder report, weekly figures | 1 | Can take minutes, nobody is waiting at 2am |
The --queues flag of the worker in the GoodJob setup above is this table written as one line. Photo analysis and purging run as Active Storage's own jobs, which go to the default queue unless config.active_storage.queues says otherwise. Owen sets them explicitly so nobody has to guess.
Scheduled and recurring work
Two kinds of "later" are easy to confuse:
- Scheduled once: send a reminder the evening before a booking. That is
set(wait_until:)on a normal job3. - Recurring: run the reorder report every night. Active Job in Rails 7.1 has no scheduler of its own. Each backend family has its answer: GoodJob has cron style jobs built in10. Sidekiq has periodic jobs in its paid Enterprise version, and there are community gems such as sidekiq cron. And a plain Unix cron entry calling a Rake task, often written with the whenever gem, works with anything.
A recurring job has its own failure modes. It can run twice (two worker processes both have the scheduler switched on) or not at all (the server was down at 2am). The fix is the same rule as before: give every run a date key in the database, and make the job do nothing if that date is already done.
Example: the nightly reorder report
Cogwell keeps 2,400 spare parts in stock. Every night the managers want a list of parts at or below their reorder level, with suggested quantities. The parts table from Active Record done well has sku, name, stock_on_hand and reorder_level. It has no column for an order quantity, and this report does not need one: the suggestion is computed as whatever brings the stock back up to twice the reorder level, a simple rule Hannah can change later.
First, a record that remembers each night's report, with a unique index on the date:
# db/migrate/20240227091000_create_reorder_reports.rb
class CreateReorderReports < ActiveRecord::Migration[7.1]
def change
create_table :reorder_reports do |t|
t.date :report_date, null: false
t.integer :line_count, null: false, default: 0
t.datetime :sent_at
t.timestamps
end
add_index :reorder_reports, :report_date, unique: true
end
end
# app/models/reorder_report.rb
class ReorderReport < ApplicationRecord
has_one_attached :csv
end
Then the job:
# app/jobs/reorder_report_job.rb
require "csv"
class ReorderReportJob < ApplicationJob
queue_as :reports
retry_on StandardError, wait: :polynomially_longer, attempts: 10
def perform(date = Date.current)
report = ReorderReport.find_or_create_by!(report_date: date)
return if report.sent_at # this night is already done: a second run does nothing
parts = Part.where("stock_on_hand <= reorder_level").order(:sku)
csv = CSV.generate do |rows|
rows << %w[sku name in_stock reorder_level suggested_order]
parts.find_each do |part|
suggested = (2 * part.reorder_level) - part.stock_on_hand # back up to twice the reorder level
rows << [part.sku, part.name, part.stock_on_hand, part.reorder_level, suggested]
end
end
report.csv.attach(io: StringIO.new(csv), filename: "reorder-#{date.iso8601}.csv", content_type: "text/csv")
report.update!(line_count: parts.count)
ManagerMailer.with(report: report).reorder_report.deliver_now
report.update!(sent_at: Time.current)
end
end
The unique index is what makes find_or_create_by! safe if two copies race. One insert wins, the other raises ActiveRecord::RecordNotUnique, and the retry finds the existing row. find_each loads the parts in batches of 1,000 rather than all at once, as the Active Record chapter explains. And sent_at is the date key's partner: a run that crashes after building the file but before emailing will try again, and a run after success will stop at the second line.
The schedule lives in the GoodJob configuration:
# config/initializers/good_job.rb
Rails.application.configure do
config.good_job.enable_cron = true
config.good_job.cron = {
reorder_report: {
cron: "0 2 * * *", # every night at 2am, server time
class: "ReorderReportJob",
description: "Parts at or below reorder level, emailed to managers"
},
ready_sweep: {
cron: "*/15 * * * *", # every 15 minutes
class: "ReadyNotificationSweepJob",
description: "Resend any ready message that was dropped"
}
}
end
The servers run on Coordinated Universal Time (UTC), so the report runs at 2am in winter and 3am in British Summer Time. For a nightly report that is fine. For something that must run at a local hour, schedule it in the application's time zone deliberately rather than by accident.
Action Mailer: emails as code you can see
Action Mailer is the Rails framework for email. A mailer is a class much like a controller: each method is one kind of email, it sets instance variables and calls mail, and views in app/views/<mailer>/ render the body20. If you provide both an .html.erb and a .text.erb template, Rails sends a "multipart/alternative" email with both versions automatically20. Always send both: some people read plain text, and spam filters notice a message with no text part.
The parts of the Rails 7.1 Guide that matter most in practice20:
deliver_laterhands the email to Active Job, usingActionMailer::MailDeliveryJob. The queue it lands in is set bydeliver_later_queue_name, which defaults to your normal default queue.deliver_nowsends it in the current process.- Mailers have no request, so links need a host: set
config.action_mailer.default_url_options = { host: "cogwellcycles.example" }and use*_urlhelpers, not*_path. - Previews live in
test/mailers/previews/and are shown in development at/rails/mailers. - In tests, the
:testdelivery method collects emails inActionMailer::Base.deliveriesinstead of sending them. Rails 7.1 addedcapture_emailsanddeliver_enqueued_emailstest helpers5.
Example: the ready email and its preview
# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
default from: "Cogwell Cycles <workshop@cogwellcycles.example>"
layout "mailer"
end
# app/mailers/ready_mailer.rb
class ReadyMailer < ApplicationMailer
def bike_ready
@job_card = params[:job_card]
@customer = @job_card.customer
@workshop = @job_card.booking.workshop
mail(to: @customer.email, subject: "Your bike is ready to collect from #{@workshop.name}")
end
end
<%# app/views/ready_mailer/bike_ready.text.erb %>
Hi <%= @customer.first_name %>,
Your bike is ready to collect from Cogwell Cycles <%= @workshop.name %>.
Opening hours and directions: <%= workshop_url(@workshop) %>
See you soon,
<%= @workshop.name %> workshop
The HTML template says the same thing with the same link. Then the job that sends it, with the same check, lock, send, record pattern as the text:
# app/jobs/ready_email_job.rb
class ReadyEmailJob < ApplicationJob
queue_as :customer_messages
retry_on Net::OpenTimeout, Net::ReadTimeout, Net::SMTPServerBusy,
wait: :polynomially_longer, attempts: 7
def perform(job_card)
job_card.with_lock do
next if job_card.ready_emailed_at
next unless job_card.ready?
ReadyMailer.with(job_card: job_card).bike_ready.deliver_now
job_card.update!(ready_emailed_at: Time.current)
end
end
end
And the preview, so Hannah can read the email in a browser before a single customer does:
# test/mailers/previews/ready_mailer_preview.rb
class ReadyMailerPreview < ActionMailer::Preview
def bike_ready
ReadyMailer.with(job_card: JobCard.ready.first).bike_ready
end
end
Opening http://localhost:3000/rails/mailers/ready_mailer/bike_ready shows the HTML and text versions side by side. Previews are the lowest effort review step in Rails: the person who owns the wording reads the real email, not a screenshot in a ticket.
A test pins the behaviour that matters, that running the job twice sends once:
# test/jobs/ready_email_job_test.rb
require "test_helper"
class ReadyEmailJobTest < ActiveJob::TestCase
include ActionMailer::TestHelper
test "sends the ready email once, however often the job runs" do
card = job_cards(:ellis_ready) # a fixture with status ready, ready_emailed_at nil
assert_emails 1 do
ReadyEmailJob.perform_now(card)
ReadyEmailJob.perform_now(card)
end
assert card.reload.ready_emailed_at
end
end
Writing that test first, before the job, is how I work. The testing series later in this programme goes into the workflow in depth.
Sending email that arrives
Rails builds the email. Something else has to deliver it, and deliverability, whether it lands in the inbox rather than spam, is mostly decided outside your code.
- Use a transactional email provider. Postmark, Amazon Simple Email Service (SES), Mailgun and SendGrid all accept mail over SMTP or an HTTP API, and most publish a gem or an Action Mailer delivery method. Sending from your own server's IP address is possible and rarely worth it.
- Authenticate your domain. Sender Policy Framework (SPF) lists the servers allowed to send for your domain. DomainKeys Identified Mail (DKIM) signs each message. Domain based Message Authentication, Reporting and Conformance (DMARC) tells receivers what to do when those checks fail. These are DNS records your provider will walk you through.
- Since February 2024, Gmail requires it. Google announced in October 2023 that from February 2024 bulk senders to Gmail, those sending more than 5,000 messages a day, must authenticate their mail, offer one click unsubscribe for commercial mail and keep their spam rate low21. Google's sender guidelines also require every sender, of any volume, to set up SPF or DKIM22. Cogwell sends far fewer than 5,000 a day, but the rules for all senders still apply, and doing all three costs an afternoon.
- Keep transactional and marketing mail apart. A newsletter that annoys people should never drag down the reputation of "your bike is ready". Most providers let you send the two through separate streams or subdomains.
Example: Cogwell's sending setup
Owen picks a transactional provider, adds its gem, and points production at it. The DNS records for cogwellcycles.example get an SPF entry for the provider, the provider's DKIM key, and a DMARC record that starts with p=none (report only) and moves to quarantine once the reports show nothing legitimate failing. Marketing emails, when Hannah wants them, go from a subdomain such as news.cogwellcycles.example through the provider's separate broadcast stream. In development, config.action_mailer.delivery_method = :test plus the previews means no real customer ever receives a test email.
Active Storage: before and after photos on every job card
Active Storage attaches files to Active Record models and stores them in a service: the local disk in development, an object store such as Amazon S3 in production23. You install it once:
bin/rails active_storage:install
bin/rails db:migrate
That creates three tables: blobs (one row per stored file, with its key, size, content type and checksum), attachments (which record a blob belongs to) and variant records (which transformed versions exist)23. Your own tables get no new columns.
The pieces from the Rails 7.1 Guide23:
has_one_attachedandhas_many_attacheddeclare attachments on a model.- Named variants declare transformed versions, such as thumbnails, in one place. Rails 7.1 added a
preprocessedoption, so a variant can be generated in a background job straight after upload instead of on the first page view5. - Transformations need the image_processing gem and libvips or ImageMagick on the server. New Rails 7 applications use libvips by default19.
- After upload, Active Storage analyses each file (dimensions, for example) in a background job.
purge_laterdeletes a file and its blob in a job.- Files on the Disk service are fine for development. In production, use an object store. The S3 service accepts an
endpoint, which is how you connect to S3 compatible services. The Guide's example is DigitalOcean Spaces23.
Example: the photos on a job card
# app/models/job_card.rb (the attachment part)
class JobCard < ApplicationRecord
PHOTO_TYPES = %w[image/jpeg image/png image/webp].freeze
MAX_PHOTO_SIZE = 15.megabytes
has_many_attached :before_photos do |attachable|
attachable.variant :thumb, resize_to_limit: [240, 240], preprocessed: true
attachable.variant :large, resize_to_limit: [1600, 1600], preprocessed: true
end
has_many_attached :after_photos do |attachable|
attachable.variant :thumb, resize_to_limit: [240, 240], preprocessed: true
attachable.variant :large, resize_to_limit: [1600, 1600], preprocessed: true
end
validate :photos_are_images_of_sensible_size
private
def photos_are_images_of_sensible_size
(before_photos + after_photos).each do |photo|
unless photo.content_type.in?(PHOTO_TYPES)
errors.add(:base, "#{photo.filename} is not a JPEG, PNG or WebP photo")
end
if photo.byte_size > MAX_PHOTO_SIZE
errors.add(:base, "#{photo.filename} is larger than 15 MB")
end
end
end
end
Active Storage in Rails 7.1 does not validate file type or size for you. The Guide does not offer such a validation, so you write one, as above, or use a community gem such as active storage validations. The content type checked here is the one Active Storage identifies from the file itself when it is analysed, but treat it as a helpful check, not a security boundary: never serve user uploads from your own domain as HTML.
The board shows the thumbnails:
<%# app/views/job_cards/_photos.html.erb %>
<% job_card.before_photos.each do |photo| %>
<%= image_tag job_card_photo_path(job_card, photo, variant: :thumb),
alt: "Before repair photo of #{job_card.booking.bike.description}" %>
<% end %>
That path points at Cogwell's own controller rather than at Active Storage's routes, for a reason the next section explains.
The storage service for production:
# config/storage.yml
local:
service: Disk
root: <%= Rails.root.join("storage") %>
photos:
service: S3
endpoint: https://s3.eu-west-2.amazonaws.com # or the endpoint of any S3 compatible provider
region: eu-west-2 # London
bucket: cogwell-job-card-photos
access_key_id: <%= Rails.application.credentials.dig(:storage, :access_key_id) %>
secret_access_key: <%= Rails.application.credentials.dig(:storage, :secret_access_key) %>
# config/environments/production.rb
config.active_storage.service = :photos
config.active_storage.queues.analysis = :default
config.active_storage.queues.purge = :default
The bucket stays private. Nothing in it is ever publicly readable.
Giant uploads: let the browser send photos straight to storage
A mechanic photographs a bike with a phone, and phone photos are large. If the form posts them to Rails, each upload occupies a Puma thread for as long as a workshop's wifi needs to push the bytes, and then Rails pushes the same bytes again to the storage service.
Direct uploads remove the middle step. The browser asks Rails for a signed upload URL, sends the file straight to the storage service, and submits only a small signed reference with the form. The Guide's steps are short: include Active Storage's JavaScript, add direct_upload: true to the file field, and configure the bucket's cross origin resource sharing (CORS) rules so the browser may upload to it from your domain23. The Disk service needs no CORS because it shares your application's origin23.
There is a catch worth knowing. With direct uploads the file is in the bucket before your model validation runs. A rejected 40 MB file is already stored, as a blob that belongs to nothing. The Guide shows how to purge such unattached uploads in a recurring task, with ActiveStorage::Blob.unattached.where(created_at: ..2.days.ago).find_each(&:purge_later)23.
Example: the upload form, and what it costs to keep photos
<%# app/views/job_cards/_photo_form.html.erb %>
<%= form_with model: job_card do |form| %>
<%= form.label :before_photos, "Before photos" %>
<%= form.file_field :before_photos, multiple: true, direct_upload: true,
accept: "image/jpeg,image/png,image/webp" %>
<%= form.submit "Save photos" %>
<% end %>
// app/javascript/application.js
import * as ActiveStorage from "@rails/activestorage"
ActiveStorage.start()
The accept attribute filters the phone's file picker. The model validation is still the real check. Owen also adds the unattached purge to the cron table as a nightly job.
Then a sum for Hannah, because photos accumulate quietly. Assume (this is an assumption for the arithmetic, not a measured figure) four photos per repair, two before and two after, at 3 MB each. The yearly storage for originals is
where is the volume in megabytes per year, the repairs per week, the photos per repair, the average size of one photo in megabytes, and 52 the weeks in a year (Foundations: ratios and rates). With Cogwell's numbers:
So GB: about 718 gigabytes a year of originals, growing for as long as nobody decides otherwise. The variants are small next to that. Object storage is priced per gigabyte per month, so the bill grows every month even if the business does not. This is a business decision dressed as a technical one: how long does Cogwell need the originals? Hannah decides two years for warranty disputes, after which a nightly job purges originals older than that and keeps only the large variant. Written down now, it costs a few lines of code. Discovered in year four, it costs an afternoon of nervous deletion.
Private files: signed, expiring, and behind your own login
This is the part most applications get wrong, so it is worth reading the Guide's exact position. The Guide says that all Active Storage controllers are publicly accessible by default, and that anyone who knows a blob's URL can access it, even if your controllers require a login23.
Here is how that comes about. The URL that url_for(photo) produces points to a Rails route containing the blob's signed ID. The signature stops anyone guessing other files. It does not expire unless you set config.active_storage.urls_expire_in, whose default is nil19. When requested, the route redirects to a short lived URL at the storage service. That one expires after 5 minutes by default (service_urls_expire_in)19. So the link that leaks is the long lived one: pasted in a chat, forwarded in an email, kept in a browser history.
For photos of a customer's bicycle that may not sound alarming. But job card photos can show a home address on a label, a face in the background, or a very expensive bike and where it is kept. Security of processing is a legal duty in the UK too: Article 32 of the UK General Data Protection Regulation (UK GDPR) asks for measures appropriate to the risk24. The Information Commissioner's Office (ICO) is the regulator. This is general information, not legal advice. In practice, it means a file link should only work for the people who should see the file, and only for a while.
The Guide's answer is to build your own controllers for files that need authentication, and optionally to switch off the built in routes with config.active_storage.draw_routes = false23. Switching them off also removes the direct upload route, which then has to be drawn by hand, so Owen takes a middle path.
Example: photos only for logged in staff, links that die
# config/environments/production.rb
config.active_storage.urls_expire_in = 1.hour # leaked Active Storage links stop working
# config/routes.rb
resources :job_cards do
resources :photos, only: :show, controller: "job_card_photos"
end
# app/controllers/job_card_photos_controller.rb
class JobCardPhotosController < ApplicationController
before_action :require_staff_login # the authentication from the security chapter
def show
job_card = JobCard.find(params[:job_card_id])
photo = (job_card.before_photos + job_card.after_photos).find { |p| p.id == params[:id].to_i }
raise ActiveRecord::RecordNotFound unless photo
variant = params[:variant].presence_in(%w[thumb large])
file = variant ? photo.variant(variant.to_sym).processed : photo
# A direct storage URL that expires in five minutes, issued only after the login check
redirect_to file.url(expires_in: 5.minutes, disposition: :inline), allow_other_host: true
end
end
The view never contains an Active Storage URL. It contains a link to JobCardPhotosController, which checks who is asking and only then hands out a five minute link to the private bucket. A leaked page shows a link that requires a login. A leaked storage link is dead within five minutes. A leaked Active Storage link, if one ever escapes, dies within the hour. The finer question of which staff may see which workshop's cards belongs to authorisation, which the security chapter covers.
For the person paying for this
If you commission a Rails application, you do not need to read the code above to judge this part of the work. Ask these questions, and listen for a calm, specific answer:
| Question | A good answer sounds like |
|---|---|
| What runs our background jobs in production? | A named backend, with a dashboard you can be shown, not the default :async adapter |
| What happens if a job runs twice? | "Nothing, it checks the database first", with a test to prove it |
| Can a customer get a message for something that was cancelled or rolled back? | "No, the job is only enqueued after the commit" or "the jobs are in the same database transaction" |
| How would anyone notice if messages stopped going out? | Failed jobs are visible and alert someone, a sweep resends dropped ones |
| How many retries, and why that number? | Tied to how long the message stays useful |
| Are uploaded files private? How long do links work? | Private bucket, own controller with a login, links that expire |
| How long are photos kept, and what does that cost per year? | A retention period you agreed, and a rough storage figure |
| Is our email domain authenticated? | SPF, DKIM and DMARC set up, transactional and marketing mail separated |
None of this is exotic. It is a few days of careful work in the first version, and it is the difference between an application your staff trust and one they double check by phone. If you are planning one, my web application development page explains how I build them, and my prices are published.
What the Django version does differently
The Django series builds the same three features for the same company, in the Django chapter on background tasks, email and files later in this programme. The short version, so you can compare like for like: Django in its 5.0 release has no built in task queue, so the job layer is a third party choice (Celery is the common one), while email and file storage are built in. The three questions and the rule "let the database remember, let the queue hurry" apply unchanged, because they are about the queue and the database, not about the framework.
Conclusion
Slow, foreign and heavy work belongs outside the request, and Rails gives you good tools for it: Active Job as the interface, Action Mailer for email with previews you can show the person who owns the wording, and Active Storage for files with variants and direct uploads. The tools are the easy part.
The hard part is the promises. Every job must answer three questions: could it run twice, could it run for nothing, could it never run. Record the business fact in your own database inside the transaction, enqueue after commit (or inside the transaction when the queue shares the database), make every job check before it acts, size retries by how long the result stays useful, and sweep for promises that were not kept. Use queues rather than priority numbers. Keep files in a private bucket, behind your own login, with links that expire.
My view: for an application of Cogwell's size, background work is a correctness problem long before it is a capacity problem. Choose the backend that makes correctness easiest for your team, which often means the one that lives in the database you already run, and spend the time you save on the tests that prove a message goes out once.
