Sub topic 6
Serving the feed with cursor pagination
This chapter covers how the feed API returns a long timeline in pages without duplicates or gaps. It assumes you know HTTP APIs, basic SQL, and the fan-out models from the earlier chapters. You should be able to read short Python and SQL.
Why pagination is harder for feeds
A feed is a list that changes while the user reads it. A user opens the app, sees 20 posts, and scrolls. During the scroll, followed accounts publish new posts, and older posts may be deleted. The client then asks for "the next page", and the server must decide what that means.
The API has three goals:
- No duplicates. A post the user already saw must not reappear on the next page.
- No gaps. A post that existed when the user started scrolling must not be skipped.
- Bounded cost. Page 50 must cost about the same as page 1.
The common first attempt is offset pagination, which breaks the first two goals on a live feed.
The problem with offset pagination
Offset pagination sends ?offset=20&limit=20. The server skips 20 rows and returns the next 20. The server counts positions, and the list shifts under it.
Suppose a user has seen posts at positions 0 to 19. Three new posts arrive at the top. The old positions 17, 18 and 19 are now positions 20, 21 and 22. The request for offset=20 returns them again, so the user sees three duplicates. Deletions cause the opposite error: a deleted post moves later items up, and the server skips one.
Offset also costs more on deep pages. A SQL OFFSET 10000 makes the database walk past 10,000 rows before it returns any.
Cursor (keyset) pagination
A cursor identifies a position by the last item the client saw, not by a count. The server returns "items strictly older than this one." Because the position is a value and not an index, new posts at the top cannot move it.
For this to work, every item needs a unique, totally ordered sort key. Timestamps alone are not unique, since two posts can share a millisecond. The usual key is the pair (created_at, post_id). The post_id breaks ties, so the order is the same on every read.
The query from the data model looks like this:
SELECT post_id, author_id, created_at
FROM posts
WHERE author_id IN (:followed_author_ids)
AND (created_at, post_id) < (:cursor_created_at, :cursor_post_id)
ORDER BY created_at DESC, post_id DESC
LIMIT 20;The row-value comparison (created_at, post_id) < (...) means "older, or the same time with a smaller id". With an index on (author_id, created_at DESC, post_id DESC), the database seeks directly to the cursor position. Page 50 costs about the same as page 1.
| Property | Offset pagination | Cursor pagination |
|---|---|---|
| Position is | A row count | A sort-key value |
| New posts at top | Cause duplicates | No effect |
| Deletions | Cause skipped items | No effect |
| Cost of deep pages | Grows with offset | Constant with an index |
| Jump to page N | Easy | Not possible |
| Client complexity | Low | Slightly higher |
The cost of cursors is that the client cannot jump to "page 7". A feed is an infinite scroll, so this rarely matters.
The API contract
A feed endpoint needs only a few parameters. A typical contract:
GET /v1/feed?limit=20returns the first page.GET /v1/feed?limit=20&cursor=<token>returns the page after the cursor.- The response contains
itemsandnext_cursor. When there are no more items,next_cursorisnull.
Some design rules follow from this:
- Make the cursor opaque. Encode it as a single string, such as base64 of a small JSON value. Clients must treat it as a token and never parse it. This lets you change the contents later, for example by adding a ranking score, without breaking clients.
- Cap
limiton the server. If a client asks for 10,000 items, return at most your maximum, such as 50. - Return
next_cursoronly when more data exists. Fetchinglimit + 1rows tells you whether another page exists without a second query. - Do not return a total count. Counting a merged, filtered feed is expensive, and the number is stale immediately.
The sequence below shows one scroll step.
Implementing cursors over a cached timeline
With fan-out on write, each user has a bounded timeline of (timestamp, post_id) references, newest first. The following code paginates over such a list.
import base64
import json
from itertools import islice
MAX_LIMIT = 50
def encode_cursor(created_at, post_id):
raw = json.dumps([created_at, post_id]).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def decode_cursor(cursor):
padded = cursor + "=" * (-len(cursor) % 4)
created_at, post_id = json.loads(base64.urlsafe_b64decode(padded))
return (created_at, post_id)
def get_page(feed, cursor=None, limit=20):
"""feed is a list of (timestamp, post_id), newest first."""
limit = max(1, min(limit, MAX_LIMIT))
if cursor is None:
candidates = iter(feed)
else:
key = decode_cursor(cursor)
candidates = (item for item in feed if item < key)
items = list(islice(candidates, limit + 1)) # one extra row
has_more = len(items) > limit
items = items[:limit]
next_cursor = encode_cursor(*items[-1]) if has_more else None
return {"items": items, "next_cursor": next_cursor}
feed = [(105, 5), (104, 4), (103, 3), (102, 2), (101, 1)]
page1 = get_page(feed, limit=2)
print(page1["items"]) # [(105, 5), (104, 4)]
# Two new posts arrive while the user is reading.
feed.insert(0, (106, 6))
feed.insert(0, (107, 7))
page2 = get_page(feed, cursor=page1["next_cursor"], limit=2)
print(page2["items"]) # [(103, 3), (102, 2)]
print(page2["next_cursor"] is not None) # TrueThe two new posts did not shift page 2. An offset of 2 on the updated list would have returned (105, 5) and (104, 4) again, both duplicates.
The list scan above is fine for an 800-entry timeline. A production cache would use a sorted structure. In Redis, a sorted set (ZSET) can hold post ids with the timestamp as the score. ZREVRANGEBYSCORE then seeks to the cursor score, but it only handles ties if you encode them. A common trick is to use a post id that is itself time-ordered, such as a Snowflake-style id. A single number then carries both time and uniqueness, and the cursor is just that id.
Cursors in a hybrid feed
In the hybrid design, a read merges the pushed timeline with posts pulled from high-follower accounts. The cursor must still be a single position. Because both sources are sorted by the same key, one (timestamp, post_id) cursor works for both.
On each request, the server does the following:
- Reads entries older than the cursor from the precomputed timeline.
- Pulls entries older than the cursor from each followed high-follower account.
- Merges the sources with a lazy k-way merge and takes
limit + 1items. - Returns the page and builds the next cursor from the last returned item.
import heapq
from itertools import islice
def hybrid_page(pushed, celebrity_posts, cursor_key=None, limit=20):
"""All sources are lists of (timestamp, post_id), newest first."""
sources = [pushed, *celebrity_posts]
if cursor_key is not None:
sources = [[x for x in s if x < cursor_key] for s in sources]
merged = heapq.merge(*sources, reverse=True)
items = list(islice(merged, limit + 1))
return items[:limit], len(items) > limit
pushed = [(105, 5), (101, 1)]
celebs = [[(104, 4), (100, 0)]]
page, more = hybrid_page(pushed, celebs, limit=3)
print(page, more) # [(105, 5), (104, 4), (101, 1)] TrueThe position is stored in the cursor itself, and the server keeps no per-user scroll state. Any API server can answer the next request, and the design survives restarts and load balancing.
Edge cases and common errors
Ties in the sort key
If you paginate on created_at alone and use <, any posts that share the cursor's timestamp are skipped. If you use <=, they are returned twice. Always add a unique tiebreaker such as post_id. This is the most common cursor bug.
Mismatched ordering and comparison
The ORDER BY columns, their directions, and the cursor comparison must agree. If you sort by created_at DESC, post_id ASC but compare with (created_at, post_id) <, the comparison does not match the order. Rows are then skipped or repeated at ties.
Deleted cursor items
A cursor refers to a position in the key space, not to a row. If the last item the client saw is deleted, the query still works, because it asks for "older than this key". Cursors do not break when their anchor row disappears. Offsets and "after this row id" lookups can break.
Items hidden after caching
The cached timeline holds references. When you hydrate them into full posts, some may be deleted, blocked, or made private. If you remove them after slicing the page, the page can contain fewer than limit items. Two safe responses:
- Over-fetch and fill: keep reading until you have
limitvisible items or the timeline ends. - Return a short page with a valid
next_cursor, and make sure the client keeps requesting whilenext_cursoris not null.
Never treat a short page as "end of feed". Only a null cursor means that.
New posts at the top
Cursor pagination protects the scroll, but it never shows new posts. The client has to ask for them separately. A common design is a second call such as GET /v1/feed?since=<newest_seen_cursor> that returns items newer than the client's top item. The client then shows a "new posts" banner and prepends them when the user taps it. This stops the list from jumping while someone reads.
Tampering and trust
Clients can edit a cursor. Treat it as untrusted input: validate that it decodes, that it has the right types, and that the timestamp is plausible. If the cursor holds anything sensitive or a ranking state you do not want forged, sign it with an HMAC and reject tokens with a bad signature. Always use parameterized queries when the cursor values reach SQL, as in the example above.
Cursors and ranking
A ranked feed does not sort by time, so a timestamp cursor no longer fits. The ranking chapter returns to this. In brief, a ranked feed either snapshots the ranked candidate list for the session and paginates by position in that snapshot, or it keeps the cursor as (score, post_id). Scores change over time, so the snapshot approach is more stable. A snapshot needs a short time to live, and the cursor then carries a snapshot id.
Choosing page size
Page size trades latency against round trips. A small page loads fast but triggers more requests while scrolling. A large page wastes bandwidth if the user stops after five posts. Most feeds use 10 to 30 items and let the client prefetch the next page when the user is about two items from the end. Whatever you choose, enforce a server-side maximum.
Summary of the design
- Use a unique, totally ordered sort key, normally
(created_at, post_id)or a time-ordered id. - Make the cursor an opaque token holding the last returned key.
- Fetch
limit + 1items to decide whether a next page exists. - Return
next_cursor = nullonly at the true end. - Keep all state in the cursor so any server can answer.
- Fetch new posts through a separate "newer than" request.
Exercise
A feed API paginates with created_at only, using the condition created_at < :cursor_created_at. A user's feed has three posts with created_at = 1000, ids 7, 8 and 9. The page size is 2, so the first page ends in the middle of this group. What goes wrong on the next page, and how do you fix it?
Show answer
The first page ends with one of the three posts at timestamp 1000, so the cursor timestamp is 1000. The next query uses created_at < 1000, which excludes the remaining posts with that timestamp, so they are skipped. Using <= would instead return the already seen post again. The fix is to add a unique tiebreaker to the sort key and cursor: order by created_at DESC, post_id DESC and filter with (created_at, post_id) < (:cursor_created_at, :cursor_post_id).
Exercise
A user fetched page 1 of a feed. Before requesting page 2, ten new posts arrived and the post at the end of page 1 was deleted. Does cursor pagination still return the correct page 2? Does offset pagination?
Show answer
Cursor pagination does. The cursor holds the key of the last item returned, and the query asks for items older than that key, so neither the new posts nor the deletion change the result. Offset pagination does not. The ten new posts shift the list, so page 2 repeats up to ten items from page 1, and the deletion shifts items the other way, which can skip one.
Exercise
Why must a client keep requesting pages until next_cursor is null, instead of stopping when a page has fewer than limit items?
Show answer
Items are removed after the timeline is read, for example posts that were deleted, blocked or made private. A page can therefore be short even though older, visible posts remain. Only a null next_cursor means the timeline has ended.