Sub topic 6
Serving the feed with cursor pagination
This chapter assumes you know HTTP APIs, basic SQL, and the fan-out models from earlier chapters. You should also know that a timeline is a list of (timestamp, post_id) references. Here you design the API call that returns one page of that list at a time.
Why offset pagination breaks on feeds
A feed is a list that changes at the head. New posts arrive at the top while the user scrolls down. Offset pagination (LIMIT 20 OFFSET 40) asks for "items 41 to 60". If three new posts arrive between page 2 and page 3, every item shifts down by three. The user sees the last three items of page 2 again as duplicates.
Offset paging has a second cost. The database must walk past all skipped rows before it returns the page, so deep pages get slower.
Cursor pagination fixes both problems. The client sends back a marker for the last item it saw, and the server returns items strictly older than that marker.
The cursor
A cursor is a position in the sort order, not a row number. For a feed sorted newest first, the position is (created_at, post_id). Timestamps alone are not unique, because two posts can share a millisecond. Adding post_id as a tie-breaker gives a total order, so no item is skipped or repeated at a boundary.
Clients should treat the cursor as an opaque string. Encode it so you can change its contents later without breaking clients.
import base64
import json
def encode_cursor(created_at, post_id):
raw = json.dumps([created_at, post_id]).encode()
return base64.urlsafe_b64encode(raw).decode()
def decode_cursor(cursor):
created_at, post_id = json.loads(base64.urlsafe_b64decode(cursor.encode()))
return created_at, post_id
cursor = encode_cursor(1700000000123, 98765)
print(cursor)
print(decode_cursor(cursor)) # (1700000000123, 98765)The API shape
A typical request and response look like this:
- Request:
GET /v1/feed?limit=20&cursor=<opaque>. The first page omitscursor. - Response: a list of items, a
next_cursor, and optionally ahas_moreflag. - Limits: cap
limiton the server, for example at 50, whatever the client asks for.
The server returns next_cursor built from the last item in the page. When there are no more items, it returns no cursor.
Keyset query on the database
When the feed is read from the posts table (fan-out on read, or the pull side of a hybrid design), the cursor becomes a keyset condition:
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 comparison (created_at, post_id) < (...) jumps straight to the right place if an index covers the sort order. A composite index on (author_id, created_at, post_id) supports this per author. The cost of a page no longer depends on how deep the user has scrolled.
Cursors over a cached timeline
With fan-out on write, the timeline lives in a cache as a sorted list of (timestamp, post_id) pairs. The same idea applies, but you search the list instead of using SQL.
def page_from_timeline(feed, cursor=None, limit=20):
"""feed: list of (timestamp, post_id), newest first."""
if cursor is None:
start = 0
else:
# first entry strictly older than the cursor
start = next((i for i, item in enumerate(feed) if item < cursor), len(feed))
page = feed[start:start + limit]
next_cursor = page[-1] if start + limit < len(feed) and page else None
return page, next_cursor
feed = [(105, "p5"), (104, "p4"), (103, "p3"), (101, "p1"), (100, "p0")]
page1, cur = page_from_timeline(feed, limit=2)
# A new post arrives at the head. The cursor still points at the same place.
feed.insert(0, (106, "p6"))
page2, cur = page_from_timeline(feed, cur, limit=2)
print(page1) # [(105, 'p5'), (104, 'p4')]
print(page2) # [(103, 'p3'), (101, 'p1')]Page 2 contains no duplicates even though a new post was inserted at the head. The linear scan is fine for a demonstration. A real cache such as a Redis sorted set would do the same lookup by score, in logarithmic time.
How the pieces flow
The timeline stores only references. The service then hydrates them, meaning it looks up the full post data by ID, before it responds.
Common errors
- Using only a timestamp as the cursor. Posts that share a timestamp get skipped at page boundaries.
- Using
OFFSETin the SQL fallback path. The duplicates and slow deep pages come back. - Building the cursor from a post that was later deleted. Because the cursor is a position and not a lookup, it should still work. Do not require the cursor's post to exist.
- Returning a cursor on the last page, which gives clients one extra empty request.
- Putting a ranked feed behind a plain time cursor. Ranked order is not time order, so a time cursor no longer describes a position. The ranking chapter covers how to handle that.
Exercise
A feed is sorted by createdat only, and the cursor is the createdat of the last item on the page. Two posts share the exact same created_at, and one is the last item on page 1. What goes wrong, and how do you fix it?
Show answer
The next query asks for items with createdat strictly less than the cursor, so the second post with the same timestamp is never returned. It is skipped. The fix is to add a unique tie-breaker such as postid, sort by (createdat, postid), and use the pair as the cursor with a row comparison.
Exercise
Why does cursor pagination keep the same cost for page 50 as for page 1, while OFFSET does not?
Show answer
The cursor condition lets the database seek directly into an index at the cursor position. OFFSET makes the database read and discard all skipped rows first, so cost grows with depth.