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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Slicing a large collection into fixed-size batches keeps memory and mailer load predictable at scale.
- 2Enqueuing work with deliver_later moves heavy delivery off the request path into background jobs.
- 3Recording a log row per batch gives you a replayable audit trail of what was sent and to whom.
Related explainers
ruby
require "csv" class SalesReport def initialize(path)
Aggregating CSV sales data in Ruby
data-aggregation
memoization
group_by
Intermediate
6 steps
ruby
module DurationFormatter UNITS = [ ['week', 604_800], ['day', 86_400],
Turning seconds into human-readable durations in Ruby
greedy-decomposition
modular-arithmetic
formatting
Intermediate
7 steps
ruby
class Comment < ApplicationRecord belongs_to :post belongs_to :author, class_name: "User"
Live-updating comments with Turbo in Rails
turbo-streams
callbacks
associations
Intermediate
8 steps
ruby
require 'json' require 'set' class SensitiveScrubber
Recursively scrubbing secrets from JSON
recursion
data-masking
pattern-matching
Intermediate
7 steps
ruby
class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true, counter_cache: true belongs_to :author, class_name: "User"
How polymorphic comments work in Rails
polymorphic-association
concerns
counter-cache
Intermediate
8 steps
ruby
class SessionsController < ApplicationController MAX_ATTEMPTS = 5 THROTTLE_WINDOW = 15.minutes
Throttling failed logins in Rails
rate-limiting
authentication
caching
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/batching-monthly-email-summaries-in-rails-explained-ruby-b686/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.