← TidbitsSnippet

Active Record Batching

Efficient memory usage when querying large database collections by using batch processing methods.

When working with thousands of database records in Ruby on Rails, loading all of them into memory at once can exhaust server memory. Instead, use batch processing to fetch records in small groups.

Using find_each queries records in batches of 1000 by default, keeping your memory consumption flat.

# Good: Memory footprint stays flat as it batches database records
User.active.find_each(batch_size: 500) do |user|
  user.calculate_reputation_score!
end

Avoid .each when processing large tables, as it executes a single query and instantiates all objects simultaneously.