When an application displays thousands of transactions, articles, notifications, or activity records, sending all the data at once is not a good choice. Responses become large, wait times increase, and the database has to work harder. Pagination breaks results into smaller chunks. For data that changes continuously, one approach worth considering is cursor pagination.
Unlike page-number-based pagination, cursor pagination uses a position marker that the client sends back when requesting more data. This pattern is commonly used in APIs serving timelines, catalogs, logs, or large search results.
What Is Cursor Pagination?
Cursor pagination fetches a set of items and returns a token indicating where the next request should continue. This token may be called cursor, next_cursor, or page_token. The client does not need to calculate page numbers; it simply passes along the token provided by the server.
For example, an endpoint returns 20 transactions and a continuation cursor. The application sends that cursor in the next request, and the server returns the collection following that position. Ideally, the cursor is treated as an opaque token: the client stores it and sends it back without attempting to modify its internal contents.
Cursor Pagination vs. Offset Pagination
Offset pagination uses parameters like limit=20&offset=1000. This approach is easy to understand and works well for small lists or when users need to jump to a specific page. However, very large offsets can force the database to skip many rows before producing data. Changes to the data while the user navigates can also cause items to be skipped or appear twice.
Cursor pagination is generally better suited for sequential, continuous data fetching. Because requests start from a marker value, performance can remain more stable on large datasets—provided indexes and queries are designed correctly. The trade-off is that jumping directly to page 50 is not as straightforward as with offset-based pagination, and implementation requires clear sorting rules.
Designing a Stable Cursor
A good cursor foundation is deterministic ordering. Do not sort data by timestamp alone if multiple records can share the same timestamp. Add a unique column as a tiebreaker, such as an ID. This way, a composite sort like created_at then id remains unambiguous.
Conceptual example: the server sorts transactions by newest time first, then by descending ID. The cursor stores the timestamp and ID of the last displayed item. The next request looks for items positioned after that value pair in the same order. The specific comparison operators depend on the sort direction and database engine being used.
Cursors do not need to carry sensitive data. If the token encodes internal values, consider an opaque format or signing so clients cannot arbitrarily change the position. Signing helps detect tampering but does not replace authorization. Every request must still verify user identity and access limits on the data.
Example API Pattern
An API response can include the data list and a cursor for the next request. The exact shape depends on the API contract, but the general pattern looks like this:
{
"data": [
{ "id": 501, "name": "Sample item" }
],
"next_cursor": "token-from-server",
"has_more": true
}
The client then requests the same endpoint with a cursor parameter, such as ?limit=20&cursor=token-from-server. When no more data follows, the server may send next_cursor as null or has_more as false. Choose one consistent contract and document how to terminate loading.
Implementation Practices to Consider
- Set a maximum limit. Cap the
limitvalue so clients cannot request thousands of items in a single response. - Use appropriate indexes. Columns used for cursor filtering and sorting need to be evaluated against the database query plan, not just assumed.
- Validate tokens. Handle broken, expired, or version-mismatched cursors with clear error responses.
- Maintain filter consistency. Cursors should be used with the same filters and ordering as the initial request. If filters change, restart from the beginning.
- Design behavior for changing data. Cursors help reduce page-shift issues but do not automatically create consistent snapshots. Define whether results may reflect the latest changes or require a snapshot mechanism.
- Avoid information leakage. Do not treat cursors as access permissions. Check user rights on every request and do not store secrets in easily readable tokens.
- Test edge cases. Verify empty datasets, items with identical timestamps, new items arriving during processing, data deletion, and repeated requests.
When Should It Be Used?
Cursor pagination is appropriate for timelines, account activity, system logs, messages, large catalogs, and APIs primarily used for sequential data retrieval. Offset pagination still makes sense for simple administrative tables that need direct page navigation and have limited data volumes.
Before choosing, measure application access patterns, dataset size, user requirements, and database capabilities. Complex cursor implementations are not always necessary for small lists. Conversely, waiting until performance degrades can make API contract changes harder because clients have already come to depend on the old format.
Conclusion
Cursor pagination is an effective strategy for fetching large data incrementally, especially when data order needs to remain stable as the dataset changes. The key to success is not merely adding a cursor parameter, but establishing consistent ordering, designing indexes, validating tokens, maintaining authorization, and documenting API behavior. Start from real requirements, test with data approaching production conditions, then monitor latency and database load to ensure the approach delivers actual benefits.

Komentar (0)
Belum ada komentar. Jadilah yang pertama berkomentar.