Keyset Pagination vs LIMIT OFFSET in ActiveRecord
Replace OFFSET with a row-value WHERE clause and a composite index, and keep deep pages as fast as page one.
Keyset pagination replaces OFFSET with a WHERE clause on the last row you showed. In ActiveRecord you write it as where("(created_at, id) > (?, ?)", last.created_at, last.id) with a matching order(:created_at, :id) and a composite index. The cost of a page stays flat. OFFSET gets slower with every page you skip.
Tested on ActiveRecord 8.1.1, PostgreSQL 16.15, Ruby 3.3.6. I ran everything below on PostgreSQL only.
The setup
One table, one million rows, ten rows per timestamp (one timestamp per minute) so ties are real. The index is the one keyset pagination needs.
create_table :events do |t|
t.string :title
t.datetime :created_at, null: false
end
add_index :events, [:created_at, :id]
What OFFSET does at depth
This is what Event.order(:created_at, :id).limit(20).offset(500_000) produces:
SELECT "events".* FROM "events"
ORDER BY "events"."created_at" ASC, "events"."id" ASC
LIMIT 20 OFFSET 500000
The index gives you the right order. It does not let the database jump to row 500,000. PostgreSQL reads every entry up to the offset and throws them away:
Limit (cost=22572.58..22573.48 rows=20 width=23) (actual time=72.292..72.297 rows=20 loops=1)
-> Index Scan using index_events_on_created_at_and_id on events
(actual time=0.037..56.691 rows=500020 loops=1)
The scan node returned rows=500020 to produce 20 rows. The PostgreSQL manual says the same: rows skipped by an OFFSET clause still have to be computed inside the server. Here is the second-run EXPLAIN ANALYZE execution time at four depths, on this one machine with a warm cache:
| Offset | Index entries read | Execution time |
|---|---|---|
| 0 | 20 | 0.018 ms |
| 100,000 | 100,020 | 12.6 ms |
| 500,000 | 500,020 | 60.6 ms |
| 900,000 | 900,020 | 122.1 ms |
Your absolute numbers will differ. The shape will not. Work grows linearly with the offset. A client walking every page of a large table pays this cost on every request, so the total work grows with the square of the table size.
OFFSET has a second flaw. If a row is inserted or deleted while a user pages through, the next page shifts and shows a duplicate or skips a row. Keyset pagination does not have this problem, because each page is anchored to a value and not to a position.
The keyset query
Remember the last row of the page. Ask for rows after it:
def next_page(after_created_at, after_id, per = 20)
rel = Event.order(:created_at, :id).limit(per)
rel = rel.where("(created_at, id) > (?, ?)", after_created_at, after_id) if after_id
rel
end
last = next_page(nil, nil).to_a.last
next_page(last.created_at, last.id)
SELECT "events".* FROM "events"
WHERE ((created_at, id) > ('2025-01-01 00:01:00', 20))
ORDER BY "events"."created_at" ASC, "events"."id" ASC
LIMIT 20
The tuple comparison (created_at, id) > (a, b) (PostgreSQL compares row elements left to right) means “created_at is greater, or created_at is equal and id is greater”. PostgreSQL turns it into an index condition. Here is the plan for the page after row 500,000:
Limit (cost=0.42..1.60 rows=20 width=23) (actual time=0.050..0.054 rows=20 loops=1)
-> Index Scan using index_events_on_created_at_and_id on events
(actual time=0.049..0.051 rows=20 loops=1)
Index Cond: (ROW(created_at, id) > ROW('2025-02-04 17:19:00'::timestamp without time zone, 500000))
It read 20 entries and took 0.064 ms. The OFFSET version of the same position took 60.6 ms, roughly 900 times longer. I walked the first 1,000 pages this way and got ids 1 to 20,000 in order with no duplicates and no gaps.
The tie-breaker is not optional
Ten rows share each created_at value in this table. If you order and compare on created_at alone, WHERE created_at > last.created_at skips the remaining rows with the same timestamp, and >= repeats them. In my table a cursor at id 5 with created_at > jumped to id 11 and skipped ids 6 to 10. With >= the next page restarted at id 1. Add a unique column as the last sort key. The primary key is the usual choice.
Ordering by a non-unique column alone is also unstable with OFFSET. The database is free to return tied rows in any order, so two requests for the same page might disagree. Add :id there too.
Descending order
Flip both the comparison and the order. Both columns must go the same direction:
Event.order(created_at: :desc, id: :desc).limit(20)
.where("(created_at, id) < (?, ?)", cursor_time, cursor_id)
Index Scan Backward using index_events_on_created_at_and_id on events
Index Cond: (ROW(created_at, id) < ROW('2025-02-04 17:19:00'::timestamp without time zone, 500000))
The existing ascending index serves it with a backward scan.
Mixed directions need the long form
Row-value comparison applies one direction to every column. For ORDER BY created_at DESC, id ASC you must expand it by hand:
Event.order(created_at: :desc, id: :asc).limit(20)
.where("created_at < :t OR (created_at = :t AND id > :i)", t: cursor_time, i: cursor_id)
PostgreSQL 16 did not use an index condition for this form. The plan was an index scan with a filter plus an incremental sort, and at position 500,000 it took 44.2 ms:
Incremental Sort Sort Key: created_at DESC, id
Presorted Key: created_at
-> Index Scan Backward using index_events_on_created_at_and_id on events
Filter: ((created_at < '2025-02-04 17:19:00'::timestamp without time zone) OR ((created_at = '2025-02-04 17:19:00'::timestamp without time zone) AND (id > 500000)))
Rows Removed by Filter: 500010
The scan walked the index and threw away 500,010 entries before it found 20 rows. That is the cost shape of OFFSET. I also built an index with matching mixed directions, add_index :events, [:created_at, :id], order: { created_at: :desc, id: :asc }. The planner used it, still as a filter: 45.9 ms, 500,010 rows removed. A matching index did not rescue the OR form in this test. If you get to choose, keep every sort column in one direction and use the row-value form.
Index traps
I replaced the composite index with one on created_at alone. The plan became an index scan with Index Cond: (created_at >= ...), a row-value Filter, and an incremental sort. It still returns correct pages (0.050 ms in my test, with 10 rows removed by the filter), but the database filters and sorts rows inside each group of equal timestamps. With ten ties per value the groups are small. With a low-cardinality column such as a date or a status, the groups are large.
NULLs break row comparison. In a five-row test table with two null scores, WHERE (score, id) > (0, 0) returned 3 of 5 rows. The null rows never match a tuple comparison, because PostgreSQL returns NULL when the first unequal pair contains a NULL (docs). Keep sort columns NOT NULL. For nullable columns, read ORDER BY NULLS LAST in ActiveRecord first, because null placement changes the cursor logic too.
Precision trap
A cursor must carry the full timestamp. I stored 2030-01-01 12:00:00.500000, then built the cursor from the same value with microseconds cut to zero. The query returned the same row again. If you encode cursors into URLs, serialize with iso8601(6) and parse the same way. Do not round-trip through to_i.
What you give up
- No jump to page 37. You only move forward or backward from a known row. Pagy’s keyset paginator documents the same limit.
- No total page count. Counting rows is a separate query and costs a full scan or an estimate.
- Going backward means reversing the order and the comparison, then reversing the result in Ruby.
- Sorting by a user-chosen column needs a different index per option. Allow a short list.
- Cursors are opaque to users. They cannot edit a page number in the URL.
Keep OFFSET for small tables, admin screens, and any list where users need page numbers and no one will reach page 50,000. Use keyset for feeds, APIs, exports and anything a bot crawls.
Rails already does this internally for batches. By default find_each runs WHERE id > $1 ORDER BY id ASC LIMIT $2 for each batch in my test. On 8.1.1 it also takes cursor: [:created_at, :id], and the Rails API docs say custom cursor columns should include a unique tiebreaker. That option generates the long OR form, not the row-value form:
SELECT "events".* FROM "events"
WHERE ("events"."created_at" > $1 OR "events"."created_at" = $2 AND "events"."id" > $3)
ORDER BY "events"."created_at" ASC, "events"."id" ASC LIMIT $4
I ran the same OR condition by hand at position 500,000 of the million-row table. PostgreSQL 16 filtered instead of using an index bound: 41.1 ms, 500,000 rows removed. Each batch of a long job pays that scan at depth, so for a background job prefer the default id cursor. With order: :desc the cursor option sorts created_at DESC, id ASC, the mixed form from the section above.
If you start from SQL such as ORDER BY ... LIMIT ... OFFSET ..., the SQL to ActiveRecord converter gives you the offset form. Rewrite it by hand into the keyset form above, and confirm the plan with explain.
Related: ORDER BY NULLS LAST in ActiveRecord, Database indexes existed, ActiveRecord ignored them, find_each vs each
Frequently asked questions
- Why is OFFSET slow on deep pages in Rails?
- PostgreSQL reads and discards every row before the offset. In a 1,000,000-row test, offset 500,000 read 500,020 index entries and took 60.6 ms on a warm second run, while the keyset query read 20 entries in 0.064 ms.
- Do I need a tie-breaker column for keyset pagination?
- Yes, when the sort column is not unique. Append the primary key as the last order column and put it in the same tuple comparison, or rows sharing a value get skipped or repeated.
- Does keyset pagination work with descending order?
- Yes. Flip both the comparison and the order, so (created_at, id) < (?, ?) goes with order(created_at: :desc, id: :desc). A backward index scan served it in the test.
- Is jumping to page 37 possible with keyset pagination?
- No. You move forward or backward from a known row, and you get no total page count without a separate count query.
- What happens to NULL values in a keyset sort column?
- A row whose first compared column is NULL never matches a tuple comparison. In a five-row test with two NULL scores, the query returned 3 of 5 rows. Keep sort columns NOT NULL.
Was this article helpful?
Your feedback helps us improve our content
How We Verify Conversions
Every conversion shown on this site follows a strict verification process to ensure correctness:
- Compare results on same dataset — We run both SQL and ActiveRecord against identical test data and verify results match
-
Check generated SQL with
to_sql— We inspect the actual SQL Rails generates to catch semantic differences (INNER vs LEFT JOIN, WHERE vs ON, etc.) - Add regression tests for tricky cases — Edge cases like NOT EXISTS, anti-joins, and predicate placement are tested with multiple scenarios
- Tested on Rails 8.1.1 — All conversions verified on current Rails version to ensure compatibility
Last updated: December 03, 2026
Try These Queries in Our Converter
See the SQL examples from this article converted to ActiveRecord—and compare the SQL Rails actually generates.
Deep Dive into ActiveRecord
Raza Hussain
Full-stack developer specializing in Ruby on Rails, React, and modern JavaScript. 15+ years upgrading and maintaining production Rails apps. Led Rails 4/5 → 7 upgrades with 40% performance gains, migrated apps from Heroku to Render cutting costs by 35%, and built systems for StatusGator, CryptoZombies, and others. Available for Rails upgrades, performance work, and cloud migrations.
More on SQL to ActiveRecord
LOWER() in ActiveRecord and the Functional Index Trap
LOWER() in ActiveRecord where and order, why a plain index is ignored, and the add_index expression fix, with EXPLAIN on PostgreSQL.
UPDATE with JOIN in Rails: update_all and joins
UPDATE with JOIN in Rails on PostgreSQL: joins plus update_all, the UPDATE FROM SQL on 8.1.1, the 8.0 error and safe alternatives. Tested.
SQL INTERSECT and EXCEPT in Rails ActiveRecord
ActiveRecord has no intersect or except method. Four tested options for Rails 8.1: Arel nodes, from with raw SQL, find_by_sql and where IN rewrites.
Leave a Response
Responses (0)
No responses yet
Be the first to share your thoughts