API pagination determines how clients retrieve large result sets without excessive response sizes, slow queries, or inconsistent data. This guide compares page-number, offset, cursor, and keyset pagination, then provides implementation templates, failure checks, and a reusable test checklist for building or integrating REST APIs safely.
Overview
Pagination splits a collection into smaller responses. A client requests one portion of the collection, processes it, and then follows information in the response to request the next portion. The right method depends on how frequently the underlying data changes, how deeply clients need to browse, how the database sorts records, and whether the API must support reliable full-dataset extraction.
Page-number pagination usually exposes a page and page-size parameter, such as ?page=3&per_page=25. Offset pagination exposes the number of records to skip, such as ?offset=50&limit=25. These approaches are straightforward and work well for small or relatively stable collections, but inserts and deletes can shift later results while a client is paging through them.
Cursor pagination returns a continuation token based on the current position. A request might look like ?limit=25&after=eyJpZCI6MTI1fQ. The token is normally treated as opaque: clients store it and send it back rather than parsing or modifying it. Cursor pagination is often a good default for feeds, activity streams, and collections that change frequently.
Keyset pagination uses the values of an ordered, indexed key to find the next records. For example, a query ordered by created_at and id can request rows after the last pair seen. A cursor may encode those same values, so cursor and keyset pagination can overlap in implementation. The important distinction is that keyset describes the database navigation strategy, while a cursor describes the continuation value exposed by the API.
| Method | Typical request | Strength | Watch for |
|---|---|---|---|
| Page number | page=4&per_page=25 | Easy to understand and document | Results can move when records change |
| Offset | offset=75&limit=25 | Simple navigation and random access | Deep offsets may become expensive; shifting rows can repeat or skip records |
| Cursor | after=token&limit=25 | Stable continuation for changing collections | Usually supports sequential navigation rather than arbitrary page jumps |
| Keyset | after_created_at=...&after_id=... | Efficient ordered traversal with suitable indexes | Requires a deterministic, correctly indexed sort |
Before choosing a method, define what “next page” means. Decide whether the endpoint promises a snapshot-like traversal, accepts changes during pagination, supports ascending and descending order, and returns a maximum page size. Document these decisions in the API contract; an OpenAPI validation workflow can help keep request and response examples aligned with the implementation.
Checklist by scenario
Choose page-number or offset pagination when simplicity matters
- Use page numbers for administrative screens, reports, or small collections where users need to jump to a visible page.
- Use offset and limit when clients need familiar database-style controls and the collection is stable enough that movement is acceptable.
- Set a server-side maximum for
limitorper_page; do not allow an unbounded request to determine response size. - Return consistent metadata, such as the requested limit, the number returned, and links or a flag indicating whether more records exist.
- Define behavior for offsets beyond the end: normally return an empty collection rather than an error.
Choose cursor pagination for feeds and changing collections
- Return a cursor in a clearly named field such as
next_cursor, and provide a next link when that fits the API style. - Treat the cursor as opaque and allow it to carry the ordering state, filters, direction, or other validation data the server needs.
- Make cursor requests repeatable enough for clients to retry safely. If a cursor expires or becomes invalid, return a documented client error with a recovery path.
- Decide whether newly inserted records should appear in a traversal that has already started. State the behavior rather than leaving clients to infer it.
- Use separate parameters or a documented convention for previous-page navigation; do not assume that reversing a cursor is automatically safe.
Choose keyset pagination for efficient ordered traversal
- Choose a sort order that is deterministic. A timestamp alone may not be unique, so add a unique tie-breaker such as an ID.
- Use a matching database index where practical. The filter and order should support the intended access pattern instead of forcing a large scan.
- For ascending order, the next query commonly selects rows greater than the last sort tuple; for descending order, it selects rows less than that tuple.
- Encode the last sort values into a cursor when exposing them directly would couple clients to database details.
- Keep filtering consistent between requests. Changing a search term or tenant scope while reusing a cursor can produce missing or misleading results.
Use a consistent response shape
A response should make continuation unambiguous. One practical shape is:
{
"items": [
{ "id": "a101", "name": "Example" }
],
"pagination": {
"limit": 25,
"next_cursor": "opaque-token",
"has_more": true
}
}
For offset-based APIs, replace or supplement next_cursor with offset, next_offset, or documented links. Avoid returning a total count by default if calculating it is costly or unnecessary for the client. If a total is provided, document whether it is exact, filtered, and calculated at request time.
What to double-check
- Stable ordering: Every paginated query needs an explicit order. Without one, database execution may return records in an order that changes between requests.
- Unique tie-breakers: If the primary sort value can repeat, append a unique column. The pair
(created_at, id)is more reliable thancreated_atalone. - Boundary operators: Confirm whether the next query uses greater-than or greater-than-or-equal comparisons. Including the boundary incorrectly can duplicate the last record; excluding the wrong boundary can skip it.
- Concurrent changes: Insertions before an offset can push records into later pages, while deletions can pull records backward. Cursor or keyset traversal usually reduces this specific problem, but it does not create an immutable snapshot by itself.
- Filter consistency: Preserve every filter, authorization scope, tenant condition, and sort direction across requests. A continuation token should be rejected or safely handled when its original context no longer matches.
- Encoding: If cursors travel in URLs, encode them as URL-safe values and avoid exposing sensitive query state. The URL encoder and decoder guide is useful when diagnosing malformed query strings.
- Contract accuracy: Document parameter types, defaults, maximum limits, empty-page behavior, invalid-cursor errors, and response fields. Validate representative JSON with the JSON formatter and validation guide during development.
When investigating a suspected pagination defect, capture the exact request URL, authenticated scope, sort order, response IDs, and continuation value. Compare adjacent pages as a set: look for duplicates, gaps, and unexpected order changes rather than checking only the page length.
Common mistakes
- Using an unstable default order: A query without an explicit order can make pagination appear randomly inconsistent.
- Assuming page numbers are permanent positions: Page 3 is a position in a changing result set, not a durable identifier for a fixed group of records.
- Allowing arbitrary limits: A large limit can create slow queries, oversized responses, and avoidable memory pressure. Enforce a reasonable ceiling and communicate it.
- Exposing database cursors as an API promise: Clients should not depend on internal IDs, timestamps, or cursor encoding details unless the contract explicitly supports them.
- Counting before every response: An exact total may cost more than the page retrieval and is often unnecessary for “load more” interfaces.
- Testing only an unchanged database: Insert and delete records between page requests in tests. Also test identical sort values, empty collections, one-record collections, invalid cursors, and a final page whose size is below the limit.
- Retrying without considering side effects: Read pagination is normally safe to retry, but any endpoint that combines retrieval with mutations needs separate idempotency and transaction decisions.
For related integration debugging, use a repeatable process for status codes and response bodies rather than treating every empty page as a server failure. The HTTP status code reference provides a useful framework for separating request, authorization, validation, and server errors.
When to revisit
Revisit the pagination design before a major increase in collection size, a new sorting or filtering requirement, a database migration, or a change from an internal consumer to a public API. Also review it when clients report duplicates, missing records, slow deep pages, or inconsistent “load more” behavior.
Use this practical review checklist:
- Record the endpoint’s intended ordering, consistency expectations, and maximum page size.
- Run a full traversal against a realistic dataset and verify that every expected ID appears exactly as intended.
- Repeat the traversal while inserting and deleting records between requests.
- Inspect query plans and response timings at shallow, middle, and deep positions.
- Check that OpenAPI examples, SDK behavior, frontend requests, and server defaults all describe the same pagination contract.
- Document a migration path if changing from offset to cursor pagination; changing parameter names and navigation behavior can require coordinated client updates.
As a general rule, start with offset or page-number pagination when the collection is modest and user navigation is the priority. Prefer cursor or keyset pagination when clients traverse changing or large collections sequentially. Whatever you choose, stable ordering, explicit boundaries, bounded requests, and tests that simulate concurrent changes matter more than the parameter names alone.