Page results with a cursor
Users scroll long lists; OFFSET queries get slower the deeper they go.
Say it like this
Users scroll a long timeline, so I page by cursor rather than offset: the client sends the last (created_at, id) it saw, the query seeks past it on the index, and page 1,000 costs the same as page 1.
Basic solution
Return an opaque cursor (last seen key or timestamp) and query "rows after cursor LIMIT n" using an index.
Cursor seek versus offset skip
The offset query reads and discards everything before the page. The cursor query seeks straight to the position after the last seen key, so every page costs the same.
How it works
- Choose a sort key that is unique and indexed, such as (created_at, id) rather than created_at alone. Two rows can share a timestamp, and the id breaks the tie so the order is the same on every request.
- First page: SELECT ... WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT 21. Ask for one row more than the page size; if 21 come back you know a next page exists and you show 20.
- Build the cursor from the last row you return: encode its (created_at, id) as an opaque base64 string. Opaque means clients cannot read or forge it, so you can change its contents later without breaking them.
- Next page: WHERE user_id = ? AND (created_at, id) < (cursor.created_at, cursor.id) ORDER BY created_at DESC, id DESC LIMIT 21. The index seek lands directly on the row after the cursor, so no earlier rows are read or skipped.
- Return the rows plus next_cursor, or null when fewer than 21 came back, which tells the client it has reached the end.
- For paging in both directions, also return a prev_cursor built from the first row, and for the previous page flip the comparison to greater-than and the ORDER BY to ascending, then reverse the result.
Why offset degrades
- OFFSET 10000 LIMIT 20 reads 10,020 rows and throws away the first 10,000 on every request, so the cost grows with how deep the user has scrolled. A row inserted between two page requests also shifts every offset by one, so the user sees a duplicate or misses a row.
Worked example
Message history in the chat app
- A conversation table keyed by (conversation_id, seq). A long group chat has 2 million messages; the client scrolls back 50 at a time.
- Offset paging: scrolling to the 100,000th message runs OFFSET 100000 LIMIT 50, reading 100,050 index entries, about 80 ms, and the cost keeps rising. A new message arriving between two pages shifts every offset by one, so the user sees a duplicate.
- Cursor paging: WHERE conversation_id = ? AND seq < 1900000 ORDER BY seq DESC LIMIT 51. The index seek costs the same at any depth, about 1 ms, and new messages change nothing because the cursor is an absolute position.
- Scale: 100,000 history fetches per second across the fleet; with offsets the average fetch depth of 2,000 means 200 million index entries read per second; with cursors it is 5 million. A 40x reduction in index reads for the same user experience.
- Cursor size: seq is an integer, so the opaque cursor is about 16 bytes encoded; a (created_at, id) cursor is about 40 bytes.
Variants and when each wins
Keyset (cursor) pagination
- Each page seeks past the last key seen on an index. It wins for feeds and infinite scroll because every page costs the same and inserts do not shift results; it cannot jump to page N.
Offset pagination
- OFFSET n LIMIT m. It wins for small admin tables that need page numbers and a total count, and it degrades with depth and shifts under inserts.
Time-bucketed pages
- Each page is a fixed time window, such as one day. It wins for activity logs and calendars because pages are easy to cache and share, and page sizes are uneven.
Search-engine cursors
- Elasticsearch search_after, or a point-in-time snapshot. It wins for search results because the cursor walks a consistent snapshot, so results do not shift while the user scrolls.
Recommendation: keyset for anything a user scrolls; offset only for small admin lists that need page numbers.
Failure modes
Duplicate or missing rows between pages
- You notice a user sees the same post twice while scrolling. It happens because offsets shifted when a row was inserted, or because the cursor is on a column where two rows share a value. Fix it with a cursor on (sort_key, id) and a strict comparison, so the order is total.
Cursor on a mutable field
- You notice rows go missing mid-scroll when paging by updated_at. It happens because a row was edited, its updated_at moved past the cursor, and the seek skipped it. Fix it by paging on an immutable key such as created_at or a sequence number, and surfacing edits some other way.
Client depends on cursor contents
- You notice old app versions break after a backend change to the cursor format. It happens because the cursor was plain JSON the client parsed and relied on. Fix it by encoding cursors opaquely and versioning them, and by rejecting a malformed cursor with a 400.
Deep offset on a large table
- You notice page 5,000 of a report times out. It happens because OFFSET reads and discards every row before that page. Fix it by switching to keyset paging, or by capping the offset and offering filters to narrow the list instead.
Count queries on every page
- You notice each page spends most of its time on SELECT COUNT(*). It happens because the UI shows a total page count, and counting a large table is a full scan. Fix it by estimating the count from table statistics, caching it, or dropping page numbers in favour of infinite scroll.
Interviewer follow-ups
Answer out loud before you open each one.
Why must the cursor include the id as well as the timestamp?
Timestamps collide, especially at millisecond resolution under load. Without a tiebreaker the comparison created_at < cursor either skips rows that share the cursor timestamp or returns them again. Adding the unique id makes the ordering total and the seek exact.
How do you support jumping to page 50 with cursors?
You generally do not; keyset paging gives next and previous. If the product needs random access, approximate it with a filter (jump to a date) or precompute page boundaries for a static list. For truly random access on small lists, offset paging is acceptable.
How does a cursor behave when the underlying rows are deleted?
Well, as long as the comparison is strict: the seek lands on the next existing key after the cursor, so a deleted row is simply absent. The cursor itself does not need to point at a live row, which is another reason to prefer it over offsets.
What does the index need to look like for keyset paging to be fast?
It must match the WHERE prefix and the ORDER BY exactly: (user_id, created_at desc, id desc) for a per-user timeline. Then the planner does one seek and a short forward scan, with no sort node. A mismatched order forces a sort over every candidate row.
Connections
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | History API | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |