Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 158/ 160
08. Backend

Pagination

Cursor and offset pagination for listing traces, docs, and eval results.

BeginnerCursor · Offset3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Pagination gives you a long list a handful of items at a time, with a bookmark telling the server where to continue, so you never download everything at once.

Think of it like…

Reading a long ledger with a bookmark. Offset pagination is "open to page 250", which means counting pages from the front each time and losing your place if pages are inserted; a cursor is a bookmark placed after the last entry you read, so you pick up exactly there however the ledger grows.

Where you’ve seen it

The traces list holds 50 million rows. A client asking for page 250,000 with limit=20 uses OFFSET 4,999,980: even with an index the database walks and discards almost 5 million index entries (seconds of work), and the cost rises linearly with the page number. A cursor query reads the same 20 rows by seeking into the index on (created_at DESC, id DESC): about a millisecond at any depth. Offsets also misbehave under writes: a user views items 1 to 20, then 5 new traces arrive at the top; page 2 via OFFSET 20 now returns items that were 16 to 35, so items 16 to 20 appear twice. A cursor continues strictly after the last seen item and shows no duplicates or skips. The API accepts limit (default 20, maximum 100, validated) and returns {"data": [...], "next_cursor": "eyJ0IjoiMjAyNi0xMS0yMVQwOToyNzowMFoiLCJpIjoidHJfOTEifQ", "has_more": true}. The cursor is the URL-safe base64 of {"t": created_at, "i": id} (the unique tiebreaker prevents skipping rows that share a timestamp) with an HMAC so clients can't tamper with it, and clients treat it as opaque. The query fetches limit + 1 rows; if 21 come back, has_more is true and the extra row is dropped. A total count is not returned by default because COUNT(*) over 50 million rows takes seconds; the API offers an approximate count (from table statistics) or computes counts asynchronously. For sorting by a non-unique field such as latency_ms, the cursor carries (latency_ms, id) and the index matches. Filters (tenant_id, status) are part of the index prefix, and a cursor is only valid with the filters it was issued for. Cursors expire after 24 hours if they reference a snapshot, and the UI uses infinite scroll or next/previous buttons rather than page numbers.

Words you’ll hear

Offset pagination
Skipping a number of rows with OFFSET and taking LIMIT more.
Cursor / keyset pagination
Continuing from the last item's sort key instead of counting rows.
Stable order
A deterministic, unique sort such as (created_at, id) that never repeats or skips rows.
has_more
A flag that tells the client whether another page exists.

Visual diagram

Loading interactive diagram

Theory & deep dive

Offset versus cursor in practice

Offset pagination is simple: SELECT ... ORDER BY created_at DESC LIMIT 20 OFFSET 40. It supports jumping to arbitrary pages and showing page numbers, but it has two flaws. Performance: the database must produce and discard all skipped rows, so page 250,000 of a 50-million-row table (OFFSET 4,999,980) scans nearly five million index entries while page 1 reads 20; latency grows with depth. Consistency: if rows are inserted at the top while a client pages, later offsets shift: after 5 new items arrive, page 2 repeats items that were previously the last five of page 1; deletions cause skips.

Cursor (keyset) pagination removes both. Order by a unique, indexed sequence such as (created_at DESC, id DESC) and ask for rows after the last one seen: WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT 21. The database seeks directly to the position in the index, so cost is constant regardless of depth, and the result is stable because the cursor identifies a position, not a count. The cost is flexibility: no jumping to page N, and arbitrary sort orders need matching indexes. Use offsets only for small, bounded lists (admin tables of a few hundred rows); use cursors for anything unbounded.

Duplicates under offset

Client has seen items 1–20. Five new items arrive at the top. OFFSET 20 LIMIT 20 now returns what are items 16–35 in the old numbering, so items 16–20 appear twice. With a cursor after item 20, the next page starts at item 21 regardless of the five new arrivals.

Key takeaway: Use keyset cursors with a unique sort order for large or changing lists; reserve offsets for small static ones.

Designing the contract: cursors, limits, counts and sorting

A good contract: limit with a default (20) and maximum (100) enforced by validation; a response object {data: [...], next_cursor, has_more} rather than a bare array so fields can be added; and an opaque cursor, typically the URL-safe base64 of the sort key values plus a signature (HMAC) so clients can't forge or edit it. The server fetches limit + 1 rows; if it gets limit + 1, has_more is true and the extra row is discarded, avoiding an extra query. Bind the cursor to the filters and sort it was created for and reject mismatches with a 400 and a clear error, because a cursor from one query is meaningless in another.

Total counts are costly: COUNT(*) on 50 million rows takes seconds and may be inconsistent anyway, so return has_more by default, offer an approximate count from table statistics where useful or compute exact counts asynchronously. Sorting by a non-unique column such as latency_ms needs a cursor of (latency_ms, id) and an index on the same columns in the same direction; sorting by arbitrary user-chosen fields multiplies indexes, so limit the sortable set. For bidirectional navigation return prev_cursor as well. Plan for evolution: adding fields to items is safe, changing the sort or cursor format requires a version. For streams of new data (live trace views) consider polling with after=<cursor> or a streaming API. Test with data inserted during paging, ties on the sort key and the maximum limit.

Cursor contents

Decoded cursor: {"t":"2026-11-21T09:27:00Z","i":"tr_91","f":"status=error"} plus an HMAC. Next query: WHERE status = 'error' AND (created_at, id) < ('2026-11-21T09:27:00Z', 'tr_91') ORDER BY created_at DESC, id DESC LIMIT 21.

Key takeaway: Return a signed opaque cursor, cap limits, fetch one extra row for has_more and avoid default total counts.

How it works, step by step

Step 1 of 4
Backend engineer

1. Choose a stable unique order

Pick a sort such as (created_at DESC, id DESC) and create the matching composite index.

(created_at DESC, id DESC)
Key numbers at this step
Tiebreaker
id

When to use it & trade-offs

What it is

Pagination returns a long list in pieces. Offset pagination uses limit and offset (?limit=20&offset=40): easy to build and to jump to a page, but the database must skip all earlier rows, and rows inserted or deleted between requests shift the pages. Cursor (keyset) pagination returns an opaque next_cursor that encodes the last item's sort key, and the next query asks for rows after it (WHERE (created_at, id) < (:ts, :id) ORDER BY created_at DESC, id DESC LIMIT 21); it stays fast at any depth and is stable under concurrent writes. A stable, unique sort order is required in both, and a response shape such as {data, next_cursor, has_more} tells clients when to stop. AI backends paginate traces, conversations, documents, jobs and evaluation results, all of which grow without bound.

Why it matters: Without pagination a list endpoint returns megabytes, times out and exhausts memory; with naive offsets it gets slower with every page and shows duplicates or gaps when new data arrives. Tables of traces and messages reach tens of millions of rows quickly, so a design that works at 10,000 rows fails in production. A well-defined pagination contract also protects clients from breaking changes and keeps database cost predictable.

When to reach for it

  • Trace, message and job list endpoints
  • Evaluation result browsers with filters
  • Exports and sync feeds

When to avoid or be careful

  • Unbounded list responses
  • Offsets on tables with millions of rows
  • Sorting by a non-unique field without a tiebreaker

Pagination styles

Offset and limit
Best for: Small, bounded lists and numbered pages

Strengths: Simple; random access to pages.

Watch out: Slow at depth; duplicates and skips under writes.

Cursor (keyset)
Best for: Large, growing lists and infinite scroll

Strengths: Constant cost; stable under writes.

Watch out: No random page jumps; needs matching indexes.

Time or ID range (after=)
Best for: Syncing and incremental feeds

Strengths: Very simple for clients.

Watch out: Requires a monotonic, unique field.

Interview signals & numbers to know

When this topic comes up

  • “Why is page 10,000 so slow?”
  • Cursor versus offset pagination
  • Why a unique tiebreaker is needed
  • Duplicates when data changes
  • Why not return a total count

Benchmarks & rules of thumb

≈ 5 million -
entries scanned by OFFSET 4,999,980 on a 50M-row table
limit + 1 -
rows fetched to decide has_more
20 default · 100 max -
a common limit policy

Common mistakes & follow-ups

Common interview mistakes

  • Exposing raw offsets that clients depend on forever.
  • Using only created_at, so rows with equal timestamps vanish between pages.
  • Letting clients send arbitrary limits.

Likely interviewer follow-ups

  • How would you paginate sorted by latency?
  • How do you support a previous-page button?
  • How would you give users a total count cheaply?
Interview tip: Name the duplicate-items failure of offsets; it is the concrete bug that justifies cursors.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Pagination with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
File Uploads to S3
Next topic
Input Validation with Pydantic