find_each vs find_in_batches in Active Record

When working with large datasets in Rails, loading all records into memory can be expensive and inefficient. That’s where Active Record’s batch processing methods — find_each and find_in_batches — come to the rescue. They allow you to iterate over large numbers of records without blowing up your memory usage.

What is find_each?

find_each is a convenient way to loop over records one at a time, but under the hood it processes them in batches.

1
2
3
User.find_each(batch_size: 1000) do |user|
  user.send_weekly_email
end

What is find_in_batches?

find_in_batches gives you access to each batch as an array of records, allowing you to process them in groups.

1
2
3
User.find_in_batches(batch_size: 1000) do |users|
  users.each { |user| user.send_weekly_email }
end

When Should You Use Each?

Use find_each when:

Use find_in_batches when:

A Few Things to Keep in Mind