Lesson 197 of 296
Pagination, filtering and sorting
What you will learn
- Why lists must be paginated
- Offset pagination and its problems
- Cursor (keyset) pagination
- Encoding cursors
- Filtering and sorting safely
- Response shapes
On this page
Why paginate?
GET /orders returning all 2 million orders would be slow, use huge memory (Lesson 190) and break clients. Every list endpoint must return results in pages with a maximum page size.
Offset pagination
GET /orders?page=3&pageSize=20 → SQL: LIMIT 20 OFFSET 40| Pros | Cons |
|---|---|
| Simple; users can jump to page 50 | Slow for deep pages: the database still reads and throws away all skipped rows (OFFSET 100000 reads 100,020 rows) |
| Easy "page 3 of 120" display with a total count | Unstable: if a new order is inserted while the user pages, items shift: the user sees a duplicate or misses one |
COUNT(*) for the total can itself be slow on big tables |
Fine for small admin tables and anywhere users need page numbers.
Cursor (keyset) pagination
Instead of "skip 40 rows", say "give me rows after this one":
GET /orders?limit=20 first page
→ { data: [...], nextCursor: "eyJjcmVhdGVkQXQiOi..." }
GET /orders?limit=20&cursor=eyJjcmVhdGVkQXQiOi...The cursor encodes the sort values of the last row seen. The SQL (Lesson 220):
SELECT * FROM orders
WHERE (created_at, id) < ($lastCreatedAt, $lastId)
ORDER BY created_at DESC, id DESC
LIMIT 21;| Pros | Cons |
|---|---|
| Fast at any depth: an index jumps straight to the position | Cannot jump to an arbitrary page number |
| Stable: new rows do not shift pages, no duplicates or gaps | Sorting by many different columns needs care |
| Ideal for feeds, infinite scroll, sync APIs, exporting |
Tie-breaker: always add a unique column (the ID) to the sort, because many rows can share the same created_at. Without it, rows with equal timestamps can be skipped or repeated.
Fetch one extra row (LIMIT 21 for a page of 20): if 21 come back, there is a next page. This avoids a separate count query.
Encoding the cursor
Make the cursor opaque to clients (they should not build or edit it), for example Base64URL-encoded JSON. Validate it when decoding, because it comes from the client:
import { z } from "zod";
const CursorSchema = z.object({ createdAt: z.iso.datetime(), id: z.string().min(1) });
export type Cursor = z.infer<typeof CursorSchema>;
export function encodeCursor(cursor: Cursor): string {
return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
}
export function decodeCursor(raw: string): Cursor | null {
try {
return CursorSchema.parse(JSON.parse(Buffer.from(raw, "base64url").toString("utf8")));
} catch {
return null;
}
}
type Row = { id: string; createdAt: string };
export function paginate<T extends Row>(sortedDesc: T[], limit: number, cursor: Cursor | null) {
const after = cursor
? sortedDesc.filter((r) => r.createdAt < cursor.createdAt || (r.createdAt === cursor.createdAt && r.id < cursor.id))
: sortedDesc;
const page = after.slice(0, limit + 1);
const hasMore = page.length > limit;
const data = hasMore ? page.slice(0, limit) : page;
const last = data[data.length - 1];
return { data, nextCursor: hasMore && last ? encodeCursor({ createdAt: last.createdAt, id: last.id }) : null };
}paginate does in memory what the SQL query does in the database; it is handy for tests and for understanding. An invalid cursor should return 400.
Filtering
GET /orders?status=paid&customerId=c_9&createdFrom=2026-01-01&minTotal=1000&q=mug- Validate every parameter with a schema (types, allowed values, maximum lengths).
- Allow-list which fields can be filtered; never build SQL from raw parameter names (SQL injection, Lesson 260). Use parameterised queries.
- Make sure common filters are indexed (Lesson 220).
- Search (
q) on large text needs full-text search (PostgreSQL full-text, Elasticsearch, OpenSearch), notLIKE '%mug%', which cannot use a normal index.
Sorting
GET /orders?sort=-createdAt,totalPenceA common convention: comma-separated fields, - for descending. Allow-list sortable fields and map them to real column names. Always add the ID as a final tie-breaker.
Response shape
{
"data": [ { "id": "ord_1" } ],
"pagination": { "nextCursor": "eyJ...", "hasMore": true, "limit": 20 }
}Or for offset pagination: { "data": [...], "page": 3, "pageSize": 20, "total": 2381 }. Some APIs use the HTTP Link header for next and previous URLs (GitHub does). Set a maximum limit (for example 100) so clients cannot request a million rows.
How to say it in an interview
"Every list endpoint is paginated with a maximum page size. Offset pagination is simple and supports page numbers but gets slow for deep pages because skipped rows are still read, and it duplicates or skips items when data changes. Cursor or keyset pagination encodes the last row's sort values in an opaque cursor and queries rows after it, which is fast at any depth and stable; I always add the ID as a tie-breaker and fetch limit plus one to know if there is a next page. Filters and sort fields are validated and allow-listed, mapped to indexed columns and passed as query parameters."
Key words
| Word | Meaning |
|---|---|
| Pagination | Returning a list in pages |
| Offset pagination | Skipping N rows (LIMIT and OFFSET) |
| Cursor / keyset pagination | Continuing after the last row's sort values |
| Opaque cursor | A token clients pass back without reading it |
| Tie-breaker | A unique column added to the sort to make order fully defined |
| Allow-list | A list of the only values that are permitted |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.