Cursor-Based Pagination
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-10-14
Problem Statement
Designing a cursor-based pagination system for an API that returns large datasets (e.g., posts, transactions, or search results). Unlike offset-based pagination, cursor-based pagination provides a stable, efficient, and scalable way of navigating through results without performance degradation when data grows.
Functional Requirements
1.Pagination Query
•API should support queries of the form:
•getItems(limit, cursor)
•cursor indicates where to resume fetching (e.g., last item ID, timestamp).
•limit specifies the number of items per page.
2.Cursor Generation & Encoding
•Generate cursors for results consistently (e.g., based on ID or createdAt).
•Cursor should be opaque to the client (e.g., base64 encoding).
•Must support both nextCursor and previousCursor.
3.Stability
•Ensure results are consistent even when new records are inserted or deleted during pagination.
•Avoid duplication or skipping of records across pages.
4.Edge Cases
•Empty dataset.
•Last page (no next cursor).
•First page (no previous cursor).
5.Extensibility
•Should work across multiple entities (posts, messages, transactions).
•Should support sorting (e.g., by time, relevance).
Non-Functional Requirements
•Performance: Fetch queries must be efficient for very large datasets (better than OFFSET-based).
•Scalability: Should work well with distributed databases or sharded data.
•Security: Cursor values should not expose sensitive internal details (use encoding).
•Concurrency: Handle pagination consistently even when new items are added between requests.
Design Hints for Interview
•Treat data as ordered list (sorted by ID or timestamp).
•Cursor = pointer to the last item in the current page.
•Use encoded cursor objects (e.g., Base64(lastSeenId)).
•Classes to think about:
•Paginator → generates cursors and fetches items.
•Cursor → encapsulates position info (id/timestamp, encoding/decoding).
•Repository → fetches items efficiently from DB (with WHERE id > lastId LIMIT N).
Example Scenario
•Data: [ID=1, ID=2, ID=3, ID=4, ID=5, ID=6]
•Query: getItems(limit=2, cursor=null)
•Returns [1,2], nextCursor=2
•Query: getItems(limit=2, cursor=2)
•Returns [3,4], nextCursor=4
•Query: getItems(limit=2, cursor=4)
•Returns [5,6], nextCursor=null (end reached).
✅ This problem is great for LLD discussions because it touches class design, clean APIs, edge case handling, and DB efficiency trade-offs.