API pagination best practices help developers process large datasets efficiently without overwhelming application memory or database connections. This guide explains how to format an API response pagination payload, select the right technique for your database, and maintain system performance as your data grows.
How API pagination works, types, and when to use it
TL;DR: API pagination protects server resources and improves client performance by delivering manageable datasets. Offset methods work for simple applications, while cursor and keyset techniques ensure stability for changing data. Proper metadata and standard parameter names keep API integrations reliable.
API pagination is the technique of splitting a large API response into smaller, sequential chunks so a client can request data incrementally. Instead of returning an entire database table in a single oversized payload, the server returns a bounded set of records called a page. Each page contains a limited number of records.
Pagination typically uses parameters like offset, limit, or cursor-based tokens. The parameters determine the starting point and the number of records to include on each page. The API consumer requests subsequent pages to retrieve additional data until the dataset is complete.

Advantages of API Pagination
By implementing API pagination, developers as well as consumers experience the following advantages.
Improved Performance
Retrieving and processing smaller chunks of data reduces the response time and improves the overall efficiency of API calls. It minimizes the load on servers, network bandwidth, and client-side applications.
Reduced Resource Usage
Since pagination retrieves data in smaller subsets, it reduces the amount of memory, processing power, and bandwidth required on both the server and the client side. This efficient resource utilization leads to cost savings and improved scalability.
Enhanced User Experience
Paginated APIs provide a better user experience by delivering data in manageable portions. Users navigate through the data incrementally, accessing specific pages or requesting more data as needed. This approach enables smoother interactions, faster rendering of results, and easier navigation through large datasets.
Efficient Data Transfer
With pagination, only the necessary data travels over the network. This reduces the amount of data transferred and improves network efficiency.
Scalability and Flexibility
Pagination allows APIs to handle large datasets without overwhelming system resources. It provides a scalable solution for working with ever-growing data volumes and enables efficient data retrieval across different use cases and devices.
Error Handling
With pagination, error handling becomes more manageable. If a failure occurs during data retrieval, only the affected page needs to reload or process, rather than reloading the entire dataset. This helps isolate and address errors effectively, ensuring smoother error recovery and system stability.

Common Examples of Paginated APIs
Some of the most common, practical examples of API pagination include:
- Social media platforms like Twitter, Facebook, and Instagram employ paginated APIs to retrieve posts, comments, or user profiles.
- Online marketplaces such as Amazon, eBay, and Etsy utilize paginated APIs to retrieve product listings, search results, or user reviews.
- Banking or payment service providers provide paginated APIs for retrieving transaction history, account statements, or customer data. Identity providers use similar mechanics; reading how the Okta API works with core management endpoints and cursor pagination shows how directories handle large user lists.
- Job search platforms like Indeed or LinkedIn Jobs offer paginated APIs for retrieving job listings based on various criteria such as location, industry, or keywords.
How API Pagination Works in Databases
Pagination logic translates to backend database queries to manage scalability. When an API client requests the next chunk of a dataset, the server queries the database for that specific slice of rows. Handling pagination in databases requires optimizing these retrieval commands.
Offset-based pagination relies on SQL OFFSET and LIMIT clauses. This structure works for small tables but degrades as the dataset grows because the database must scan and discard all skipped rows. APIs You Won’t Hate notes that Performance degradation is significant as the offset increases. Fetching records with an offset of 500,000 forces the database engine to load 500,000 rows just to return the next 50.
Indexed keyset lookups solve this by using WHERE clauses to jump directly to the last seen record, making database retrieval fast regardless of depth. The query asks for records where the indexed identifier is greater than the previous page’s final identifier. This mechanism avoids recalculating positions from the start of the table.
API Pagination Techniques
There are several common API pagination techniques developers use for efficient data retrieval. You can read our guide explaining the 5 API pagination techniques explained with when to use each, trade-offs, and implementation notes to understand them completely. Here are the core methods:
1. Offset and limit pagination
Offset/limit pagination fetches records using two parameters: offset (how many records to skip) and limit (how many to return). Abstract API’s API glossary states that offset tells the server the number of items that should be skipped, while limit indicates the number of items to be returned. Sportmonks similarly defines it as a method of retrieving large datasets in pages by specifying how many records to skip (the offset) and how many to return (the limit).
For example, GET /records?offset=40&limit=20 returns records 41–60. It functions as the simplest method to implement because the database does the work with a single OFFSET/LIMIT clause, and a client jumps directly to any page by calculating its offset. The trade-off is the instability under concurrent writes. Because position is calculated fresh on every request, a record inserted or deleted earlier in the set shifts every subsequent page, and at high offsets the database gets slower as the dataset grows.
2. Cursor-based pagination
Cursor-based pagination replaces the numeric offset with an opaque token the server generates and the client passes back unchanged. A request looks like GET /records?cursor=eyJpZCI6MTIzfQ&limit=20. The server decodes the cursor to know exactly where the last page ended and fetches forward from there, so it never has to recalculate position from the start of the table.
Because the cursor anchors to the last record returned rather than to a count, it stays stable under concurrent writes and fast at any depth into a large dataset. Because the cursor only encodes the forward state, a client cannot jump straight to page 40 the way it can with offset/limit. Pages require sequential walking.
3. Page-based pagination
Page-based pagination acts as offset/limit with a friendlier interface. The client passes a page number and a pageSize instead of raw offset math, such as GET /records?page=3&pageSize=20. The server converts that internally to the equivalent offset.
It provides the easiest method for a UI to expose directly with page number inputs or jump controls. It remains the easiest for API consumers to reason about. Underneath, though, it calculates position by count, inheriting the same stability and performance limits as offset/limit at scale.
4. Time-based pagination
Time-based pagination uses a timestamp as the cursor instead of an ID or count. A request like GET /events?since=2026-08-20T00:00:00Z&limit=50 returns records after that point in time. The response’s last record’s timestamp becomes the since value for the next request.
It creates a natural fit for chronological data like activity feeds, logs, and webhook event streams. The limitation dictates that it only works cleanly when the sort order is time itself. It needs a tie-breaking rule, such as a secondary sort key, for records that share the exact same timestamp. Otherwise two records created in the same millisecond can duplicate across a page boundary.
5. Keyset pagination
Keyset pagination, sometimes called seek pagination, moves the cursor using an indexed column’s actual value rather than a position count. A request includes the last record’s sort key. The query fetches the next batch with a WHERE key > last_seen_key condition instead of an OFFSET.
Because it never recalculates position from the start of the table, it stays fast at scale. It does not produce duplicate or skipped rows when data changes mid-pagination.
| Method | How It Works | Best For | Main Trade-off |
|---|---|---|---|
| Offset/limit | Client specifies a starting index and count | Small, static datasets | Slow and unstable on large or frequently-changing data |
| Cursor-based | Server returns an opaque pointer to the last record seen | Large or real-time datasets | Can’t jump to an arbitrary page |
| Page-based | Client specifies a page number and size | Simple UIs, predictable datasets | Same instability risk as offset under the hood |
| Keyset | Client passes the last seen record’s sort key | High-throughput APIs needing consistency | Requires a stable, indexed sort column |
| Time-based | Client passes a timestamp cursor | Event streams, logs, activity feeds | Not suited to non-chronological data |

API Pagination Standards and Response Structures
Industry-wide API pagination standards prevent developers from having to reinvent the wheel. Standardizing how an API delivers metadata ensures clients parse responses predictably across different platforms.
The JSON:API specification defines standard pagination keys: first, last, prev, and next. These keys sit inside a dedicated links object, keeping the navigational pointers logically separate from the primary data array. Another approach relies on the RFC 8288 HTTP Link header format for pagination. This places the pagination pointers in the HTTP headers rather than the response body. Clients read the headers to find the next URL without needing to parse the full JSON payload.
Best Practices for API Pagination
When implementing API pagination, there are several core API pagination best practices to follow to ensure performance.
1. Use a common naming convention for pagination parameters
Adopt a consistent naming convention for pagination parameters, such as "offset" and "limit" or "page" and "size." Predictable naming makes it easier for API consumers to understand and use your pagination system.
2. Always include pagination metadata in API responses
Provide metadata in the API responses to convey additional information about the pagination state.
This includes the total number of records, the current page, the number of pages, and links to the next and previous pages. This metadata helps API consumers navigate through the paginated data effectively. Here is how the response of a paginated API should look:
{
"data": [
{
"id": 1,
"title": "Post 1",
"content": "Lorem ipsum dolor sit amet.",
"category": "Technology"
},
{
"id": 2,
"title": "Post 2",
"content": "Praesent fermentum orci in ipsum.",
"category": "Sports"
},
{
"id": 3,
"title": "Post 3",
"content": "Vestibulum ante ipsum primis in faucibus.",
"category": "Fashion"
}
],
"pagination": {
"total_records": 100,
"current_page": 1,
"total_pages": 10,
"next_page": 2,
"prev_page": null
}
}
3. Determine an appropriate page size
Select an optimal page size that balances the amount of data returned per page. A common starting point is 20–50 records per page for user-facing APIs, and up to a few hundred for internal batch or sync jobs. Always enforce a hard server-side cap so a client cannot request an unbounded page and degrade performance for other tenants. Third-party vendor limits vary widely. The Knit documentation states that Salesforce allows up to 2,000 records per query while HubSpot caps at 100; Knit abstracts that difference away.
A smaller page size reduces the response payload and improves performance, while a larger page size reduces the number of requests required.
Determining an appropriate page size for a paginated API involves considering various factors, such as the nature of the data, performance considerations, and user experience. To set proper defaults, review our guide covering recommended ranges by use case and how to handle page size limits.
4. Implement sorting and filtering options
Provide sorting and filtering parameters to allow API consumers to specify the order and subset of data they require. This enhances flexibility and enables users to retrieve targeted results efficiently.
Here is an example of how you can implement sorting and filtering options in a python API pagination logic flow:
from flask import Flask, request, jsonify
app = Flask(__name__)
# Dummy data
products = [
{"id": 1, "name": "Product A", "price": 10.0, "category": "Electronics"},
{"id": 2, "name": "Product B", "price": 20.0, "category": "Clothing"},
{"id": 3, "name": "Product C", "price": 15.0, "category": "Electronics"},
{"id": 4, "name": "Product D", "price": 5.0, "category": "Clothing"}
]
@app.route('/products', methods=['GET'])
def get_products():
# Pagination parameters
page = int(request.args.get('page', 1))
per_page = int(request.args.get('per_page', 10))
# Sorting options
sort_by = request.args.get('sort_by', 'id')
sort_order = request.args.get('sort_order', 'asc')
# Filtering options
category = request.args.get('category')
min_price = float(request.args.get('min_price', 0))
max_price = float(request.args.get('max_price', float('inf')))
# Apply filters
filtered_products = filter(lambda p: p['price'] >= min_price and p['price'] <= max_price, products)
if category:
filtered_products = filter(lambda p: p['category'] == category, filtered_products)
# Apply sorting
sorted_products = sorted(filtered_products, key=lambda p: p[sort_by], reverse=sort_order.lower() == 'desc')
# Paginate the results
start_index = (page - 1) * per_page
end_index = start_index + per_page
paginated_products = sorted_products[start_index:end_index]
return jsonify(paginated_products)
5. Preserve pagination stability
Ensure the pagination remains stable and consistent between requests. Newly added or deleted records should not affect the order or positioning of existing records during pagination. This ensures users navigate through the data without encountering unexpected changes. Check out our guide explaining how to build stable, consistent API pagination using cursors to avoid shifting issues.
If a client paginates with offset/limit and a record disappears from an earlier page while they fetch, every subsequent page shifts by one position. The client either skips a record it never saw or receives a duplicate. Cursor and keyset pagination avoid this because the next page anchors to a specific record’s position in the sort order, not a numeric offset.
6. Handle edge cases and error conditions
Account for edge cases such as reaching the end of the dataset, handling invalid or out-of-range page requests, and gracefully handling errors. Provide informative error messages and proper HTTP status codes to guide API consumers in handling pagination issues. For a full breakdown of edge cases, read about the 7 most common API pagination errors with causes and fixes for each.
7. Consider caching strategies
To optimize performance, implement page-level caching for 30–60 seconds keyed on full parameter sets. This approach absorbs repeated requests from pagination UI re-renders, while data staleness stays negligible.
Caching improves efficiency by reducing the load on the server and cutting down response times. Beyond basic page-level caching, effective strategies include result set caching, time-based caching, conditional caching (ETags), and reverse proxy caching (Nginx/Varnish). These advanced strategies provide flexibility for different workloads, further reducing latency and offloading caching duties from the core application server.
Frequently Asked Questions
How to handle pagination in APIs?
When fetching data, you must check the response for a next cursor or has_more flag, follow that pointer, loop until none remains, and respect page size limits. Rather than constructing URLs manually, use the pointer provided by the server in each response. For large datasets, process or store intermediate results as each page arrives instead of accumulating everything in memory.
What are the best practices for pagination?
To build reliable endpoints, use cursor-based pagination for large datasets, standard parameter names, include metadata, set sensible defaults, and use stable sorting. Cursor-based methods prevent shifting when data updates concurrently. Standard naming like limit and after helps developers integrate faster. Explicit metadata ensures clients navigate the dataset safely and accurately.
Does API pagination start at 0 or 1?
It depends on the API implementation. Page-based pagination most commonly starts at 1, meaning page=1 represents the first page. Offset-based pagination starts at 0 by convention, where offset=0 means skip zero records. Cursor-based pagination uses no page numbers at all. You start with no cursor and follow the next cursor returned in each response. Always check the specific API documentation to avoid off-by-one errors.
Is API pagination outdated?
No. API pagination remains essential, even though user interface features like infinite scroll hide it from end users. Cursor and keyset pagination techniques have largely superseded raw offset methods. While modern apps load data smoothly as you scroll, the underlying API still paginates the data to protect server resources. Developers continue to rely heavily on these mechanics for safe data transfer.
What is the ideal page size for API pagination?
The ideal page size depends on the payload size per record, the client’s use case, and server capacity. You should aim for 20–100 records per page for general APIs, with a typical hard maximum of 1,000. Data-heavy payloads warrant smaller pages. Let callers set their own limit up to the maximum rather than fixing page sizes.
How should pagination metadata be included in API responses?
Return pagination metadata in a consistent envelope alongside your data array. At minimum include a next cursor or next page URL, a has_more boolean, and optionally a total_count. Use a standard structure so clients can reliably parse it. Avoid returning pagination state only in HTTP Link headers, as many clients fail to parse headers correctly.
How do you handle the last page in API pagination?
Signal the last page clearly so clients know when to stop requesting. For cursor-based pagination, return next_cursor: null or omit the field entirely on the last page. For page-based pagination, return has_more: false or compare current_page to total_pages. Clients treat a missing or null next pointer as the termination signal. Avoid relying on an empty data array as the only signal.
What are common API pagination mistakes to avoid?
Common mistakes include using offset pagination on large, frequently-updated datasets, which causes records to skip or duplicate. Failing to sort on a stable indexed field breaks cursor-based pagination. Omitting total_count when clients genuinely need it for progress tracking limits usability. Setting fixed page sizes with no limit parameter restricts client flexibility. Forgetting to handle the last page signal causes infinite loops in client sync code.
What are the two main types of pagination?
The two foundational approaches are offset-based pagination and cursor-based pagination. Offset-based relies on a numeric position or page number. Cursor-based uses a pointer to the last record seen. Page-based, keyset, and time-based pagination function as variations built on these two underlying mechanics.
What are common problems with pagination?
The most frequent issues include inconsistent results when data changes between page requests, producing duplicate or skipped records. Poor performance at high offsets on large datasets causes query latency. Inconsistent parameter naming across an API’s endpoints confuses developers. Cursor or keyset pagination avoids the first two problems, while a documented naming convention fixes the third.
Simplify API pagination
Implementing effective API pagination remains essential for providing efficient access to large datasets. It adds complexity when you deal with a large number of API integrations. Development teams spend excessive time normalizing offset counts, cursors, and timestamps across different application endpoints.
Using a unified API solution like Knit ensures that your API pagination requirements work without forcing you to write custom fetch loops for every vendor. Knit acts as a translation layer that standardizes API authentication, data models, pagination, and errors across all integrated accounting platforms.
Once you connect Knit for a specific software category such as HRIS, ATS, or CRM, it automatically connects you with all the APIs within that category. In this process, Knit manages API authorization, authentication, pagination, rate limiting, and day-to-day maintenance of the integrations. This allows you to focus on building your core product rather than fighting rate limits and next_cursor tokens.