Pagination Cursor Builder
Prerequisites & Dependencies
- SQL database (PostgreSQL, MySQL, SQLite) or NoSQL (MongoDB) with indexed columns
- Language runtime: Node.js 18+, Python 3.10+, or Go 1.21+
- Indexed monotonically increasing column (usually
idorcreated_at)
Execution Steps
- Identify a stable, unique, indexed column for the cursor (prefer auto-increment
idorcreated_atwith UTC timestamp) - Design the API endpoint:
GET /items?cursor=last_seen_id&limit=20 - In the query, filter with
WHERE id > last_cursor ORDER BY id ASC LIMIT limit(keyset pagination) - Return the first item's cursor to the client for the next page, and a
hasMoreflag when fewer items thanlimitare returned - Avoid
OFFSETfor large tables; keyset pagination maintains O(1) performance regardless of page depth - Support backward pagination optionally:
WHERE id < last_cursor ORDER BY id DESC LIMIT limit - Validate cursor format, sanitize input, and document the pagination contract for API consumers
-- Keyset pagination (forward)
SELECT id, title, created_at
FROM articles
WHERE id > 12345 -- cursor = last seen id
ORDER BY id ASC
LIMIT 20;
-- Response: include new cursor = (SELECT MAX(id) FROM returned rows)