Keyset Pagination Design for High-Volume Event Logs
System DesignModel answerLast updated
Design a cursor-paginated API for a large append-only event ledger that avoids offset pitfalls and stays stable under concurrent inserts.
You are building a read-heavy REST API on top of an append-only event ledger that stores billions of records. Clients need to scroll through large result sets sorted newest-first, and the system must remain fast and correct even as new events arrive continuously.
What to Design
A paginated endpoint that returns events in descending order by event_time, using event_id as a tie-breaker so ordering is fully deterministic. The API should use cursor-based navigation rather than traditional offset/limit pagination.
Requirements
Functional
- Clients can fetch the first page and continue to subsequent pages using a cursor token returned by the server.
- Results are sorted by
event_time DESC, event_id DESC. - Each user only sees events belonging to their own scope (e.g., their organization or account).
Non-Functional
- Page fetches must stay constant-time regardless of how deep the client has scrolled. No linear scan of skipped rows.
- If new events are inserted while a client is mid-pagination, the client should not see duplicated or skipped records within the logical sort order.
- Target p99 read latency under 50 ms at tens of thousands of concurrent requests per second.
Deliverables
- Propose the request and response format, including the structure of the cursor token.
- Define the database schema and indexing strategy.
- Show the SQL query pattern for fetching the first page and for fetching a page given a cursor.
- Explain how authorization is enforced so that a user cannot use a cursor to access another user's data.
- Discuss what happens when events arrive with timestamps older than the cursor position (late-arriving events) and how you would handle that edge case.
Hints
Hint 1
Think about why ORDER BY ... LIMIT N OFFSET M degrades as M grows, and how a cursor avoids scanning discarded rows.
Hint 2
The cursor must encode enough sort-key information to seek directly to the next position in the index. What fields does it need?
Hint 3
Consider what happens when a row is inserted with a timestamp between two pages the client already fetched. How do you keep the snapshot consistent?
Hint 4
The cursor is client-visible and tamper-prone. What prevents a user from swapping in someone else's scope identifier?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarifying Assumptions
I would start by confirming scale and access patterns with the interviewer:
- Data volume: roughly 2B rows, with the largest accounts holding up to 10M events each.
- Write rate: ~5k appends/sec at peak. Rows are immutable; corrections are posted as new entries, never updates or deletes.
- Read traffic: ~20k page requests/sec. p99 latency target is 50 ms regardless of page depth.
- Page size: default 20, max 100. Clients scroll forward through newest-first. Backward navigation is a nice-to-have, arbitrary jumps are a follow-up.
Why OFFSET fails. LIMIT 20 OFFSET 1000000 forces the database to walk and discard a million index entries before returning the first row, so cost grows linearly with depth. It is also unstable: if 5 rows are inserted at the head between requests, every subsequent row shifts down and the next page repeats records the client already saw. Deletions cause skips.
Keyset pagination fixes both. It remembers where you stopped (a value in the sort key) instead of how many rows you have passed. The database seeks directly to that position in the B-tree, giving O(log N + page_size) regardless of depth.
2. API Design
GET /v1/accounts/{account_id}/events?limit=20&cursor=
Authorization: Bearer <token>
{
"data": [
{"event_id": "1044", "event_time": "2021-06-29T20:53:19.482113Z",
"payload": { ... }}
],
"page": {
"next_cursor": "eyJ2IjoxLCJ0cyI6...",
"has_more": true,
"limit": 20
}
}
Design decisions:
- Omit
cursorfor the first page. When results are exhausted,next_cursorisnullandhas_moreis false. - Detect
has_moreby fetchinglimit + 1rows. If the extra row comes back, return onlylimitrows and sethas_more = true. This avoids a separateCOUNT(*)query. - Return IDs as strings to prevent 64-bit integer precision loss in JavaScript clients.
- The cursor is a base64url-encoded JSON payload like
{"v":1,"ts":1625000000,"id":1045,"acct":"A123","f":"<filter_hash>"}, signed with an HMAC key to prevent tampering. Include a format version for future migration.
3. Schema and Indexing
CREATE TABLE events (
event_id BIGINT NOT NULL,
account_id BIGINT NOT NULL,
event_time TIMESTAMPTZ NOT NULL,
payload JSONB,
ingest_seq BIGINT NOT NULL,
PRIMARY KEY (event_id)
);
CREATE INDEX ix_events_acct_time_id
ON events (account_id, event_time DESC, event_id DESC);
The index column order is the critical decision:
account_idgoes first because it is the equality predicate. This narrows to one account's partition of the B-tree.- Sort columns follow in the exact query sort order, so each account's rows form one contiguous, pre-sorted range.
- A page fetch is a single index seek plus a scan of ~21 entries: O(log N + limit), constant regardless of depth.
Optional refinement: add INCLUDE (payload) to make it a covering index, avoiding heap lookups entirely. At this scale, partition the table by account_id hash or time range; the query shape stays the same.
4. Query Logic
First page (no cursor):
SELECT event_id, event_time, payload FROM events
WHERE account_id = :acct
ORDER BY event_time DESC, event_id DESC
LIMIT :limit + 1;
Subsequent page (after decoding cursor (ts, id)):
SELECT event_id, event_time, payload FROM events
WHERE account_id = :acct
AND (event_time, event_id) < (:ts, :id)
ORDER BY event_time DESC, event_id DESC
LIMIT :limit + 1;
The composite row-value comparison means "strictly after the last row returned" in descending order. The tie-breaker on event_id is essential: many events can share one timestamp. Using event_time < :ts alone would skip same-timestamp rows, and <= would duplicate them.
For databases that do not support row-value comparisons (older MySQL), use the expanded form:
AND (event_time < :ts
OR (event_time = :ts AND event_id < :id))
Encode the timestamp as integer microseconds in the cursor, not a float or truncated ISO string. A rounded cursor silently skips or repeats rows.
5. Authorization
Never trust the cursor for access control. Derive account_id from the authenticated principal, not from the URL or cursor payload. The data-access layer must inject account_id = :acct as a mandatory predicate before the query runs.
Bind the cursor to its context: include account_id and a hash of the active filter set in the HMAC-signed payload. On decode, verify the signature and reject the request if the cursor's account does not match the authenticated user's entitlement. This prevents replaying one user's cursor against another account.
A tampered, expired, or context-mismatched cursor returns 400 Bad Request.
6. Late-Arriving Events
Rows inserted with a newer timestamp than anything already seen land before the cursor position. Since traversal goes newest-first, the client never revisits that region, so these are neither skipped nor duplicated.
The subtle case is late-arriving rows: a card settlement posted hours later with an older event_time. If it lands behind the cursor, the client misses it. If it lands ahead, they see it mid-traversal.
Options:
- Snapshot high-water mark. On the first page, record
max_seq = current max(ingest_seq)in the signed cursor. AddAND ingest_seq <= :max_seqto every page. The traversal becomes a consistent snapshot: rows ingested after it started never appear. The client refreshes from the top to see new rows. This filter is a cheap residual predicate since it rejects very few rows. - Accept and document. For newest-first feeds where eventual visibility is fine, late-arriving rows simply appear on the next refresh.
- Sort by ingest order (
ingest_seq DESC) instead of business time when the use case allows, eliminating the late-arrival problem entirely.
A strong answer raises the late-arrival issue unprompted and recommends option 1 for financial ledgers where consistency matters.