chiefletterAll stories

Building skills / CHIEFLETTER JOURNAL

Choose an API Pagination Pattern That Fits Your Data

Compare offset and cursor pagination, design stable ordering, and handle changing data without confusing clients.

A database table displayed on a computer screen
Photography via Unsplash

Decide what a page means to the client

Pagination controls how a client moves through a large collection without asking the server for every record at once. Begin with the user’s task. A person browsing recent activity may need a “load more” action. An administrator exporting a report may need predictable batches and a way to resume. A mobile screen may prefer a short list that grows as the person scrolls. The endpoint should support the job instead of exposing database internals as its contract.

Write down the maximum page size, the default size, and what happens when the client asks for more than the allowed limit. Return enough information to continue, such as a next-page link or cursor. Use consistent names and document whether the page size is approximate or exact. A client should not need to infer how to build the next request from a database offset hidden in an example.

Use a stable order before choosing a pagination method

A paginated result needs a deterministic order. Sorting by a timestamp alone is not enough if many records share the same timestamp. Add a unique tie-breaker, such as a record ID, so adjacent requests agree about the order. Without that rule, a record can appear twice or disappear between pages even when the underlying data has not changed much.

State whether newest or oldest items come first and make the sort key explicit in the endpoint contract. If clients can choose sort order, define which fields are supported and how null values sort. Do not let a client pass arbitrary database field names. Stable ordering is the foundation. Offset and cursor strategies both become confusing when the order changes between requests.

Understand the trade-off in offset pagination

Offset pagination asks for a page number or a number of records to skip. It is easy to explain and works well for small or mostly stable collections. A user can jump to page four, and a simple interface can show page counts when the server knows the total. It also maps naturally to many SQL queries and is familiar to client developers.

Large offsets may cost more because the database still has to locate or walk past preceding rows. New records inserted before the current offset can shift later pages, creating duplicates or skipped items. Deletions can shift records in the other direction. If the collection changes often or grows large, measure the query and test what happens while someone moves between pages.

Use cursor pagination for a moving collection

Cursor pagination gives the client a token representing where to continue. The token might encode the last sort key and a unique tie-breaker. The next request asks for records after that position. This pattern suits activity feeds and large collections because the query can seek from a known key rather than skip thousands of rows. New items added before the cursor usually do not shift the next page in the same way as an offset.

A cursor is part of the API contract. Treat it as opaque to the client, validate it on the server, and avoid putting private data in a readable token. Explain when a cursor expires and whether it works with the same filter and sort order only. A client should pass it back unchanged. Cursor pagination usually makes arbitrary page jumps harder, so it is not automatically the right fit for every table.

Keep page boundaries clear as records change

Decide what consistency the endpoint promises. A live feed may allow new records to appear while the client reads older pages. A report export may need a stable snapshot or a fixed upper time boundary. If the client switches a filter between requests, invalidate the old cursor. Otherwise the next page may continue a position calculated for a different collection.

Test the boundary cases: no results, exactly one full page, one record beyond a full page, deleted records, and records with equal sort values. For cursor pagination, verify that the next cursor advances and the last page has no next link. For offset pagination, insert and delete records between requests. These tests reveal contract problems that a static ten-row fixture will miss.

Make the response useful and predictable

A response should tell the client whether another page exists and how to request it. A next link is explicit. A cursor plus a `has_more` value is also clear. Avoid making clients calculate the next offset from a total count if that count is expensive or changes during browsing. Include a page size limit in documentation and return a useful validation error for malformed or incompatible cursors.

Be careful with total counts. A count over a large filtered collection can be costly and may become stale before the next request. If the interface only needs a “show more” button, a reliable next-page signal may be enough. If a user needs to know the total number of report pages, explain how fresh that number is and whether it is estimated.

Check the index that supports the chosen sort and filter. A cursor query is not automatically fast if the database must scan many unrelated rows to find the next batch. Inspect the query plan with representative data and watch for a sharp slowdown near the end of a large collection. Performance should remain acceptable across the full path a client is likely to read.

Test and document the client workflow

Write one example of the first request, one continuation request, and the final page. Show the fields that change and those that remain fixed. Include an example with a filter or sort option if the API supports it. Add error examples for an invalid limit or cursor. These examples help a client developer build the loop without guessing at server behavior.

Check permissions on every page, not only on the first request. A cursor should not let a user retrieve records they would not be allowed to see after their access changes. Log enough information to troubleshoot a failed continuation without recording sensitive cursor contents or customer data. Finally, measure the query using realistic data. Pagination reduces response size, but a poorly indexed query can still be slow.

When the API returns a next-page URL, build it on the server and encode its query values correctly. Clients should follow the link rather than concatenate an offset or cursor by hand. Validate that continuation links use an expected scheme and host before a client follows them, especially when a service proxy or user-controlled endpoint is involved. Document whether the link is absolute or relative and how long it remains valid. A clear continuation contract lowers client-specific bugs and gives the server room to change its internal query strategy without changing the interface.

A short working note

Try this with your work

Compare offset and cursor pagination, design stable ordering, and handle changing data without confusing clients.

0 of 30 of 3 steps
Your note stays in this browser.

Focus session

Give one idea your attention.

Use a short, quiet work block to try one step from this article.

25:00

25 minutes

Video resources

For a visual walkthrough related to this topic, see this YouTube learning resource. It opens a topic search so you can choose a current explanation that fits your level.

Frequently asked questions

Should I use cursor or offset pagination?

Use offset when page jumps and simple numbered pages matter for a modest, stable collection. Consider cursors for large or frequently changing collections that need efficient continuation. Measure your data and client needs.

Why do records repeat between API pages?

The sort order may not be unique, or new records may shift offsets between requests. Add a stable tie-breaker and choose a pagination contract suited to changing data.

Should an API return total count?

Return it when the client needs it and the cost and freshness are acceptable. Many “load more” interfaces need only a clear signal that another page exists.

Should clients decode a cursor?

Usually no. Treat the cursor as an opaque value and send it back unchanged. The server should validate it and bind it to the relevant sort and filters.

What should a pagination test cover?

Empty results, exact and partial final pages, repeated sort keys, inserts or deletions between requests, invalid limits, and access checks on continuation requests.