Pagination: offset vs cursor

Why you need it

A feed can hold millions of posts, so the app asks for a few at a time, a page. If pages are numbered by position, new posts push everything along and you see the same post twice, or miss one. Deep pages also get slower and slower.

Think of it like this

Marking your place in a book. Writing "I was on page 120" breaks if someone adds pages at the front. Putting a bookmark on the actual page you were reading always works.

Where you’ll find it

  • Slack: Moved its API to cursor-based pagination after numbered pages became slow and unreliable.
  • Stripe: Pages through payments with starting_after: "give me the ones after this ID".
  • GitHub: Its GraphQL API pages with cursors: each page returns an endCursor to ask for the next one.

What to know first

Page. One small slice of a long list, like 20 posts.

Offset. How many items to skip from the start. "Offset 40, limit 20" means items 41 to 60.

Cursor. A marker that points at a real item, like "post 9812", so the next page starts right after it.

How it works

  1. Offset: ask by position. "Skip 20, give me 20." In SQL that is LIMIT 20 OFFSET 20. It is easy, and you can jump straight to page 50.
  2. Offset breaks when the list moves. If 3 new posts arrive while you read page 1, everything shifts by 3. Page 2 now starts with 3 posts you already saw. This is the repeat in the animation.
  3. Offset gets slow deep down. To skip 100,000 rows the database still reads them, then throws them away. Page 5,000 is far slower than page 1.
  4. Cursor: ask by item. "Give me 20 posts older than post 9812." New posts at the top cannot shift that. With an index on the post ID (Indexes (B-tree)) the database jumps straight there, so page 5,000 is as fast as page 1.
  5. What cursors give up. You cannot jump to page 50; you can only go next or back. For feeds and infinite scroll that is fine. Cursors are usually sent as an opaque string, so the server can change what is inside later.

An example

You open a feed and see posts 100 down to 81 (page 1, offset 0).

Three new posts arrive: 103, 102, 101.

Offset asks for "skip 20, take 20" and gets 83 down to 64. You see 83, 82 and 81 again.

Cursor asks for "20 older than post 81" and gets 80 down to 61. No repeats, no gaps.

Further reading