Paging Through a Huge Ledger Without Gaps or Slowdowns
System DesignModel answerLast 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
- Clients can choose the page size. The default is 50 and the maximum is 100.
- 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.
- 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
transactionstable has these columns:transaction_id,user_id,amount, andcreated_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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer covers
The core point is that offset pagination degrades with depth and drifts under writes, while keyset pagination does neither. A complete answer also covers a strict total order, a matching composite index, an opaque cursor, and the subtle late-commit case.
1. Clarify scope and scale
Assumptions I would state out loud:
- Billions of rows overall; heavy users have around 10M each.
- Roughly 20k page requests per second at peak, most for the first page (newest data).
- Writes of about 5-10k per second globally, with bursts from a single user that can share a timestamp.
- Latency target: p99 under 50 ms for any page.
- Default order is newest first, with an optional oldest-first flag.
- Out of scope: total counts and "jump to page N". I would confirm this, since it is what makes keyset viable.
2. API design
GET /v2/users/{user_id}/transactions?limit=50&cursor=<opaque>&order=desc
limit: default 50; values above 100 are clamped or rejected with 400.cursor: absent on the first call.- Optional
start_time/end_timefilters, which also give a "seek to date" capability.
Response:
{
"data": [
{"transaction_id": "8f3c...", "amount": "-12.50",
"created_at": "2024-05-01T12:00:00.123456789Z"}
],
"pagination": {"next_cursor": "eyJ2Ijox...", "has_more": true, "limit": 50}
}
Design points:
- Opaque, signed cursor. Base64 of
{version, created_at_ns, transaction_id, order, filter_hash}plus an HMAC. The server rejects tampered cursors, cursors from another user, or cursors used with different filters. Opacity lets you change internals later. - Cheap
has_more. Querylimit + 1rows; the extra row signals another page and is dropped from the response. - No
total_count. Counting millions of rows per request would break the latency goal.
3. Storage and indexing
CREATE TABLE transactions (
transaction_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
amount NUMERIC(38,18) NOT NULL,
created_at_ns BIGINT NOT NULL, -- epoch nanoseconds
deleted_at TIMESTAMPTZ,
PRIMARY KEY (user_id, transaction_id)
) PARTITION BY HASH (user_id);
CREATE INDEX idx_user_time ON transactions
(user_id, created_at_ns DESC, transaction_id DESC)
WHERE deleted_at IS NULL;
- Timestamp precision. PostgreSQL
timestamptzstores microseconds, so nanosecond precision needs aBIGINTof epoch nanoseconds (format it back to ISO-8601 in responses). - Tie-breaker. Timestamps collide. Appending a unique
transaction_idmakes(created_at_ns, transaction_id)a strict total order. - Partitioning by
user_id. One user's history lives in one partition or shard, so every page is a single B-tree range scan. Optionally sub-partition by time for archival. - Covering index.
INCLUDEthe returned columns if heap fetches become the bottleneck, enabling index-only scans.
4. Offset vs. keyset
Offset:
SELECT ... FROM transactions
WHERE user_id = $1
ORDER BY created_at_ns DESC, transaction_id DESC
LIMIT 50 OFFSET 500000;
Keyset:
SELECT ... FROM transactions
WHERE user_id = $1 AND deleted_at IS NULL
AND (created_at_ns, transaction_id) < ($2, $3)
ORDER BY created_at_ns DESC, transaction_id DESC
LIMIT 51;
| Offset | Keyset | |
|---|---|---|
| Cost of a deep page | Scans and discards all skipped rows, so it grows linearly with depth | One index seek plus a short range scan, O(log n + limit) |
| New inserts at the head | Rows shift down, causing duplicates | Unaffected; the cursor is a value, not a position |
| Deletes | Rows shift up, causing skipped records | Unaffected |
| Jump to page N | Easy | Not directly supported |
| Complexity | Low | Needs composite index, tie-breaker, cursor encoding |
Offset fails requirements 2 and 3; keyset meets both. The row-value comparison (a, b) < (x, y) is native to PostgreSQL and uses the composite index well, which is generally better than an expanded OR condition.
5. Concurrent inserts
Inserts at the head (the common case). With newest-first order and a cursor meaning "older than (ts, id)", new rows land above the cursor. Later pages never include them and nothing shifts, so there are no duplicates or gaps. To show new items, the client requests "newer than the first item I saw" using a before cursor returned with page one, or via polling or push.
Late-visible commits (the subtle case). Transaction A gets timestamp T1 but commits slowly; B gets T2 > T1 and commits first. A reader may move beyond T1 before A is visible and will never see A. Mitigations:
- Assign the ordering key at commit or finalization time from a monotonic source per user shard.
- Or serve only rows older than a visibility watermark (for example
now() - 2s, or the start of the oldest in-flight transaction), and deliver newer rows through the "new since" path once stable. - If business timestamps can be backdated (e.g. a late settlement), paginate on an insertion sequence and keep
created_atas a display field.
Snapshot consistency. Each page is its own query, which is acceptable because the keyset order is stable. For exports needing a point-in-time view, embed an as_of upper bound in the first cursor and apply it on every page.
6. Extras and trade-offs
- Bidirectional paging: store direction in the cursor, flip the comparison and
ORDER BY, then reverse the rows before returning. - Hot first page: short-TTL cache per user or a read replica. Older pages are immutable, so replica lag is harmless for them.
- Cursor versioning: include a version field so the format can evolve.
- Soft deletes: the partial index excludes deleted rows; a row deleted mid-scan simply disappears.
- Rate limiting: cap requests per user to protect against scraping.
Common mistakes
- Proposing keyset on
created_atalone, which drops or repeats rows that share a timestamp. - Using
timestamptzand claiming nanosecond precision. - Index column order that does not match the filter and sort (
user_idmust come first). - Returning a raw
(ts, id)cursor that clients can forge or depend on. - Offering
total_countor arbitrary page jumps without acknowledging the cost. - Ignoring late-committing rows, which silently disappear from a client's view.