In Active Record, how does in_batches differ from find_each, and when does in_batches with update_all beat loading each record?
answer
- yields relations, not records
- pluck ids, then WHERE id IN
- whole table: id ranges
- BatchEnumerator returns a row total
- no validations or callbacks
basics
~20 sin_batches yields an unloaded relation per batch of 1,000 ids instead of model objects, so batch.update_all writes a whole batch in one UPDATE. That beats find_each when the change is expressible in SQL and per-record validations and callbacks are not needed.
solid answer
~40 s`find_each` loads records; `in_batches` yields an `ActiveRecord::Relation` per batch (`load: false` by default), so you can run set-based statements on it: `Member.where(tier: "gold").in_batches(of: 5_000) { |batch| batch.update_all("loyalty_score = loyalty_score * 2") }`. For a scoped relation each batch costs two queries, a `pluck` of the ids and an `UPDATE ... WHERE id IN (...)`; a walk over the whole table uses id ranges by default. Without a block it returns a `BatchEnumerator` whose `update_all`, `delete_all` and `touch_all` return the total rows affected, and `destroy_all` instantiates and runs callbacks. The win is huge for a million rows, a few hundred statements instead of a million, and short transactions per batch. The cost is that `update_all` skips validations, callbacks and `updated_at`, so use it only where nothing per-record must happen.
code
ruby · 8 linesMember.where(tier: "gold").in_batches(of: 5_000) do |batch|
batch.update_all(["loyalty_score = loyalty_score * 2, updated_at = ?", Time.current])
sleep 0.1 # give live traffic room between batches
end
# The same, as a one-liner that returns the total rows updated
Member.where(tier: "gold").in_batches(of: 5_000)
.update_all("loyalty_score = loyalty_score * 2")go deeper
Know that in_batches yields relations you can call update_all or delete_all on, while find_each yields records.
Explain the pluck-then-IN query pair, range iteration on whole tables, and the BatchEnumerator methods and their return values.
Justify batch size and throttling by lock time and replication lag, and decide which per-record side effects make update_all unsafe.
Set a team policy for data fixes: when set-based batches are allowed, who signs off on skipped callbacks, and how runs are throttled and observed.
## Three batch methods, three shapes All of Active Record's batch methods walk the table by a cursor (the primary key by default) in chunks of 1,000. They differ in what reaches your block: | Method | Yields | Loads records? | |---|---|---| | `find_each` | each record | yes | | `find_in_batches` | an `Array` of records | yes | | `in_batches` | an `ActiveRecord::Relation` for one batch | no, unless `load: true` | `in_batches` exists for **set-based work**: a relation that stands for 1,000 rows can be updated, deleted or counted in one statement without building a single model. ## What in_batches runs For a scoped relation, each batch is two queries: 1. A `pluck` of the next batch's ids: `SELECT members.id FROM members WHERE tier = 'gold' AND members.id > 41873 ORDER BY members.id LIMIT 5000`. 2. Whatever you run on the yielded relation, which is the original scope with `id IN (...)` for that batch: `UPDATE members SET loyalty_score = loyalty_score * 2 WHERE tier = 'gold' AND members.id IN (...)`. When the relation has **no conditions at all** (`Member.in_batches`), Rails switches to **range iteration**: it finds the last id of each batch with a single-row lookup and yields a relation bounded by `id > previous_last AND id <= last`, instead of an `IN` list of 1,000 ids. `use_ranges: true` opts a filtered relation into the same style, which suits a filter that matches almost every row; `use_ranges: false` turns it off. ## The BatchEnumerator shortcuts Called without a block, `in_batches` returns an `ActiveRecord::Batches::BatchEnumerator`: - `update_all(updates)`: runs `update_all` per batch and returns the **total** rows updated. - `delete_all`: deletes per batch with no callbacks and returns the total. - `touch_all`: updates timestamps per batch. - `destroy_all`: **instantiates** each batch and runs `destroy` callbacks, returning the count destroyed. - `each_record`: yields records one by one, like `find_each`. - `each`: yields the relations, the same as passing a block. ```ruby Member.where(tier: "gold").in_batches(of: 5_000).update_all("loyalty_score = loyalty_score * 2") # => 238_114 (rows updated across all batches) ``` ## Why it wins Re-scoring a million members with `find_each` and `update!` means a million `SELECT`ed models and a million single-row `UPDATE`s, each with its own transaction, validations and callbacks. With `in_batches(of: 5_000)` and `update_all` it is about 200 id lookups and 200 `UPDATE`s. Batching rather than one giant `update_all` matters too: - each statement locks at most one batch of rows, so other writers wait less; - each statement's transaction is short, which keeps lock waits and replication lag small; - the loop can **throttle** between batches, `sleep(0.1)`, to share the database with live traffic. ## What you give up `update_all` is a plain SQL `UPDATE`. It **skips validations and callbacks**, does not set `updated_at` unless you include it, and leaves any already-loaded records stale. Use it when: 1. the new value is computable in SQL, such as arithmetic on columns or a subquery; 2. nothing per-record must happen afterwards: no cache to bust, no search index to update, no event to publish; 3. the rule you would otherwise validate is enforced by a database constraint, or by the update itself. When per-record behaviour is required, use `each_record` or `find_each` and accept the cost, or do the set-based update and then enqueue the follow-up work per batch. ## A note on loaded relations `in_batches(load: true)` loads each batch's records into the yielded relation, so iterating it does not query again, while `update_all` on it still targets exactly that batch's ids. It is the bridge when a batch needs Ruby logic to decide something and SQL to apply it: ```ruby Member.in_batches(of: 1_000, load: true) do |batch| lapsed_ids = batch.select { |m| m.last_purchase_on&.before?(1.year.ago.to_date) }.map(&:id) batch.where(id: lapsed_ids).update_all(tier: "lapsed") end ``` ## Choosing a batch size `of:` defaults to 1,000. Larger batches mean fewer round trips but longer statements and longer row locks per `UPDATE`; smaller ones are gentler on a busy primary but take longer overall. A few thousand rows per batch with a short pause is a common starting point for a live table; measure the statement time in the log and adjust, rather than trusting a fixed number.
- Why does Member.in_batches with no where clause avoid the 1,000-id IN list?For a relation with no conditions Rails uses range iteration by default: it looks up only the last id of each batch and yields a relation bounded by an id range. Two range bounds are much smaller to build, send and parse than a list of a thousand ids, and the batch's last id is found with a single-row lookup instead of plucking every id.
- When would you pass load: true to in_batches?When each batch needs both Ruby logic over the records and a set-based write on the same rows. With `load: true` the yielded relation already holds the batch's records, so iterating them does not run another query, and `update_all` on that relation still targets exactly that batch.
- in_batches yields arrays of loaded models just like find_in_batches.
- update_all on each batch still runs the model's validations.
- in_batches.update_all returns true when every batch succeeded.
- BatchEnumerator#delete_all runs dependent: :destroy callbacks per record.
- One giant update_all is always better than batching it.