Pagination is a contract about traversing a collection, not just limiting the number of rows in a response. Clients need to know how to request the next portion, what ordering means and what happens when the collection changes during traversal. Those decisions become harder to revise once integrations depend on them.
GitHub’s REST API pagination guidance shows one concrete interface using response links and page-related parameters. It is an example to study, not a universal prescription. The design method here compares the behavior a product needs before choosing an offset, cursor or other traversal mechanism.
Start with the caller’s retrieval task
A person browsing recent activity, a synchronization worker and a full export job need different guarantees. A browsing interface may tolerate new items appearing between pages. A synchronization process may need a durable way to avoid missing changes. A full export may require a defined snapshot.
For a fictional project-management API, list the tasks served by the issues endpoint. An interface displays the newest open issues, while an integration periodically retrieves updates. It may be inappropriate to force both tasks through one pagination contract if their consistency needs differ.
Describe the expected collection size and query patterns without treating current volume as permanent. A small initial table can hide the cost of deep offsets or expensive counts. Choose a design that fits plausible growth while keeping the first implementation understandable.
Define a stable order
Every paginated collection needs an explicit ordering rule. A database returning rows without a guaranteed order is not a dependable interface. Document the field or sequence used and the direction in which results appear.
Include a tie-breaker when the primary sort field is not unique. Several records can share the same creation timestamp. A stable secondary identifier helps define their relative position and supports predictable traversal.
Consider whether the sort field can change. Sorting by last-updated time means an edited record may move while a client is paging. That may be useful for a particular view, but it changes the duplication and omission risks. Explain the behavior instead of presenting all sort options as equivalent.
Understand offset pagination’s tradeoffs
Offset pagination asks for a position in the current ordered result, often through a page number or row offset. It can be straightforward for interfaces that jump to a numbered page. The implementation and user experience are easy to explain for bounded, relatively stable collections.
However, inserting or deleting records before the current position can shift later pages. A client traversing over time may see a duplicate or miss an item. The contract should not promise a stable snapshot unless the system actually provides one.
Deep offsets can also require work that grows with the skipped portion, depending on the database and query plan. Measure the real implementation with representative filters and sizes. Do not choose or reject offset pagination solely from a slogan; connect the tradeoff to the caller’s needs and observed system behavior.
Understand cursor pagination’s contract
A cursor represents a continuation position according to the service’s rules. It can avoid some positional shifts when based on a stable ordering key, but it does not automatically solve every consistency problem. Updates to sort fields and changes to filters still need defined behavior.
Treat the cursor as an opaque value to clients. The server may encode position and query context, but clients should not construct or modify it. Protect any sensitive information and validate the token using the mechanism appropriate to the design.
Document cursor lifetime and invalidation. A cursor tied to a snapshot or temporary server state may expire. The client needs a clear error and restart strategy when that happens. An unexplained empty page is not an adequate signal that the continuation token is no longer usable.
Bind continuation to the original query
A next-page request should use the same relevant filters, sort order and authorization scope. If the client changes the query while retaining a cursor, define whether the server rejects it or starts a new traversal. Silent reinterpretation can produce surprising results.
Consider including query identity in the continuation mechanism or validating the supplied parameters against the original context. The exact implementation varies, but the contract should make incompatible reuse visible.
Account for permissions changing between requests. A record accessible on the first page may no longer be accessible later. Enforce current authorization and explain the limits of consistency where necessary. Pagination must not become a way to retain access after the underlying permission is removed.
Choose page-size limits intentionally
Set a default and a maximum page size based on response cost, memory use and client needs. Very small pages increase request overhead; very large pages can create slow responses and resource spikes. Measure representative records, including those with expensive expansion fields.
Define how invalid or excessive sizes are handled. A clear validation error and a documented maximum are easier for clients to use than inconsistent silent truncation. If the server clamps values, describe that behavior and return enough information for the client to understand the actual page.
Do not assume every item costs the same. A response that embeds related objects may grow unpredictably. Consider separate retrieval or explicit expansions when necessary, and evaluate their effect on the pagination contract rather than only on the schema.
Make continuation discoverable
Return a documented way to find the next page. This may be a link, token or structured field. A client should not have to guess whether another page exists from the number of returned items alone, unless that inference is explicitly part of the contract.
Define the end condition clearly. An absent next link, null cursor or explicit completion field can each work. Keep the behavior consistent for an empty collection and for a final page that happens to contain the maximum number of items.
If providing previous-page navigation, specify how it relates to a changing collection. Backward traversal may have different costs or semantics. Do not add controls merely because a familiar UI has them if the API cannot support them predictably.
Be careful with total counts
A total count can help a numbered-page interface, but computing it may be expensive and its meaning may change during traversal. Decide whether the count is exact, approximate or absent. Label an estimate clearly rather than returning it in a field that implies certainty.
For filtered collections, ensure the count uses the same scope as the returned items. An account-wide count alongside a filtered page can confuse users and leak information if authorization is inconsistent.
Consider whether the caller actually needs a total. A load-more interface may only need to know whether continuation is available. Removing an unnecessary count can simplify the implementation and avoid a costly query, but make the decision based on the product workflow.
Design synchronization separately when needed
A client that needs every change since a previous run may require a change feed or high-water mark rather than ordinary browsing pagination. Deletions and repeated updates complicate a list of current records. State whether the endpoint represents current state or a history of changes.
If the client uses timestamps, account for ties, precision and the possibility of changes occurring during retrieval. A naive greater-than filter can miss records at a boundary. Use a documented continuation strategy that preserves the intended sequence.
Do not promise lossless synchronization from an endpoint designed only for interactive browsing. It is better to identify the limitation and provide a suitable interface than to let integrations infer guarantees the service cannot maintain.
Test collection changes between pages
Create tests that insert, delete and update records after the first page is read. Observe duplicates, omissions and ordering under the documented model. The test should verify the promise you chose, not impose a snapshot guarantee the product never intended.
Include equal sort values, an empty collection, one item beyond the page boundary and an expired or malformed cursor. Test filters and permissions together with pagination. These combinations often expose errors hidden by a simple unfiltered happy path.
Measure deep traversal and large permitted page sizes with realistic data. Record the query plan or relevant performance evidence where appropriate. A contract that works logically but becomes unusably slow under normal growth still needs revision before broad adoption.
Explain client recovery
Tell clients how to handle temporary failures without losing their continuation state. A retry of a page request should use the same query context and token according to the contract. If results can change, recommend an application-level strategy appropriate to that uncertainty, such as recognizing stable item identifiers.
Provide a clear response for invalid continuation and explain whether the client must restart. Avoid exposing internal database details in the error. The caller needs a recovery action, not the implementation’s exception message.
A durable pagination contract makes the collection’s behavior understandable under growth and change. Ordering, continuation, consistency and recovery deserve as much attention as the page-size parameter, because those are the promises clients will build into their own systems.
Continue reading
Keep Webhook Processing Safe When Events Arrive Twice
Make Database Migrations Compatible with Rolling Deployments