Pagination: offset and cursor

Intermediate · 26 min

Page a list with limit and offset or an opaque cursor. See offset repeat items, measure deep-page cost, and build a keyset cursor.

Before thisArgumentsNullability in practiceConnecting a database

Caleb Curry · 26 min

Pagination: offset and cursor

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Caleb CurryReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Never return an unbounded list. A field that can grow needs pagination from day one, because adding it later is a breaking change to the field's shape.
  • Offset pagination (`limit`, `offset`) is simple and allows jumping to page N, but rows inserted or deleted between requests make items repeat or vanish.
  • On a 500,000-row SQLite table an offset of 480,000 took about 1.3 ms against 0.003 ms for a keyset query; the database must walk the skipped rows.
  • Cursor pagination asks for the rows after a marker, `first: 20, after: $cursor`, so it stays stable under inserts and its cost does not grow with depth.
  • Keep cursors opaque, always order by a unique key, and add a tiebreaker such as `id` when sorting by a column that can repeat.

The problem: lists grow

A field posts: [Post!]! that returns everything works with ten rows and falls over at ten thousand: slow responses, big payloads, a database sweating. The fix is to return a page at a time. The decision that matters is how a client asks for the next page, because that choice shapes the schema, and changing it later breaks clients.

Two approaches cover nearly everything: offset and cursor. The video in this lesson is a general API walkthrough of both, and the GraphQL specifics are below.

Offset pagination

The client says how many and how far to skip:

type Query {
  postsByPage(limit: Int = 3, offset: Int = 0): [Post!]!
}
SELECT * FROM posts ORDER BY id DESC LIMIT ? OFFSET ?

It is easy to build, easy to understand, and supports “jump to page 7” and numbered pagers. Many real products rely on those, so it earns a place.

It has two problems, which I measured.

It is unstable when data changes. I fetched page 1 (limit: 3, offset: 0), which returned Post 10, 9, 8. Then someone inserted a new post. Page 2 (offset: 3) returned:

page 1:  Post 10, Post 9, Post 8
(insert Post 11)
page 2:  Post 8, Post 7, Post 6      <- Post 8 appears twice

New rows shift everything down, so the boundary moves. A delete does the opposite and silently skips an item. For a feed, that means duplicates; for an export, it means missing records.

It gets slower with depth. OFFSET n makes the database find and throw away n rows. I loaded 500,000 rows into SQLite and timed the average of 20 runs (better-sqlite3 13.2.0, in memory):

OFFSET 0          0.007 ms
OFFSET 100,000    0.267 ms
OFFSET 480,000    1.307 ms

On a networked database with wider rows, the gap is larger. Offset cost grows with how deep you go, so the last page is the most expensive.

Cursor pagination

A cursor is a marker for “where I stopped”. The client asks for items after it:

type Query {
  posts(first: Int = 3, after: String): PostConnection!
}

The server decodes the cursor to a position and queries from there. With an auto-increment id ordered descending, a cursor can just hold the last id seen:

SELECT * FROM posts WHERE id < ? ORDER BY id DESC LIMIT ?

This is keyset pagination: the WHERE clause uses an index to start right after the marker instead of counting rows. On the same 500,000 rows:

keyset near the start        0.004 ms
keyset deep (id < 20000)     0.003 ms
plan: SEARCH posts USING INTEGER PRIMARY KEY (rowid<?)

The cost no longer depends on depth. It is stable too. I fetched page 1 (Post 10, 9, 8), inserted a new post, and fetched with after set to the cursor of Post 8:

page 2:  Post 7, Post 6, Post 5      <- continues exactly where page 1 ended

A cursor points at a row, not at a position, so inserts above it do not move it.

The trade-off: you cannot jump to page 7 without walking there, and “total number of pages” needs a separate count query. The cursor approach fits infinite scroll and feeds well and numbered pagers poorly. Michael Staib’s talk on relative cursors, linked below, tries to bridge that gap. For the REST side of the same trade-offs, see pagination, filtering and sorting.

Make cursors opaque

Encode the position into a string the client treats as a black box. In the demo I used base64 of post:<id>:

const enc = (s) => Buffer.from(s).toString('base64url');
const dec = (s) => Buffer.from(s, 'base64url').toString();
const cursor = enc(`post:${post.id}`);   // "cG9zdDo4" for post 8

If clients are told “this is an id”, they will construct their own, and you can never change the scheme. Opaque means you are free to change the sort key later. Base64 is not security; if the cursor must not be forgeable, sign or encrypt it.

Sorting needs a tiebreaker

Suppose posts are sorted by created_at, and several share a timestamp. A cursor on created_at alone loses rows at the boundary. With seven posts, four of which share one timestamp, and three per page:

cursor on created_at only:   p1 p2 p3 p5 p6 p7     (p4 never appears)
cursor on (created_at, id):  p4 p3 p2 p1 p6 p5 p7  (every row once)

The second form orders by created_at DESC, id DESC and compares the pair: WHERE (created_at, id) < (?, ?). Always end the sort with a unique column, and put both values in the cursor.

Bounds and validation

Always cap first, or a client can ask for a million rows. A first: 500 against my demo with a limit of 50 was rejected. A plain Error came back to the client masked as Unexpected error., so throw a GraphQLError with a clear message when you validate arguments. A default (first: Int = 10) keeps casual queries cheap.

What the video covers

Caleb Curry’s “API Pagination - Offset and Cursor Pagination Explained - Backend Engineering” is a 26-minute video from September 2025. Its chapters include: what is pagination, page-based pagination, offset-based pagination with its limitations (at 12:27), cursor-based pagination (13:56) with its limitations (18:06), client-side pagination and a closing exercise. It is about REST-style APIs in general, not GraphQL, so it supplies the two models and this lesson supplies the GraphQL fields and the measurements. The next lesson turns the cursor idea into the standard GraphQL schema shape.

Where this fits

Offset and cursor are the two models. GraphQL clients and tools standardised on one shape for cursors, with edges and page info. Next: Relay connections.

Check yourself

  1. 01What went wrong when I fetched page 2 of an offset-paginated list after inserting a new post?

    The insert pushed every item down one slot, so the first item of page 2 was the last item of page 1. The same item appeared twice. A deletion would skip an item.

  2. 02Why is a deep offset slow?

    The database cannot jump to row 480,000; it reads and discards the rows before it. A keyset query uses an index to start right after the last-seen key, so its cost stays flat.

  3. 03Why should a cursor be opaque to the client?

    The client then cannot depend on its contents, so you can change how it is built, for example the sort key, without breaking anyone. Base64 of a private format is a common choice.

  4. 04Sorting by `created_at` where many rows share a value, what must the cursor also contain?

    A unique tiebreaker, usually `id`, with the query ordered and compared on both. Without it, rows that tie across a page boundary are skipped; I saw one disappear.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark