
A list endpoint that works perfectly with 50 records can become one of your API’s most expensive and least predictable surfaces at 50 million. A thoughtful guide to API pagination is not just about adding `limit` and `page` parameters. It is about controlling database cost, defining what clients can reliably expect, and making large collections usable without forcing consumers to understand your storage layer.
Pagination sits at the boundary between an API contract and a changing dataset. Get that boundary wrong and users see duplicates, missing results, slow responses, or mysterious failures during ordinary scrolling. Get it right and a growing collection remains predictable for web clients, mobile apps, background workers, and third-party integrations.
Why pagination is an API design decision
Returning every item in a collection is rarely a reasonable default. It increases query time, memory pressure, response size, and client-side work. It also creates a poor failure mode: an endpoint may look harmless in development, then time out after a tenant imports years of historical data.
Pagination puts a ceiling on each request. That ceiling protects the service, but it also creates a contract: clients need a stable way to ask for the next group of results. The right contract depends on the data, the query patterns, and whether records can change while a client is paging through them.
For example, an internal admin screen that browses a relatively static employee directory has different requirements than a feed of new security events arriving every second. The first may prioritize jumping to page 12. The second must prioritize avoiding gaps and duplicates as new events are inserted.
Before choosing a pattern, define four things: a deterministic sort order, a maximum page size, behavior for changing records, and the metadata clients need to continue. These choices matter more than the parameter names.
The three main pagination patterns
Offset pagination
Offset pagination asks for a fixed number of records after skipping a specified number. A familiar request might look like this:
“`http GET /v1/projects?limit=25&offset=50 “`
The response returns records 51 through 75 in the selected order. Some APIs expose the same idea as `page=3&per_page=25`, converting the page number into an offset internally.
This model is easy for developers to understand and useful when users need random access. An admin table with numbered pages is a natural fit. It is also straightforward to document and test.
The trade-off is performance and consistency. Large offsets can be costly because the database may still need to scan or discard many earlier rows. More importantly, inserts and deletes can shift the result set between requests. If a new record appears at the front of a list after the client requests page one, the first record on page two may be a duplicate.
Offset pagination is a reasonable choice for small-to-medium datasets, reporting views, and stable collections. Do not assume it will remain efficient merely because the API limits each response.
Cursor pagination
Cursor pagination returns an opaque marker representing the client’s current position. Rather than requesting page four, the client sends back the `next_cursor` supplied by the prior response:
“`http GET /v1/events?limit=100&cursor=eyJjcmVhdGVkQXQiOiIyMDI2… “`
A response commonly includes the items and continuation information:
“`json { “data”: [], “page”: { “next_cursor”: “eyJjcmVhdGVkQXQiOiIyMDI2…”, “has_more”: true } } “`
The cursor may encode a timestamp and unique ID, or it may contain a server-side reference. Treat it as opaque. Clients should store and replay it, not parse it or construct one themselves.
Cursor pagination performs well for ordered, append-heavy collections because the database can seek from a known boundary rather than skip a growing number of rows. It is generally the better choice for activity feeds, audit logs, messages, transactions, and synchronization jobs.
Its limitation is intentional: clients cannot reliably jump to an arbitrary page. That is often acceptable for infinite scrolling or batch processing, but it can be a poor fit for a UI that promises direct page navigation.
Keyset pagination
Keyset pagination is the database-oriented technique behind many cursor APIs. It requests rows after the last value seen in the active sort order. For a descending event feed ordered by `created_at` and then `id`, the next query resembles:
“`sql SELECT id, created_at, payload FROM events WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT :limit; “`
The secondary `id` is critical. Timestamps are often not unique, and sorting only by `created_at` can cause records with matching timestamps to be skipped or repeated. A pagination order must be deterministic, preferably using a unique tie-breaker.
Keyset pagination is efficient when supported by a matching composite index, such as `(created_at DESC, id DESC)`. Without that index, the API may still degrade as data grows. Query plans are part of pagination design, not an afterthought for the database team.
How to design a reliable pagination contract
Start by choosing a default and maximum page size. A default of 20, 50, or 100 is common, but the correct number depends on record size and client behavior. An endpoint returning small IDs can safely serve more items than one returning enriched objects with nested relationships.
Always enforce a server-side maximum, even if clients provide `limit`. Otherwise, one consumer can request an oversized page and turn an inexpensive list endpoint into a resource-exhaustion problem. Return a clear validation error or clamp the value consistently. Explicit errors are often easier to debug than silent changes, especially for integration partners.
Sort order must be explicit. Avoid relying on a database’s incidental row order, because it is not a contract. Expose a supported sort such as `created_at desc`, and state the tie-breaker behavior. If clients can choose sort fields, restrict them to indexed, vetted options rather than passing arbitrary field names into query construction.
Response metadata should help a client continue without overpromising. Cursor APIs usually need `next_cursor` and `has_more`. Offset APIs may include `offset`, `limit`, and perhaps `total`. Be cautious with total counts: `COUNT(*)` can be expensive on large or heavily filtered tables, and a count can become stale before the response reaches the client. If the product needs an exact total, measure its cost. If it only needs an indication that more records exist, fetching one extra row is often cheaper and more useful.
A good response also distinguishes an empty page from an invalid cursor. An empty page can be normal at the end of a collection. An expired, malformed, or mismatched cursor should produce a documented client error with a code that allows the consumer to restart safely.
Handle filters, mutations, and security deliberately
Pagination only makes sense within a particular query. A cursor generated for one filter set should not be accepted with a different filter set, tenant, or sort direction. Embed enough context in a signed cursor, or retain it server-side, so the API can reject mismatches. This prevents confusing results and reduces the chance of a cursor becoming a cross-tenant data access weakness.
For mutable data, decide what consistency means. Most APIs offer a best-effort traversal: records may be updated while the client paginates, but keyset boundaries reduce duplicates and omissions caused by inserts. If a workflow requires a fixed historical view, use a snapshot identifier, an export job, or a database isolation strategy designed for that purpose. A simple cursor does not automatically create a snapshot.
Deletion is another edge case. If the last item represented by a cursor is deleted, a properly designed keyset query can still continue using the cursor’s encoded sort values. This is one reason an opaque cursor should include the ordering values, not merely a record ID that must still exist.
Validate cursor size and format, sign or encrypt sensitive contents, and set expiration rules where appropriate. A cursor should never become a back door for arbitrary SQL conditions or internal identifiers that reveal information the caller should not see.
Test pagination like a stateful workflow
Unit tests for the first page are not enough. Test traversal across multiple pages, including records sharing the same sort value. Test empty collections, a final partial page, invalid limits, malformed cursors, and filter changes between requests.
Then test mutations while paging. Insert a newer record after page one, delete the boundary record, and update a sort field. The expected outcome depends on your stated consistency model, but the behavior should be intentional and documented.
Load testing deserves equal attention. Compare query latency for the first page and deep traversal across production-like data volumes. Review the database execution plan and verify the index supports both filtering and ordering. An endpoint that returns 25 items can still be slow if it must inspect millions to find them.
Choose for the consumer, then protect the system
Offset pagination is often the pragmatic answer for browseable back-office screens. Cursor and keyset pagination are usually stronger for high-volume feeds, event streams, and integrations that must process every available item efficiently. Some platforms support both, but only when the difference is clear enough that consumers will choose correctly.
The best next step is to inspect your busiest collection endpoint and identify its real sort order, largest tenant, and deepest expected traversal. Those three facts will tell you far more about the right pagination strategy than a generic `page` parameter ever can.




