API pagination
easy 24 minPagination sends a long list in small pages.
See it run
Twelve products, three per page: count past them, or remember where you stopped.
Operations
Offset pages
page=N, limit=3. Every page reads the rows in front of it again.
Step 1 of 4
Page 1
| 1 Mouse | 2 USB-C hub | 3 Keyboard | 4 Stand |
| 5 Webcam | 6 Lamp | 7 Mouse pad | 8 Organizer |
| 9 Laptop stand | 10 Cables | 11 Hook | 12 Wrist rest |
read 3, return 3
GET /products?page=1&limit=3 becomes LIMIT 3 OFFSET 0.
Step 1: Page 1
def page(n, limit=3): offset = (n - 1) * limit return query( "SELECT * FROM products ORDER BY id LIMIT ? OFFSET ?", limit, offset)- Rows read
- offset + 3
- Jump to page
- Yes
- Keyset
- 3
The answer may carry page 1 of 4 and a total of 12. The total is a second query.
In the real world
The same api pagination doing real jobs. Pick one and step through it.
New posts arrive while somebody scrolls.
Step 1 of 4
Open the feed
Three newest posts and a cursor after 7.
Step 1: Open the feed
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No unique last sort column
criticalRows with equal values can be lost at a page border, or come in a different order each time.
WrongORDER BY created_at DESCRightORDER BY created_at DESC, id DESCSorting by one column, seeking by another
criticalThis orders by created_at and filters by id. Pages repeat and lose rows as soon as the two orders differ.
Wrongquery.order_by(created_at.desc()) .filter(id < last_id)Rightquery.order_by(created_at.desc(), id.desc()) .filter((created_at, id) < last)Unlimited page size
majorlimit=1000000 is the whole table in one answer.
Wronglimit = int(args["limit"])Rightlimit = max(1, min(int(args.get("limit", 20)), 100))Trusting the cursor
majorAnyone can decode and change plain base64, also the owner inside it.
Wrongq = json.loads(b64decode(cursor))rows = load(owner=q["owner"], after=q["id"])Rightq = verify_signature(cursor)rows = load(owner=request.user.id, after=q["id"])
Interview tips
How to explain it
- Offset counts, a cursor remembers.
- A keyset is what a good cursor holds.
- Same order, same columns, same index.
Memory trick: OCK
- Offset: old-school, skip and take.
- Cursor: continuous, where I left off.
- Keyset: keen on speed, after this id.
Offset is fine when
- The list is small.
- Page numbers are required.
- The data is calm.
Use a cursor when
- People scroll without end.
- Rows come and go.
- Anyone may ask for a deep page.