Video in progress

Why do feed pages use cursor pagination instead of offset pagination?

With offset, when a new post is added the pages shift — the user sees one post twice or skips one. On top of that, a large OFFSET is slow. Cursor pagination says "give me the posts after this one": the result is stable and every page is equally fast.

📖 Answer

With offset:

SELECT * FROM posts ORDER BY created_at DESC LIMIT 20 OFFSET 40;

While the user is reading page 2, 5 new posts land at the top. When page 3 is requested, the last 5 posts of the previous page show up again. On top of that, for OFFSET 100000 the database reads 100,000 rows and throws them away.

With a cursor, the last seen post is returned to the client and sent back in the next request:

SELECT * FROM posts
WHERE (created_at, id) < (:lastCreatedAt, :lastId)
ORDER BY created_at DESC, id DESC
LIMIT 20;

With an index on (created_at, id), the database starts reading right at the needed spot. id is there so posts with the same timestamp don't get mixed up.

In the API the cursor is usually given as an opaque string (for example, base64-encoded JSON), and the client only sends it back.

The downside: you can't "jump to page 17". But in an infinite-scroll feed you don't need that anyway.