skip to content

In Active Record, what do the batch options cursor:, order:, start: and finish: do, and what goes wrong when the cursor column changes mid-run?

level: seniorimportance: should knowfreq 30%

answer

  1. cursor defaults to the primary key
  2. unique column required
  3. start and finish are inclusive
  4. order: :asc or :desc per column
  5. static cursor columns only

basics

~20 s

cursor: picks the unique column set a batch walk sorts and continues by (the primary key by default), order: sets each column's direction, and start: and finish: bound the walk inclusively. A cursor that changes mid-run repeats or skips rows.

solid answer

~50 s

`find_each`, `find_in_batches` and `in_batches` all take `cursor:`, `order:`, `start:` and `finish:`. `cursor:` names the column, or array of columns, to sort and continue by; it must include the primary key or the columns of a unique, non-partial index, otherwise Rails raises `ArgumentError`. `order:` is `:asc` (default) or `:desc`, or an array with one direction per cursor column. `start:` and `finish:` are inclusive bounds on the cursor, one value per column, useful for resuming a job or splitting a table between workers. Because each batch continues after the last cursor value, the cursor must be **static**: if the job raises the `loyalty_score` it walks by, rows jump ahead of the cursor and are visited again, and a row whose score drops below the cursor before it is reached is skipped. A `nil` cursor value, or a custom `select` without the cursor columns, raises `ArgumentError`.

code

ruby · 10 lines
ruby
# Two workers split the members table by id
Member.in_batches(of: 5_000, finish: 499_999) { |b| b.update_all("loyalty_score = 0") }
Member.in_batches(of: 5_000, start: 500_000)  { |b| b.update_all("loyalty_score = 0") }

# Resume after a crash: start is inclusive, so begin one past the last finished id
last_done = Checkpoint.value_for("rescore")
Member.find_each(start: last_done + 1) do |member|
  member.update!(loyalty_score: LoyaltyScore.for(member))
  Checkpoint.record("rescore", member.id)
end

go deeper

for a junior

Know that batches walk the primary key by default and that start: and finish: limit which ids are visited, both inclusive.

for a middle

Explain the uniqueness check on cursor:, composite cursors, order: per column, and the ArgumentErrors for wrong-sized bounds or nil cursor values.

for a senior

Show why cursor columns must be static, plan parallel ranges and crash resumption, and index any custom cursor in its column order.

for a principal

Choose how long backfills are split, checkpointed and parallelised, and when a custom cursor's ordering is worth its index and its race conditions.

## The cursor behind every batch method Every Active Record batch method sorts by a **cursor** and fetches the next batch with a condition "after the last cursor value seen". By default the cursor is the **primary key** in ascending order, which is why `find_each` reads `ORDER BY id LIMIT 1000` and then `id > last_id`. Four options change that walk, on `find_each`, `find_in_batches` and `in_batches` alike. ## The four options | Option | Default | What it does | |---|---|---| | `cursor:` | the primary key | the column, or array of columns, to sort and continue by | | `order:` | `:asc` | `:asc` or `:desc`, or an array with one direction per cursor column | | `start:` | none | the first cursor value to include | | `finish:` | none | the last cursor value to include | Details that matter in an interview: - **Uniqueness is enforced.** If the cursor does not contain the primary key, Rails looks in the schema cache for a unique index without a `WHERE` clause whose columns are all part of the cursor. Finding none, it raises `ArgumentError` ":cursor must include a primary key or other unique column(s)". A non-unique cursor would let rows with equal values fall between batches. - **Composite cursors** compare like tuples: `cursor: [:store_id, :id]` continues with `store_id > s OR (store_id = s AND id > i)`. - **Bounds are inclusive.** `start: 10_000, finish: 19_999` visits both ends. Pass one value per cursor column, or Rails raises `ArgumentError` (":start must contain one value per cursor column"). - **Directions are checked.** Anything other than `:asc` or `:desc` in `order:` raises `ArgumentError`. - **Cursor values must be present.** A `nil` in a cursor column, or a custom `select` that leaves the cursor out, raises `ArgumentError` ("Not all of the batch cursor columns were included in the custom select clause or some columns contain nil"). ## Splitting and resuming work `start:` and `finish:` are the tools for long backfills: 1. **Parallel workers**: give each worker its own id range, `Member.in_batches(start: 1, finish: 499_999)` and `Member.in_batches(start: 500_000)`, so they never touch the same rows. 2. **Resuming**: store the last finished id as the loop runs; after a crash, restart with `start:` one past it, because `start:` is inclusive. 3. **Newest first**: `order: :desc` walks from the highest id down, so recent members are re-scored before old ones; `start:` then means the highest value to begin from. ## Why the cursor must be static The walk is a series of separate queries. Rails never re-reads earlier batches, so the cursor values must stay put while the job runs: - Walking `cursor: [:loyalty_score, :id]` in ascending order while **raising** scores moves rows ahead of the cursor: they reappear in a later batch and get raised again. - A row whose score **drops below** the cursor before the walk reaches it, lowered by concurrent traffic for example, is never visited. - The same applies to any column the job, or concurrent traffic, writes: a status, a timestamp, a position. The Rails source says it plainly: custom cursor columns should include a unique column as a tiebreaker and should be static, and batch processing is subject to race conditions when other processes modify the data. The primary key is the safe default because nothing reassigns it. ## A cursor that pays off A non-default cursor is worth it when the order carries meaning and the column never changes after insert, for example walking `prices` by `[:recorded_on, :id]` to rebuild daily aggregates in date order. Index the cursor columns in that order, or each batch query sorts the remaining table. ```ruby Price.where(store: store) .in_batches(of: 2_000, cursor: [:recorded_on, :id], start: [Date.new(2026, 1, 1), 0]) do |batch| DailyPriceRollup.rebuild_for(batch) end ``` ## Checklist before a long batch run 1. Is the cursor unique (primary key included, or a non-partial unique index) and indexed in cursor order? 2. Can anything, the job or live traffic, write the cursor columns while the run is in progress? 3. Where is the last finished cursor value recorded, and is the per-row work safe to repeat if a batch runs twice? 4. If several workers share the table, do their `start:`/`finish:` ranges cover it without overlap or gaps? ## Interaction with a scoped order Batch methods ignore a scope's own `order`, warning "Scoped order is ignored, use :cursor with :order to configure custom order", or raising when `error_on_ignored_order` is set. The message is the hint: a custom order for batching is expressed with `cursor:` and `order:`, never with `.order(...)` on the relation.

  • Why does Rails reject cursor: :store_id on its own for a products table?
    Many products share a `store_id`, so a batch boundary could fall inside one store and the next batch, continuing with `store_id >` the last value, would skip the rest of that store. Rails therefore requires the primary key or a unique index in the cursor; `cursor: [:store_id, :id]` fixes it.
  • Does the cursor need an index?
    Rails does not require one, but each batch query sorts by the cursor and filters on it, so without a matching index every batch scans and sorts the remaining rows. The primary key is indexed already; a custom cursor should have a composite index in the same column order.

  • start: is exclusive, so resume with the last finished id itself.
  • Any column can be a batch cursor, unique or not.
  • in_batches snapshots all ids first, so changing the cursor column is harmless.
  • order: accepts any SQL direction such as NULLS LAST.
  • To batch in a custom order, call .order(...) on the relation before find_each.