KatInterview

Paging Through a Huge Ledger Without Gaps or Slowdowns

System DesignModel answer
MediumModel answerSystem Designpaginationkeyset-paginationpostgresql

Last updated

Design a paginated transaction-history API over a PostgreSQL table with billions of rows, staying fast on deep pages and correct while new rows keep arriving.

Scenario

A payments platform wants to expose a public endpoint that returns a user's transaction history. The backing table holds billions of rows and receives writes all day long. Some power users have millions of transactions each.

Requirements

  1. Clients can choose the page size. The default is 50 and the maximum is 100.
  2. While a client is walking through pages, new transactions keep being written. The client must not see the same record twice or skip a record.
  3. Response time must stay roughly flat whether the client is on the first page or far into the past.

Assumptions

  • The primary store is a relational database such as PostgreSQL.
  • The transactions table has these columns: transaction_id, user_id, amount, and created_at (a timestamp with nanosecond precision).
  • The endpoint has to perform well even for accounts with millions of rows.

What to produce

  • The request and response shape of the API.
  • A storage and indexing plan.
  • A comparison of offset pagination and cursor (keyset) pagination for this workload.
  • An explanation of what happens when rows are inserted while a client is paging.

State your scale assumptions explicitly, and mention any edge cases you think matter.

Hints

Hint 1

Ask what offset pagination costs when the offset is in the millions, and what happens to row positions when a new row is inserted at the front.

Hint 2

A timestamp alone is not a unique ordering key. Think about what you must add so every row has a distinct, stable position, and what composite index would match the query.

Hint 3

Consider the cursor as a value (the last row's sort key) rather than a position. Also think about rows that become visible late because a transaction with an earlier timestamp committed after a later one.