ruby 43 lines · 7 steps

Batching monthly email summaries in Rails

A service object slices opted-in recipients into fixed-size batches, builds payloads, and enqueues mail with an audit log per batch.

Explained by highlit
1class ReportBatcher
2 BATCH_SIZE = 500
3 
4 def initialize(account)
5 @account = account
6 end
7 
8 def deliver_monthly_summaries
9 pending_recipients.each_slice(BATCH_SIZE).with_index(1) do |batch, page|
10 Rails.logger.info("Dispatching summary batch ##{page} (#{batch.size} recipients)")
11 
12 summaries = build_summaries_for(batch)
13 SummaryMailer.bulk_deliver(summaries).deliver_later
14 
15 @account.delivery_logs.create!(
16 page: page,
17 recipient_ids: batch.map(&:id),
18 delivered_at: Time.current
19 )
20 end
21 end
22 
23 private
24 
25 def pending_recipients
26 @account.users
27 .active
28 .where(monthly_summary_opt_in: true)
29 .order(:created_at)
30 .to_a
31 end
32 
33 def build_summaries_for(batch)
34 batch.map do |user|
35 {
36 user_id: user.id,
37 email: user.email,
38 metrics: MetricsAggregator.new(user).last_month,
39 generated_at: Time.current
40 }
41 end
42 end
43end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Slicing a large collection into fixed-size batches keeps memory and mailer load predictable at scale.
  2. 2Enqueuing work with deliver_later moves heavy delivery off the request path into background jobs.
  3. 3Recording a log row per batch gives you a replayable audit trail of what was sent and to whom.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Batching monthly email summaries in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code