Pagination in system design: offset vs cursor
Pagination splits a long result into pages so a client can fetch it a piece at a time. Offset pagination (skip N rows, take the next 20) is simple and allows jumping to page 7, but it slows down on deep pages and repeats or skips items when data changes between requests. Cursor pagination, also called keyset pagination, remembers where the last page ended and asks for rows after that point, which stays fast and stable, and is the usual answer for feeds and large APIs.
By Evin JohnPublished 9 min read
1. What pagination is for
No client should receive a hundred thousand records in one response. Pages bound the size of each reply, the memory on the server, the time a database query holds resources and the bytes sent to a phone. The design questions are how the client asks for the next page, what the server must remember between requests (ideally nothing), and what the user sees when the underlying data changes while they scroll.
2. Why it appears in interviews
Almost every API in a design has a list endpoint: a timeline, search results, a user's files, a chat history. Interviewers ask "how does the client get the next page?" to see whether you know that offset paging degrades on large tables and misbehaves on live data. It is a small question with a crisp right answer, which makes it a good filter. It also connects to bigger topics: indexes, sharding, and the shape of your API (see REST vs gRPC).
3. Offset pagination
SELECT id, created_at, title
FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 4000;- Good: trivial to implement, the client can jump to any page number, and a page count is easy to show.
- Slow on deep pages: most databases must walk past the first 4,000 rows to return the next 20. Cost grows with the offset, so page 10,000 can take far longer than page 1.
- Unstable on live data: if a new post arrives between page 1 and page 2, everything shifts down by one and the last item of page 1 appears again at the top of page 2. A deletion does the opposite and an item is never shown.
Offset is still the right call for small, slow-changing lists where users expect page numbers, such as an admin table of a few thousand rows.
4. Keyset (cursor) pagination
Instead of a row count to skip, the client sends back the sort values of the last item it received. The server asks for rows that come after those values in sort order. With an index on the sort columns, the database jumps straight to that position, so page 10,000 costs the same as page 1. New rows at the top do not move the position, so nothing repeats.
import base64, json, sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE posts (id INTEGER PRIMARY KEY, created_at INTEGER NOT NULL)")
db.execute("CREATE INDEX posts_feed ON posts (created_at DESC, id DESC)")
db.executemany("INSERT INTO posts VALUES (?, ?)",
[(i, 1000 + i // 2) for i in range(1, 11)]) # some equal timestamps
def encode(row): return base64.urlsafe_b64encode(json.dumps(row).encode()).decode()
def decode(tok): return json.loads(base64.urlsafe_b64decode(tok))
def page_keyset(limit, cursor=None):
if cursor is None:
rows = db.execute("SELECT created_at, id FROM posts "
"ORDER BY created_at DESC, id DESC LIMIT ?", (limit,)).fetchall()
else:
ts, last_id = decode(cursor)
rows = db.execute("""SELECT created_at, id FROM posts
WHERE (created_at < ?) OR (created_at = ? AND id < ?)
ORDER BY created_at DESC, id DESC LIMIT ?""",
(ts, ts, last_id, limit)).fetchall()
nxt = encode(list(rows[-1])) if len(rows) == limit else None
return [r[1] for r in rows], nxt
def page_offset(limit, offset):
return [r[0] for r in db.execute(
"SELECT id FROM posts ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?", (limit, offset))]
# Offset: page 1, then a new post arrives, then page 2
p1 = page_offset(4, 0)
db.execute("INSERT INTO posts VALUES (11, 2000)")
print("offset:", p1, page_offset(4, 4)) # [10, 9, 8, 7] [7, 6, 5, 4] <- id 7 twice
# Keyset: the same sequence of events
db.execute("DELETE FROM posts WHERE id = 11")
ids, cur = page_keyset(4)
db.execute("INSERT INTO posts VALUES (11, 2000)")
ids2, cur2 = page_keyset(4, cur)
ids3, cur3 = page_keyset(4, cur2)
print("keyset:", ids, ids2, ids3, cur3) # [10, 9, 8, 7] [6, 5, 4, 3] [2, 1] NoneTwo details make it correct. First, the sort must be unique: two posts can share a timestamp, so the primary key is added as a tie-breaker, both in ORDER BY and in the WHERE condition. Without it, the page boundary can fall between rows with equal timestamps and some of them are never returned. Second, the index must match the sort order, here (created_at DESC, id DESC). Some databases accept the compact row comparison WHERE (created_at, id) < (?, ?); check that yours uses the index for it.
What keyset gives up
- No jumping to page 57. You can only go forward (or backward, by reversing the sort) from a known position. Infinite scroll and "load more" do not need more.
- Sorting by arbitrary columns needs an index per sort. Each allowed sort order needs a matching index and its own cursor fields.
- Rows edited after you passed them are not shown again. For a feed, that is usually what you want.
5. Page tokens in the API
Do not expose raw column values as query parameters. Encode the cursor (the last sort values, perhaps the sort direction and filters) into an opaque string and return it with the page. The client sends it back unchanged. Opaque tokens let you change the encoding later, and a signed or encrypted token stops clients from crafting cursors to probe data they should not see.
GET /v1/users/42/posts?limit=20
200 OK
{
"items": [ ...20 posts... ],
"next_page_token": "WzEwMDMsIDdd"
}
GET /v1/users/42/posts?limit=20&page_token=WzEwMDMsIDdd
200 OK
{ "items": [ ... ], "next_page_token": null } <- last page- Cap the page size on the server (for example a default of 20 and a maximum of 100) regardless of what the client asks for.
- Signal the end with a missing token, not by returning an empty page the client has to request.
- Bind the token to its query. If filters change, the old token should be rejected rather than silently applied to a different query.
- GraphQL APIs often follow the connection style: edges with a cursor per item and a pageInfo object with hasNextPage and endCursor. Same idea, different envelope. More in GraphQL interview questions.
6. Totals, deep pages and other hard cases
| Case | The problem | Reasonable answer |
|---|---|---|
| Showing "1,234,567 results" | COUNT(*) over a large filtered set can cost more than the page itself | Show an estimate, "1,000+", or count once and cache it; many products drop the exact total |
| Users jumping to the last page | Offset at the end of a huge table is the slowest query | Offer "newest" and "oldest" sorts instead of a last-page button |
| Search results | Ranking scores change and engines cap deep paging | Limit how deep users can page; for exports, use the engine's scroll or search-after style cursor |
| A paginated list across shards | Each shard has its own order | Ask each shard for its next page after the cursor and merge, or page within one shard key (for example one user's posts) |
| Snapshot consistency | A user wants a list that does not change while paging | Page as of a timestamp or snapshot ID stored in the token, where the store supports it |
| Backward paging | Users go back up a chat history | Reverse the comparison and sort, then reverse the page before returning it |
Merging across shards is a good place to show care. If each of 8 shards returns its next 20 items after the cursor and the server merges them, it can return the top 20 of 160 and must remember, in the token, a position per shard or simply the last global sort value. A shard key that keeps one user's data together, as in sharding, avoids the merge for the most common list.
7. How it shows up in common prompts
| Prompt | The list | Approach |
|---|---|---|
| Home timeline and a user's posts | Keyset on (time, post ID); timelines are precomputed, so the cursor indexes into the cached list | |
| File storage | Files in a folder, change history for sync | Keyset by name or ID for listings; a change-log cursor for sync |
| Notification system | A user's inbox of notifications | Keyset on (created_at, ID), newest first |
| Search autocomplete | Suggestions | No pagination: a fixed top-k per prefix |
| Older messages in a chat | Backward keyset on the message sequence number within the conversation |
8. Interview questions on pagination
| Question | Gist of a good reply |
|---|---|
| Offset or cursor for an infinite-scroll feed? | Cursor: constant cost per page and no repeats when new posts arrive |
| Why does OFFSET get slow? | The database still reads every skipped row before returning the page |
| What goes inside a cursor? | The last item's sort values including a unique tie-breaker, encoded opaquely |
| Two items have the same timestamp. What breaks? | A page boundary between them can drop or repeat one; add the ID to the sort |
| How would you support page numbers? | Offset for small lists; for large ones, ask whether users really need them |
| How do you paginate across shards? | Per-shard cursors merged on the server, or a shard key that keeps the list on one shard |
| Do you return the total count? | Only if cheap; otherwise an estimate or "more available" |
| What if filters change mid-scroll? | Start again from the first page; reject tokens issued for different filters |
9. Mistakes to avoid
- Sorting by a non-unique column only. Equal values at a page boundary go missing or repeat.
- No index matching the sort. Keyset without the right index is just a slow query with a different WHERE clause.
- Trusting client page sizes. A limit of 100,000 is a denial of service request.
- Exposing internal IDs or offsets as the token. Clients start depending on the format and you cannot change it.
- Exact counts by default. A counter on every list call can cost more than the data.
10. How to talk about it in the interview
- When you write a list endpoint in the API section, add a limit and a page token without being asked.
- Say keyset, name the sort key with its tie-breaker, and name the index that serves it.
- Mention what happens when items are added while the user scrolls.
- If the data is sharded, say whether the list lives on one shard or needs a merge.
Fictional example
- Interviewer
- Customers can scroll back through years of orders. How do you paginate that?
- Candidate
- Orders are sharded by customer ID, so one customer's history lives on one shard. The endpoint takes a limit, capped at 50, and a page token. The token encodes the placed_at time and order ID of the last order shown.
- Candidate
- The query asks for orders older than that pair, sorted by placed_at then order ID, both descending, using an index on (customer_id, placed_at, order_id). Every page costs the same however far back they scroll.
- Interviewer
- Do you show the total number of orders?
- Candidate
- I would keep a per-customer counter updated when an order is placed, since it is cheap here. If it were a search over all orders I would show an estimate instead.
Rehearsing API details with Natively
Pagination is the kind of detail candidates know but forget to say. A mock interview where Natively transcribes your answer makes the omission visible: read the transcript afterwards and look for the moment you wrote a list endpoint without a limit or a token. While the mock is running you can press for a suggested answer to the interviewer's last question, or for likely follow-ups, and it can sketch an API or data flow as a diagram in its reply. Notes from the session are saved on your computer alongside the transcript.
Questions people ask
What is the difference between offset and cursor pagination?
Offset pagination skips a number of rows and returns the next page, so it supports page numbers but gets slower on deep pages and repeats or skips items when data changes. Cursor (keyset) pagination returns rows after the last item's sort values, so each page costs the same and inserts ahead of the cursor do not shift it. Cursor paging cannot jump to an arbitrary page.
Why is OFFSET slow on large tables?
To return rows 4,001 to 4,020, most databases must still find and step past the first 4,000 rows in sort order. The work grows with the offset, so deep pages get steadily slower. Keyset pagination avoids this by seeking directly to the last seen position through an index.
What should a pagination cursor contain?
The sort values of the last item returned, including a unique tie-breaker such as the primary key, and often the sort direction and filters the token belongs to. Encode it as an opaque string, and sign it if clients must not tamper with it.
Should an API return the total count with paginated results?
Only when it is cheap. Counting a large filtered set can cost more than fetching the page, so many APIs return an estimate, a flag saying more results exist, or a count kept up to date separately.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
