---
title: Use find_each for large collections
impact: HIGH
impactDescription: Reduce memory consumption when iterating over large datasets.
tags: rails, performance, database, memory, active-record
---

## Use find_each for large collections

Reduce memory consumption when iterating over large datasets. Use `find_each` or `find_in_batches` instead of `each` for large ActiveRecord collections. `find_each` loads records in batches (default 1000) to avoid loading all records into memory at once.

**Incorrect:**

```ruby
# Loads ALL users into memory, which can crash the process for large datasets
User.all.each do |user|
  user.do_something
end
```

**Correct:**

```ruby
# Loads users in batches of 1000
User.find_each do |user|
  user.do_something
end
```

**Tools:** RuboCop (`Rails/FindEach`)
