Compare Offset-based Pagination vs Cursor-based Pagination for large REST collections.
❓ Interview Prompt: Explain `limit` & `offset` vs `cursor` (keyset pagination), SQL performance ($O(N)$ scanning), and handling dynamic data insertions.
APIs returning large datasets must paginate responses to prevent memory overload:
| Feature | Offset Pagination ('?page=2&limit=20') | Cursor Pagination ('?cursor=eyJpZCI6NDJ9&limit=20') |
|---|---|---|
| SQL Query | 'SELECT FROM items LIMIT 20 OFFSET 40;' | 'SELECT FROM items WHERE id > 42 ORDER BY id ASC LIMIT 20;' |
| Performance | Slow $O(N)$ on high offsets (scans & drops rows) | Fast $O(1)$ constant time using indexed column |
| Data Shifts | Skips or duplicates rows if items inserted | Immune to data shifts during pagination |
| Use Case | Page numbers UI (e.g. 1, 2, 3...) | Infinite scrolling feeds (Twitter, Feed API) |
Code Implementation Example
{
"data": [{ "id": 101, "title": "Post A" }],
"pagination": {
"limit": 20,
"nextCursor": "eyJpZCI6MTAxLCJjcmVhdGVkQXQiOjE3NTM2OTkyMDB9",
"hasMore": true
}
}Use cursor-based pagination for high performance and consistent scrolling over large dynamic datasets.