KatInterview

Keyset Pagination Design for High-Volume Event Logs

System DesignModel answer
MediumModel answerSystem Designpaginationapi-designdatabase-indexing

Last 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

  1. Propose the request and response format, including the structure of the cursor token.
  2. Define the database schema and indexing strategy.
  3. Show the SQL query pattern for fetching the first page and for fetching a page given a cursor.
  4. Explain how authorization is enforced so that a user cannot use a cursor to access another user's data.
  5. 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?