Pagination, filtering and sorting
A collection endpoint that returns everything works with 20 rows and collapses with 2 million: slow queries, huge responses, timeouts. Real APIs return collections in pages, and let clients filter, sort and choose fields with query parameters.
Offset pagination
The simplest scheme: the client asks for a page size and how many items to skip.
GET /products?limit=20&offset=40 items 41–60
GET /products?page=3&pageSize=20 the same idea, counted in pagesIn SQL that's LIMIT 20 OFFSET 40. Let's build it on a real (in-memory) database:
Note the safeguards: the page size has a default and a maximum, so nobody can ask for a million rows; and the response includes links to the next and previous pages, so clients never build URLs by hand.
The problems with offsets
- Slow deep pages:
OFFSET 900000makes the database read and throw away 900,000 rows. - Shifting results: if a new item is added while someone pages through, every item moves down one place, so they see one item twice; if an item is deleted, they skip one.
Cursor pagination
Instead of "skip N rows", the client says "give me items after this one". The cursor marks the position: here, the last id seen, encoded so clients treat it as opaque.
WHERE id > ? uses the index, so page 10,000 is as fast as page 1, and new rows never cause duplicates.
| Offset | Cursor | |
|---|---|---|
| Jump to page 7 | ✔ | ✖ (only next/previous) |
| Show "page 3 of 12" | ✔ | Hard |
| Speed on deep pages | Slow | Fast |
| Stable while data changes | ✖ | ✔ |
| Good for | Admin tables, search results | Feeds, timelines, infinite scroll, exports, sync |
Stripe, Slack, GitHub's GraphQL API and most social feeds use cursors. When sorting by something other than id (say, newest first), the cursor must contain the sort value and the id as a tie-breaker: WHERE (created_at, id) < (?, ?).
Filtering, sorting and choosing fields
Common query-string conventions:
GET /products?category=kitchen&minPrice=10&maxPrice=50 filters
GET /products?q=lamp full-text search
GET /products?sort=-price,name sort: price descending, then name
GET /products?fields=id,name,price only these fields
GET /products?include=reviews embed related resourcesOnly allow sorting and filtering on fields you've chosen (an allow-list), especially if the values end up in SQL: never paste sort straight into ORDER BY. And add database indexes for the filters and sorts you support.
Practice
- Add
pageandpageSizeparameters to the offset example and returntotalPagesinmeta. - Make the cursor example list the newest events first (
ORDER BY id DESCandWHERE id < ?). - Return 400 when
minPriceis greater thanmaxPrice.
1.Why cap the page size (e.g. at 100)?
2.What is a weakness of offset pagination?
3.How should the API treat a cursor value?