How to Choose the Right Pagination Strategy for a REST API
When an API returns thousands of records, clients need a way to retrieve them in manageable pieces. The choice between cursor vs offset pagination affects more than response size: it can change query performance, navigation behavior, and whether users see duplicated or missing records as data changes.
In brief, offset pagination is straightforward and works well when clients need to jump to numbered pages or datasets are relatively stable. Cursor pagination—often implemented as keyset pagination—is usually a better fit for large, frequently changing collections that clients browse sequentially. The right choice depends on your data, database, and user experience.
What API pagination solves
An API that returns an entire collection in one response can consume excessive bandwidth and memory, increase response times, and put unnecessary load on the server. Pagination limits each response to a defined number of records and gives clients a way to request more.
If you’re new to the concept, start with what an API is and how applications use it. In a REST API, a collection endpoint might return a page of orders, articles, or users along with information that helps the client request the next page.
Pagination is not only a performance feature. It is part of your API’s public contract: clients need predictable ordering, clear navigation rules, and consistent behavior when records are added or removed.
Offset pagination: simple page numbers
Offset pagination skips a specified number of records and then returns a limited number. A common interface uses limit and offset query parameters:
GET /api/products?limit=20&offset=40
This request asks the server to skip the first 40 products in the chosen order and return up to 20. Some APIs expose the same idea as page numbers, such as ?page=3&page_size=20; the server calculates the offset from those values.
How an offset query works
A SQL query might look like this:
SELECT id, name, created_at
FROM products
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 40;
The ordering matters. Without an explicit, deterministic ORDER BY, database results are not guaranteed to appear in a consistent sequence. Adding a unique tie-breaker such as id also helps order records whose timestamps match.
Advantages and drawbacks
- Easy to understand: Clients can request a particular page or jump forward and backward.
- Easy to implement: Many databases support limit-and-offset queries directly.
- Can slow down at high offsets: The database may need to scan or discard many rows before returning the requested page. The exact cost depends on the database, query plan, indexes, and data.
- Can shift during updates: If records are inserted or deleted between requests, later offsets may return duplicates or skip records.
Offset pagination is often suitable for small or moderately sized collections, internal tools, and interfaces where jumping to a numbered page is important. It is less attractive when users scroll through very large, rapidly changing feeds.
Cursor pagination: continue from a position
Cursor pagination uses a token that represents where the previous response ended. The client sends that token to request the next set of records. The token may encode a record’s sort values, such as its timestamp and ID, or refer to server-side state.
A request might look like this:
GET /api/products?limit=20&after=eyJjcmVhdGVkX2F0IjoiLi4uIn0
The response can return a continuation token rather than a page number:
{
"data": [
{ "id": 501, "name": "Desk lamp" }
],
"page": {
"next_cursor": "eyJjcmVhdGVkX2F0IjoiLi4uIn0",
"has_more": true
}
}
Here, the cursor is an illustrative opaque value. Clients should treat it as a token to pass back, not rely on its internal format. A real API should document how to stop: for example, a missing next cursor or has_more: false.
Keyset pagination under the hood
When a cursor is based on ordered record values, the database can use a range condition instead of skipping an increasingly large number of rows. This approach is commonly called keyset pagination.
For descending order by creation time and ID, a query could be:
SELECT id, name, created_at
FROM products
WHERE (created_at, id) < (:last_created_at, :last_id)
ORDER BY created_at DESC, id DESC
LIMIT 20;
The exact comparison syntax depends on the database. An equivalent condition can be written as created_at < :last_created_at OR (created_at = :last_created_at AND id < :last_id). The ordering columns and comparison must match. A suitable index, often starting with the sort columns, can help the database find the next range efficiently.
Advantages and drawbacks
- Efficient for deep traversal: It can avoid the growing skip cost of large offsets when the query and indexes support the range lookup.
- More stable during inserts: New records before the cursor generally do not shift the position of the next page.
- Less suited to page jumping: A cursor typically means “continue from here,” not “go directly to page 12.”
- More design work: The API needs stable ordering, cursor encoding, validation, and clear continuation behavior.
Cursor pagination is not a guarantee of a frozen snapshot. Records can still be updated or deleted between requests, and changes to sort fields can move records across the cursor boundary. If a workflow requires a consistent view of a dataset, consider snapshot or transaction semantics separately.
Cursor vs offset pagination: how to decide
Start with how clients will navigate and how the collection changes. The comparison is similar to choosing between two display technologies: what matters depends on the use case, as in this guide to 240Hz vs. 144Hz. For pagination, weigh navigation needs against query behavior and data stability.
- Choose offset pagination when numbered pages and direct page access are important, the dataset is manageable, and occasional shifting results are acceptable.
- Choose cursor or keyset pagination for large feeds, event streams, activity logs, or other collections clients mainly browse forward or backward.
- Consider a hybrid when users need both rapid browsing and page-number navigation. For example, provide cursor navigation for the feed and a separate search or filtering workflow for locating older records.
Performance should be measured rather than assumed. Benchmark realistic queries against representative data, inspect query plans, and test the indexes your API will use. The discipline is familiar to anyone comparing low-level alternatives in a performance benchmark of memmove vs. memcpy: test the workload that matters, not just the names of the techniques.
Practical REST pagination design steps
- Define a stable sort order. Specify the default order and include a unique tie-breaker. Keep the order consistent across requests.
- Set a page-size limit. Choose a sensible default and enforce a maximum so clients cannot request an unbounded response.
- Design clear navigation fields. For offset pagination, document page or offset parameters. For cursors, return a next token and indicate whether more results are available.
- Keep tokens safe and opaque. Validate cursor input. If the token contains sensitive values or must not be modified, use an appropriate signed or protected representation rather than trusting arbitrary client-supplied data.
- Define filter and sort behavior. A cursor should be used with the same collection, filters, and ordering that created it. Reject or clearly handle incompatible parameters.
- Test concurrent changes. Add, delete, and update records between page requests. Check for duplicates, gaps, and documented consistency limits.
Common pagination pitfalls
- Leaving ordering implicit: Without deterministic ordering, records can appear in different positions across requests.
- Using a non-unique cursor key: A timestamp alone may not uniquely identify a position. Add a tie-breaker and include all required sort values in the cursor.
- Assuming a cursor means a snapshot: Cursor pagination improves continuation behavior, but does not automatically provide a transactionally consistent view.
- Allowing unbounded page sizes: Large responses can undermine the performance benefits of pagination.
- Changing token semantics without a plan: Treat cursors as part of your API contract. Version or otherwise manage changes so active clients are not surprised.
Conclusion
In the choice between cursor vs offset pagination, there is no universal winner. Offset pagination offers familiar page numbers and simpler navigation, while cursor pagination—often backed by keyset queries—can provide more efficient sequential access to large collections and avoid many offset-related shifts.
Choose based on real client needs, make ordering deterministic, cap page sizes, and test against realistic data and concurrent updates. A thoughtful REST pagination design gives clients reliable ways to navigate while keeping database work and response sizes under control.