Our company has a weekly newsletter we send out to all users, but recently the process started crashing due to memory issues and our ever increasing user base. What can we do to prevent the crashing?
User.all.each do |user|
Newsletter.weekly(user).deliver_now
end
We can use find_each
and specify a batch size to iterate over all users in
a more memory efficient way:
User.find_each(batch_size: 100) do |user|
Newsletter.weekly(user).deliver_now
end
Check out the Rails Guides entry on [Retrieving Multiple Objects in Batches][] for more detail.
[Retrieving Multiple Objects in Batches]: http://guides.rubyonrails.org/active_record_querying.html#retrieving-multiple-objects-in-batches
Return to Flashcard Results