Reliable API pagination is less about choosing a fashionable pattern and more about matching the method to the data, ordering rules, and consistency guarantees your client needs. This guide compares offset, cursor, and keyset pagination, then provides practical checklists for implementing clients that avoid missed records, duplicates, runaway requests, and fragile retry behavior.
Overview
Pagination divides a large result set into smaller responses. A client requests one page, processes it, and follows a navigation value or constructs the next request until the collection is complete. The API may express pagination through query parameters such as limit and offset, links such as next, or opaque cursors returned in a response. GraphQL APIs commonly expose connection-style fields with edges, nodes, and page information, while REST APIs can use several conventions. The contract—not the client’s assumptions—should determine how pagination works.
| Method | How it works | Strengths | Trade-offs | Good fit |
|---|---|---|---|---|
| Offset | Requests a page number or number of records to skip, usually with a limit. | Easy to understand, inspect, and implement. | Deep offsets may become expensive; inserts and deletions can shift later pages. | Small or mostly static collections, administrative screens, and simple reports. |
| Cursor | Uses a token supplied by the API to identify the next position. | Can hide storage details and support efficient traversal. | Cursors may expire, be opaque, or depend on a particular filter and sort order. | High-volume feeds and APIs that provide an explicit next cursor. |
| Keyset | Uses values from the last row, such as an ID and timestamp, to request records after that position. | Efficient for ordered traversal and more stable under inserts. | Requires a suitable indexed, unique ordering and careful boundary logic. | Large database-backed collections where the client controls query parameters. |
Offset pagination is often the simplest starting point, but it is not automatically wrong for changing data. It becomes risky when a client expects a stable snapshot while records are being inserted, deleted, or reordered. Cursor pagination is usually safer when the provider defines the cursor’s behavior. Keyset pagination is a database query strategy rather than a universal API format, so it must be documented clearly when exposed to clients.
For every method, establish a deterministic sort order. Sorting only by a non-unique field, such as creation time, can produce ambiguous boundaries when multiple records share the same value. Add a unique tie-breaker, such as an immutable ID, when the API contract permits it. A conceptual keyset query might be WHERE (created_at, id) > (:last_created_at, :last_id) ORDER BY created_at ASC, id ASC. The exact syntax depends on the database and API.
Checklist by scenario
When integrating an unfamiliar REST endpoint
- Read the endpoint documentation for the default page size, maximum page size, supported filters, and allowed sort fields.
- Determine whether the response includes a next link, cursor, total count, or an indication that no more pages remain.
- Follow the server-provided next link or cursor rather than reconstructing an opaque token.
- Preserve the original filters and sort order on every subsequent request.
- Set a client-side maximum page count or item budget so a malformed termination condition cannot create an unbounded loop.
- Record the request ID, page token, response status, and item count in diagnostic logs without exposing credentials.
When the collection changes during traversal
- Ask whether the API offers snapshot, consistency, or point-in-time semantics. If it does not, treat the result as a moving view rather than a fixed export.
- Prefer cursor or keyset traversal with a stable immutable ordering when the endpoint supports it.
- Decide whether duplicates are tolerable. If processing is not naturally idempotent, maintain a short-lived set of processed IDs or use a durable checkpoint.
- Expect records deleted during traversal to disappear and avoid treating every missing record as a client failure.
- For strict exports, consider a server-side snapshot, an export endpoint, or a captured cutoff such as a maximum update time.
When implementing retries
- Retry transient transport failures and explicitly documented temporary server responses according to the service contract.
- Reuse the same cursor or offset after a failed request; do not advance the checkpoint until the page has been successfully processed.
- Use bounded exponential backoff with jitter where appropriate, and honor any server-provided retry guidance.
- Make page processing idempotent. A response may be received by the client but fail before the checkpoint is saved.
- Separate request retry limits from the overall job deadline.
When building a GraphQL client
- Inspect the schema and documentation for connection fields, page size arguments, and page information such as
hasNextPageandendCursor. - Request only the fields needed for the current workflow; large nested selections can make each page expensive.
- Pass the returned end cursor as the next request’s
aftervalue instead of deriving a cursor from a node ID. - Check whether nested connections have independent pagination. A page of parent objects does not necessarily fetch every child object.
- Define behavior for null cursors, empty edges, partial errors, and authorization changes between requests.
For generated clients, confirm how the SDK exposes pagination. Some libraries provide an iterator, while others return a single page and require manual continuation. Read the generated types and test the behavior rather than assuming the SDK automatically fetches every record. An OpenAPI review can help expose inconsistent page parameters and response schemas before client generation; see the OpenAPI specification review checklist.
What to double-check
Ordering: The order must be explicit, repeatable, and compatible with the pagination boundary. If sorting can change between requests, a cursor may no longer represent the same position.
Filters: Apply identical filters to every page. A common bug occurs when the first request includes a status or date filter but the follow-up request uses only the cursor and silently drops it.
Limits: Treat the server’s page-size limit as authoritative. Requesting a larger page does not guarantee that the server will honor it, and an empty page is not always proof that the collection has ended unless the contract says so.
Cursor scope: An opaque cursor can be tied to an endpoint, user, filter set, sort order, or expiration window. Store it with enough context to detect accidental reuse in a different job.
Checkpointing: Save progress after successful processing, not merely after receiving a response. For batch jobs, store the cursor, filter version, sort definition, and processing timestamp together.
Data comparison: When diagnosing missing or duplicated records, capture two payloads and compare their IDs, ordering fields, request parameters, and continuation values. A JSON diff and validation workflow can make this investigation more systematic.
Load behavior: Test first-page, middle-page, final-page, empty-result, and maximum-limit cases. Also test slow responses, timeouts, repeated pages, expired cursors, and records inserted around the traversal boundary.
Common mistakes
- Using page numbers as durable checkpoints: Page 4 is not a stable position when earlier records can be inserted or deleted. Prefer a cursor or keyset boundary for resumable jobs.
- Sorting by a non-unique field: Equal timestamps or names need a deterministic tie-breaker, or records can move between pages.
- Incrementing before processing: Advancing an offset or cursor before durable processing can skip data after a crash.
- Assuming “no items” always means completion: Follow the documented termination signal. Some APIs can return empty pages because of filtering, permissions, or an unusual boundary.
- Deduplicating only in memory: A process restart removes the protection. Use an idempotency key, durable record state, or an appropriate database constraint for important jobs.
- Ignoring deletions and updates: A client that expects a frozen dataset may report normal changes as corruption. Define whether the workflow needs a snapshot or simply a best-effort traversal.
- Logging sensitive URLs: Cursors and query strings may contain user or operational data. Redact credentials and review whether tokens should be persisted in logs.
Pagination failures can also look like unrelated integration problems. If a webhook triggers a paginated follow-up job, apply the same duplicate-event and retry discipline described in this webhook testing and debugging guide.
When to revisit
Revisit this checklist before seasonal planning cycles, large data imports, migrations, or any workflow expected to process substantially more records. Review it when an API provider changes its SDK, page-size limit, cursor format, sort options, authentication behavior, or error responses. A backend release that adds new indexes, changes default ordering, introduces soft deletion, or modifies timestamp precision can also affect keyset boundaries.
Make pagination part of release testing rather than a one-time integration task. Keep fixtures for duplicate sort values, records inserted during traversal, deleted records, empty results, expired cursors, and partial failures. Run a small end-to-end test after changing filters or ordering, then compare expected IDs with processed IDs. For a production job, monitor page counts, retry rates, repeated cursors, termination failures, and the difference between received and successfully processed records.
Before shipping, use this short action list:
- Document the pagination method, stable ordering, page-size behavior, and termination signal.
- Write a client loop that advances only after successful processing.
- Add bounded retries and make processing idempotent.
- Test inserts, deletions, retries, empty pages, and concurrent updates.
- Store enough checkpoint context to resume safely.
- Recheck the API contract whenever the provider, SDK, filters, or backend query changes.
The best pagination method is the one whose consistency and failure behavior are explicit. Choose offset for straightforward, limited collections; use a provider-defined cursor when the API offers one for changing or high-volume data; and use keyset boundaries when you control the query and can guarantee a stable, indexed order. Then verify the choice with tests that reflect how the data actually changes.