← Back to System Design, page 2

system-design-0026 · Medium fresher

Compare offset-based and cursor-based pagination. Why do large feeds use cursors?

Offset pagination uses LIMIT and OFFSET; it is simple and supports jumping to page N, but large offsets are slow because the database still walks the skipped rows, and new rows shift pages, causing duplicates or gaps. Cursor (keyset) pagination remembers the last item's sort key and asks for rows after it, which stays fast at any depth and is stable when data changes.

Full answer

Offset pagination

GET /posts?limit=20&offset=40 SELECT ... ORDER BY created_at DESC LIMIT 20 OFFSET 40;

Easy to build, and a UI can show "page 1, 2, 3 ... 50". Two problems:

  1. Performance: for OFFSET 100000, the database reads and throws away 100,000 rows. Deep pages get slower and slower.
  2. Shifting data: if a new post is added at the top while a user reads page 1, everything moves down by one, so page 2 repeats the last item of page 1. Deletes cause skipped items.

Cursor (keyset) pagination

The response includes a cursor that encodes where the page ended. The next request asks for items after that point using an indexed condition:

sql
SELECT id, created_at FROM posts
WHERE (created_at, id) < (:last_created_at, :last_id)
ORDER BY created_at DESC, id DESC
LIMIT 20;

id is a tie-breaker so two posts with the same timestamp are not lost. With an index on (created_at, id), the database seeks straight to the position, so page 1,000 is as fast as page 1.

A small demonstration (Python 3.13 with SQLite 3.46.1, same output on two runs). A new post arrives between page 1 and page 2:

python
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE posts (id INTEGER PRIMARY KEY, created_at TEXT, title TEXT)")
db.executemany("INSERT INTO posts VALUES (?, ?, ?)",
               [(i, f"2026-12-01 10:{i:02d}", f"post {i}") for i in range(1, 8)])

def page(cursor=None, limit=3):
    if cursor is None:
        rows = db.execute("SELECT id, created_at FROM posts "
                          "ORDER BY created_at DESC, id DESC LIMIT ?", (limit,)).fetchall()
    else:
        c_time, c_id = cursor
        rows = db.execute("SELECT id, created_at FROM posts "
                          "WHERE (created_at, id) < (?, ?) "
                          "ORDER BY created_at DESC, id DESC LIMIT ?",
                          (c_time, c_id, limit)).fetchall()
    next_cursor = (rows[-1][1], rows[-1][0]) if len(rows) == limit else None
    return [r[0] for r in rows], next_cursor

ids, cur = page()
print(ids, cur)
db.execute("INSERT INTO posts VALUES (8, '2026-12-01 10:08', 'new post')")  # arrives between pages
ids, cur = page(cur)
print(ids, cur)
print("offset page 2:", [r[0] for r in db.execute(
    "SELECT id FROM posts ORDER BY created_at DESC, id DESC LIMIT 3 OFFSET 3")])

Output:

[7, 6, 5] ('2026-12-01 10:05', 5) [4, 3, 2] ('2026-12-01 10:02', 2) offset page 2: [5, 4, 3]

The cursor version continues cleanly with 4, 3, 2. The offset version shows post 5 again.

API shape

Return an opaque cursor (base64 of the sort key) rather than raw values, so the server can change its format later:

json
{"items": [{"id": 4}, {"id": 3}, {"id": 2}], "next_cursor": "eyJ0IjoiMjAyNi0xMi0wMSAxMDowMiIsImlkIjoyfQ", "has_more": true}

Trade-offs

Cursors cannot jump to "page 37" and need a stable, indexed sort order. Offset is fine for small admin tables with page numbers. Infinite-scroll feeds, chat history and public APIs with large lists should use cursors.

By level

Fresher: Explain offset pagination, why deep pages get slow, and the idea of continuing from the last item seen. The fresher answer should mention both slowness and duplicate items.

Mid: Write a keyset query with tie-breaker, explain the index needed, opaque cursors and duplicates under concurrent inserts. Expect the tie-breaker column and the matching index.

Senior: Discuss pagination across shards and search indexes, bidirectional cursors, cursor expiry and consistency snapshots, and API contracts for large exports. Expect a plan for merging pages from several shards.

Key points

  • Offset is simple and allows page jumps but is slow at depth
  • Offset pages shift when rows are inserted or deleted
  • Cursor pagination seeks from the last seen sort key using an index
  • Add a unique tie-breaker such as id to the sort key
  • Return opaque cursors in the API

Common mistakes

  • Using a non-unique sort key without a tie-breaker
  • Exposing raw SQL values as the cursor format
  • Using offset pagination for infinite-scroll feeds
  • Sorting by a column that is not indexed

Follow-ups

  • How would you support "previous page" with cursors?
  • How do you paginate results merged from several shards?
  • How do you paginate when the sort is by score instead of time?

Tips

  • Explain both performance and correctness problems with offset
  • Write the keyset WHERE clause with a tie-breaker
  • Say when offset is still fine

Evaluation rubric

  • Correct explanation of both approaches
  • Identifies performance and shifting-data issues
  • Correct keyset query with tie-breaker and index
  • Recognises trade-offs