---
title: "Handling API Pagination: Fetching Large Data Sets - API7.ai"
description: "Learn about offset-based and cursor-based pagination, and how API gateways optimize data retrieval."
url: "https://api7.ai/learning-center/api-101/handling-api-pagination"
---

[Skip to article](#column-content)

Column contentsAPI 101

[API 101](https://api7.ai/learning-center/api-101)

Search this column

01 API Fundamentals

[View this topic · 10](https://api7.ai/learning-center/api-101?topic=fundamentals)[1. Introduction to APIs: Definition and Importance](https://api7.ai/learning-center/api-101/what-is-api)[2. RESTful API Best Practices: Architecture, Methods, and Examples](https://api7.ai/learning-center/api-101/restful-api-best-practices)[3. SOAP vs REST: Differences, Examples, and When to Use Each](https://api7.ai/learning-center/api-101/soap-vs-rest-differences)[4. GraphQL: A New Approach to APIs](https://api7.ai/learning-center/api-101/what-is-graphql)[5. gRPC: High-Performance RPC Framework](https://api7.ai/learning-center/api-101/what-is-grpc)[6. Webhooks: Real-Time Communication Between Applications](https://api7.ai/learning-center/api-101/what-is-webhooks)[7. API Endpoints: Designing and Managing for Scalability and Security](https://api7.ai/learning-center/api-101/what-are-api-endpoints)[8. HTTP Methods: GET, POST, PUT, PATCH, DELETE & More](https://api7.ai/learning-center/api-101/http-methods-in-apis)[9. API Rate Limiting Best Practices and Algorithms](https://api7.ai/learning-center/api-101/api-rate-limiting)[10. API Versioning Strategies and Best Practices](https://api7.ai/learning-center/api-101/api-versioning)

02 API Development and Design

[View this topic · 10](https://api7.ai/learning-center/api-101?topic=design)[11. How to Build an API: From Design to Deployment](https://api7.ai/learning-center/api-101/build-your-first-api)[12. API Documentation: Tools and Techniques](https://api7.ai/learning-center/api-101/api-documentation-tools-and-techniques)[13. OpenAPI Specification Guide: OAS, Examples, and Best Practices](https://api7.ai/learning-center/api-101/openapi-specification)[14. API Mocking: Testing Without a Backend](https://api7.ai/learning-center/api-101/api-mocking)[15. API Error Handling: Status Codes, Error Responses, and Best Practices](https://api7.ai/learning-center/api-101/error-handling-apis)[16. Authentication and Authorization in APIs](https://api7.ai/learning-center/api-101/authentication-authorization-apis)[17. OAuth 2.0: Secure API Access](https://api7.ai/learning-center/api-101/oauth-2.0-secure-api-access)[18. API Gateways: Managing and Securing Traffic](https://api7.ai/learning-center/api-101/api-gateways-managing-securing-traffic)[19. Microservices and APIs: Designing Modular Applications](https://api7.ai/learning-center/api-101/microservices-apis-modular-application-design)[20. API Orchestration: Combining Multiple Services](https://api7.ai/learning-center/api-101/api-orchestration-combining-services)

03 API Security

[View this topic · 10](https://api7.ai/learning-center/api-101?topic=security)[21. How to Avoid Common Vulnerabilities](https://api7.ai/learning-center/api-101/how-to-avoid-common-api-vulnerabilities)[22. Implementing JWT for API Security](https://api7.ai/learning-center/api-101/implementing-jwt-for-api-security)[23. Rate Limiting and Throttling: Protecting Your API](https://api7.ai/learning-center/api-101/rate-limiting-and-throttling)[24. API Security Testing Tools and Techniques for Modern APIs](https://api7.ai/learning-center/api-101/api-security-testing-tools-and-techiniques)[25. CORS in APIs: Handling Cross-Origin Requests](https://api7.ai/learning-center/api-101/understanding-cors-in-apis)[26. Data Encryption in API Communication](https://api7.ai/learning-center/api-101/data-encryption-in-api-communication)[27. API Security Best Practices: Protecting Your Digital Front Door](https://api7.ai/learning-center/api-101/api-security-best-practices)[28. API Tokens Explained: Usage, Security, and Best Practices](https://api7.ai/learning-center/api-101/api-tokens-and-their-usage)[29. Securing APIs in Serverless Architectures](https://api7.ai/learning-center/api-101/secure-apis-in-serverless-architectures)[30. API Security in the Age of IoT](https://api7.ai/learning-center/api-101/api-security-in-the-age-of-iot)

04 API Integration

[View this topic · 10](https://api7.ai/learning-center/api-101?topic=integration)[31. Integrating Third-Party APIs into Your Application](https://api7.ai/learning-center/api-101/integrate-third-party-apis)[32. API Aggregation: Combining Multiple APIs](https://api7.ai/learning-center/api-101/api-aggregation-combining-multiple-apis)[33. Real-Time Data with Streaming API](https://api7.ai/learning-center/api-101/real-time-data-with-streaming-apis)[34. Handling API Pagination: Fetching Large Data Sets](https://api7.ai/learning-center/api-101/handling-api-pagination)[35. Error Handling When Consuming APIs](https://api7.ai/learning-center/api-101/error-handling-when-consuming-apis)[36. API Integration Testing: Ensuring Reliability](https://api7.ai/learning-center/api-101/api-integration-testing-ensuring-reliability)[37. Working with Rate Limits in Third-Party APIs](https://api7.ai/learning-center/api-101/working-with-rate-limits-in-third-party-apis)[38. Automating Workflows with APIs](https://api7.ai/learning-center/api-101/automating-workflows-with-apis)[39. API Integration in Mobile Applications](https://api7.ai/learning-center/api-101/api-integration-in-mobile-applications)[40. How to Overcome API Integration Challenges](https://api7.ai/learning-center/api-101/how-to-overcome-api-integration-challenges)

05 API Management

[View this topic · 10](https://api7.ai/learning-center/api-101?topic=management)[41. API Lifecycle Management: From Development to Retirement](https://api7.ai/learning-center/api-101/api-lifecycle-management)[42. Monitoring API Performance: Tools and Metrics](https://api7.ai/learning-center/api-101/api-performance-monitoring)[43. API Analytics: Understanding Usage Patterns](https://api7.ai/learning-center/api-101/api-analytics-guide)[44. Monetizing Your API: Strategies and Models](https://api7.ai/learning-center/api-101/api-monetization-strategies-models)[45. Scaling APIs: Best Practices for High Traffic](https://api7.ai/learning-center/api-101/scaling-api-high-traffic-best-practices)[46. API Governance Policies and Standards Guide](https://api7.ai/learning-center/api-101/api-governance-policies-standards-guide)[47. API Developer Portal Guide: Features, Onboarding, and Engagement](https://api7.ai/learning-center/api-101/developer-portal-guide-engaging-api-users)[48. Rate Limiting Strategies for API Management](https://api7.ai/learning-center/api-101/rate-limiting-strategies-for-api-management)[49. API Breaking Changes: Deprecation and Migration Guide](https://api7.ai/learning-center/api-101/api-versioning-managing-changes-over-time)[50. Choosing the Right API Management Platform](https://api7.ai/learning-center/api-101/choosing-the-right-api-management-platform)

06 Emerging API Practices

[View this topic · 10](https://api7.ai/learning-center/api-101?topic=trends)[51. Serverless APIs: Building Scalable Applications](https://api7.ai/learning-center/api-101/serverless-apis)[52. API-First Development: From Contract to Production](https://api7.ai/learning-center/api-101/api-first-development)[53. Hypermedia APIs: HATEOAS and Its Applications](https://api7.ai/learning-center/api-101/hypermedia-apis)[54. The Role of AI in API Development](https://api7.ai/learning-center/api-101/ai-in-api-development)[55. APIs in IoT: Connecting Devices](https://api7.ai/learning-center/api-101/apis-in-iot)[56. REST and GraphQL APIs: Architecture, Caching, and Gateways](https://api7.ai/learning-center/api-101/graphql-vs-rest)[57. The Rise of API Marketplaces](https://api7.ai/learning-center/api-101/rise-of-api-marketplaces)[58. Event-Driven APIs: Designing for Real-Time](https://api7.ai/learning-center/api-101/event-driven-api-design-real-time)[59. Low-Code/No-Code API Development](https://api7.ai/learning-center/api-101/low-code-no-code-api-development-guide)[60. API Development Trends: The Future of APIs for Modern Teams](https://api7.ai/learning-center/api-101/future-and-trends-of-apis)

07 Industry API Applications

[View this topic · 10](https://api7.ai/learning-center/api-101?topic=industries)[61. Payment Gateway APIs: Integrating Stripe and PayPal](https://api7.ai/learning-center/api-101/stripe-vs-paypal-api-integration-guide)[62. Social Media APIs: Facebook, Twitter, and Instagram](https://api7.ai/learning-center/api-101/social-media-apis)[63. Maps & Geolocation APIs: Google Maps, Mapbox, and OSM](https://api7.ai/learning-center/api-101/mapping-and-geolocation-apis)[64. E-commerce APIs: Building Modern Online Stores](https://api7.ai/learning-center/api-101/e-commerce-apis)[65. Healthcare APIs: Connecting Medical Data](https://api7.ai/learning-center/api-101/healthcare-apis)[66. Financial APIs: Accessing Banking Services](https://api7.ai/learning-center/api-101/financial-apis)[67. Travel and Booking APIs: Integrating Flight and Hotel Data](https://api7.ai/learning-center/api-101/travel-and-booking-apis)[68. Music and Video Streaming APIs: Spotify and YouTube](https://api7.ai/learning-center/api-101/music-and-video-streaming-apis)[69. Weather APIs: Accessing Meteorological Data](https://api7.ai/learning-center/api-101/weather-apis)[70. Sports Data APIs: Features, Use Cases, and Integration Tips](https://api7.ai/learning-center/api-101/sports-data-apis)

08 Tools and Platforms

[View this topic · 10](https://api7.ai/learning-center/api-101?topic=tools)[71. What Is Postman? API Development Platform Guide](https://api7.ai/learning-center/api-101/postman-api-development-environment)[72. Swagger: Designing and Documenting APIs](https://api7.ai/learning-center/api-101/swagger-designing-and-documenting-apis)[73. Insomnia API Client: Debug, Test, and Design APIs](https://api7.ai/learning-center/api-101/insomnia-rest-client-for-debugging)[74. What Is Apigee? API Management Features and Architecture](https://api7.ai/learning-center/api-101/apigee-api-management-platform)[75. Building Serverless APIs with AWS API Gateway](https://api7.ai/learning-center/api-101/aws-api-gateway-building-serverless-apis)[76. Apache APISIX: Open-Source API Gateway and Enterprise Support](https://api7.ai/learning-center/api-101/apache-apisix-open-source-api-gateway)[77. MuleSoft: Connecting Applications and Data](https://api7.ai/learning-center/api-101/mulesoft-connecting-applications-and-data)[78. RapidAPI Guide: Discovering, Testing, and Connecting to APIs](https://api7.ai/learning-center/api-101/rapidapi-discovering-and-connecting-to-apis)[79. Firebase: Backend as a Service](https://api7.ai/learning-center/api-101/firebase-backend-as-a-service)[80. Auth0: Complete Authentication and Authorization Platform](https://api7.ai/learning-center/api-101/auth0-authentication-authorization-platform)

09 API Testing

[View this topic · 10](https://api7.ai/learning-center/api-101?topic=testing)[81. Automated API Testing: Tools and Techniques](https://api7.ai/learning-center/api-101/automated-api-testing-tools-and-techniques)[82. Load Testing Your API: Ensuring Performance at Scale](https://api7.ai/learning-center/api-101/load-testing-your-api-ensuring-performance)[83. Mocking APIs for Testing: Accelerating Development and Improving Quality](https://api7.ai/learning-center/api-101/mocking-apis-for-testing-purposes)[84. Contract Testing in API Development: Ensuring Reliable Integration](https://api7.ai/learning-center/api-101/contract-testing-in-api-development)[85. Postman API Testing Automation: Newman, CLI, and CI/CD](https://api7.ai/learning-center/api-101/using-postman-for-api-testing)[86. Continuous Integration and API Testing](https://api7.ai/learning-center/api-101/continuous-integration-and-api-testing)[87. Security Testing for APIs: Protecting Your API from Vulnerabilities](https://api7.ai/learning-center/api-101/security-testing-for-apis)[88. Handling API Deprecations in Testing: Strategies for Smooth Transitions](https://api7.ai/learning-center/api-101/handling-api-deprecations-in-testing)[89. Testing GraphQL APIs: Challenges and Solutions](https://api7.ai/learning-center/api-101/testing-graphql-apis-challenges-and-solutions)[90. API Test Automation Frameworks: A Comparative Study](https://api7.ai/learning-center/api-101/api-test-automation-frameworks-comparative-study)

10 Documentation and Developer Experience

[View this topic · 10](https://api7.ai/learning-center/api-101?topic=documentation)[91. Writing Clear and Concise API Documentation](https://api7.ai/learning-center/api-101/writing-clear-and-concise-api-documentation)[92. Tools for Generating API Documentation](https://api7.ai/learning-center/api-101/tools-for-generating-api-documentation)[93. Interactive API Documentation for Developer Experience](https://api7.ai/learning-center/api-101/interactive-api-documentation)[94. Maintaining Documentation for Multiple API Versions](https://api7.ai/learning-center/api-101/maintaining-documentation-for-multiple-api-versions)[95. Using OpenAPI for API Documentation](https://api7.ai/learning-center/api-101/using-openapi-for-api-documentation)[96. Best Practices for Documenting API Error Responses](https://api7.ai/learning-center/api-101/best-practices-for-documenting-api-error-responses)[97. Incorporating Code Samples in API Documentation](https://api7.ai/learning-center/api-101/incorporating-code-samples-in-api-documentation)[98. API Documentation for Non-Developers](https://api7.ai/learning-center/api-101/api-documentation-for-non-developers)[99. Translating API Documentation for Global Audiences](https://api7.ai/learning-center/api-101/translating-api-documentation-for-global-audiences)[100. How to Measure API Documentation Effectiveness](https://api7.ai/learning-center/api-101/measuring-api-documentation-effectiveness)

[API 101](https://api7.ai/learning-center/api-101)[API Integration](https://api7.ai/learning-center/api-101?topic=integration)

On this page

On this page

- [Introduction to API Pagination](#introduction-to-api-pagination)

- [Common Pagination Strategies](#common-pagination-strategies)

  - [1. Offset-Based Pagination (Page-Number Pagination)](#1-offset-based-pagination-page-number-pagination)
  - [2. Cursor-Based Pagination (Continuation Token Pagination)](#2-cursor-based-pagination-continuation-token-pagination)
  - [3. Keyset Pagination](#3-keyset-pagination)

- [Implementing Pagination with API Gateways](#implementing-pagination-with-api-gateways)

  - [1. Leveraging API Gateway Features for Pagination](#1-leveraging-api-gateway-features-for-pagination)
  - [2. Best Practices for API Gateway Configuration Related to Pagination](#2-best-practices-for-api-gateway-configuration-related-to-pagination)

- [Optimizing Pagination for Performance](#optimizing-pagination-for-performance)

  - [1. Strategies for Efficient Data Fetching](#1-strategies-for-efficient-data-fetching)
  - [2. Considerations for Database Indexing and Query Optimization](#2-considerations-for-database-indexing-and-query-optimization)

- [Error Handling and Edge Cases](#error-handling-and-edge-cases)

- [Conclusion](#conclusion)

- [Next Steps](#next-steps)

Article 34

# Handling API Pagination: Fetching Large Data Sets

API7.ai

June 19, 2025

## Introduction to API Pagination

In the realm of modern web applications and microservices, data is king. From social media likes to emails, weather reports, and wearable device data, enormous quantities of information are generated and accumulated every second. Directly fetching millions of records in a single API call is akin to trying to drink from a firehose – it's overwhelming for both the client and the server, leading to performance bottlenecks, timeouts, and memory issues. This is precisely where API pagination comes into play.

**API pagination** is a fundamental technique for breaking down large data responses into smaller, manageable chunks or "pages." Instead of sending all records at once, the API sends a subset of the data, along with information that allows the client to request subsequent subsets. This not only significantly improves API responsiveness and scalability but also provides a much smoother user experience. Consider a social media feed with billions of posts; without pagination, loading the entire feed would be impossible. Pagination ensures that only a manageable number of posts are loaded at a time, with options to load more as needed.

## Common Pagination Strategies

Choosing the right pagination strategy is critical for optimal API performance and usability. While various methods exist, the most prevalent are offset-based and cursor-based pagination.

### 1. Offset-Based Pagination (Page-Number Pagination)

Offset-based pagination is arguably the most straightforward and widely understood method. It relies on two primary parameters: `limit` (or `pageSize`) and `offset` (or `page`).

- **`limit`**: Specifies the maximum number of records to return in a single response.
- **`offset`**: Indicates the starting point (offset from the beginning of the dataset) from which to retrieve records.

**How it Works:**

To retrieve the first page, you might set `offset=0` and `limit=10`. For the second page, `offset=10` and `limit=10`, and so on.

**Example Request:**

`GET /api/products?limit=10&offset=0` (for the first 10 products) `GET /api/products?limit=10&offset=10` (for the next 10 products)

**Advantages:**

- **Simplicity:** Easy to implement on both the client and server sides.
- **Familiarity:** Most developers are familiar with this approach, making it easy to integrate.
- **Direct Access:** Allows direct access to any specific "page" if the page number is known.

**Disadvantages:**

- **Performance Issues with Deep Pagination:** As the `offset` increases, the database might still need to scan through all previous records up to the offset, leading to degraded performance for very large datasets and deep page requests. For instance, `SELECT * FROM products LIMIT 10 OFFSET 1000000;` can be significantly slower than `SELECT * FROM products LIMIT 10 OFFSET 0;`.
- **Inconsistency with Dynamic Data:** If new records are added or existing records are deleted between page requests, the results can be inconsistent. You might miss records or see duplicates. Imagine fetching products sorted by creation date, and while you're on page 5, new products are added. The records on subsequent pages might shift, leading to an incomplete or inaccurate view.

```
graph TD
    A[Client Request Page 1] --> B{API Server};
    B -- limit=10, offset=0 --> C[Database Query];
    C -- Returns Records 1-10 --> B;
    B -- Sends Records 1-10 to Client --> A;
    A[Client Request Page 2] --> D{API Server};
    D -- limit=10, offset=10 --> E[Database Query];
    E -- Returns Records 11-20 --> D;
    D -- Sends Records 11-20 to Client --> A;
```

*Figure 1: Offset-Based Pagination Flow*

### 2. Cursor-Based Pagination (Continuation Token Pagination)

Cursor-based pagination offers a more robust and efficient solution for large, dynamic datasets, especially when dealing with real-time data or when strict consistency across pages is required. Instead of using numerical offsets, it uses a "cursor" (often an opaque string) that points to the last record retrieved in the previous request.

**How it Works:**

The API returns a `next_cursor` (or similar field) in its response. The client then uses this `next_cursor` in the subsequent request to fetch the next set of records.

**Example Request:**

`GET /api/products?limit=10` (initial request, returns `next_cursor=eyJpZCI6MTIzNDV9`) `GET /api/products?limit=10&cursor=eyJpZCI6MTIzNDV9` (subsequent request)

The cursor typically encodes information about the last item, such as its ID or a timestamp, which the server uses to efficiently locate the next batch of data. For instance, if records are sorted by an ID, the cursor might contain the ID of the last item from the previous page: `SELECT * FROM products WHERE id > [last_id_from_cursor] ORDER BY id ASC LIMIT 10;`.

**Advantages:**

- **Performance:** Significantly more performant for large datasets as it avoids the `OFFSET` overhead. The database can directly seek to the cursor position.
- **Consistency:** More resilient to data changes (additions/deletions) between requests, as it always retrieves records *after* a specific point.
- **Scalability:** Better suited for highly scalable APIs with rapidly changing data.

**Disadvantages:**

- **No Direct Page Access:** Cannot directly jump to a specific "page number" as there's no inherent page concept. You can only move forward or backward (if the cursor supports it).
- **Complexity:** Can be slightly more complex to implement on both client and server sides due to the need to manage and encode/decode cursor values.
- **Sorting Dependency:** Often relies on a consistent sort order of the underlying data.

```
graph TD
    A[Client Initial Request] --> B{API Server};
    B -- limit=10 --> C[Database Query];
    C -- Returns Records 1-10 + next_cursor_X --> B;
    B -- Sends Records 1-10 + next_cursor_X to Client --> A;
    A[Client Request with next_cursor_X] --> D{API Server};
    D -- limit=10, cursor=next_cursor_X --> E[Database Query from cursor point];
    E -- Returns Records 11-20 + next_cursor_Y --> D;
    D -- Sends Records 11-20 + next_cursor_Y to Client --> A;
```

*Figure 2: Cursor-Based Pagination Flow*

### 3. Keyset Pagination

Keyset pagination is a specialized form of cursor-based pagination that leverages an ordered set of unique keys (typically primary keys or unique index columns) to define the starting point for the next page. It's particularly efficient when fetching records sorted by multiple columns. For example, `SELECT * FROM orders WHERE (order_date, order_id) > ('2023-01-01', 12345) ORDER BY order_date, order_id LIMIT 10;`.

## Implementing Pagination with API Gateways

[API gateways](https://api7.ai/learning-center/api-gateway-guide/what-is-an-api-gateway) play a pivotal role in managing and enhancing API interactions, including pagination. An API gateway acts as a single entry point for all API calls, enabling you to apply policies, transformations, and routing rules before requests reach your backend services. This is incredibly powerful for abstracting away pagination complexities from clients and centralizing pagination logic. Azure API Management, for instance, is a hybrid, multicloud management platform that can be leveraged for various API management scenarios, including gateway functionalities.

### 1. Leveraging API Gateway Features for Pagination

API gateways can significantly assist in handling pagination through:

- **Policy-Based Transformations:** You can define policies within the API gateway to transform client-requested pagination parameters into backend-friendly formats. For example, a client might send `page=2&size=10`, and the gateway can translate this into `offset=10&limit=10` before forwarding to the backend. This allows you to expose a consistent pagination interface to clients, even if your backend services use different pagination schemes.
- **Response Rewriting:** The gateway can also rewrite backend responses to inject pagination metadata. If a backend doesn't explicitly return `next_cursor` or `total_pages`, the gateway can calculate and add this information to the response body or headers based on the received data and the original request.
- **Caching:** For static or infrequently updated paginated data, the API gateway can cache pages, reducing the load on backend services and speeding up response times for subsequent requests to the same page.
- **Rate Limiting and Quotas:** Pagination helps in managing API consumption. API gateways can enforce rate limits on requests per page, preventing abuse and ensuring fair usage.
- **Centralized Logging and Monitoring:** All paginated requests passing through the gateway can be logged and monitored centrally, providing valuable insights into API usage patterns and performance.

### 2. Best Practices for API Gateway Configuration Related to Pagination

- **Standardize Pagination Parameters:** Even if your backend services vary, strive to expose a consistent set of pagination parameters through your API gateway. This simplifies client-side development.
- **Validate Inputs:** Implement policies to validate pagination parameters (e.g., `limit` within acceptable ranges) to prevent malicious or malformed requests.
- **Handle Default Values:** Set default `limit` and `offset`/`cursor` values to ensure graceful behavior when clients don't provide them.
- **Consider Total Count (Carefully):** While providing a `totalCount` can be helpful for UIs, calculating it for very large datasets can be expensive. If needed, consider caching the total count or only providing it for the first page.
- **Secure Cursor Values:** If using cursor-based pagination, ensure cursor values are opaque and securely encoded to prevent clients from tampering with them.

## Optimizing Pagination for Performance

Beyond choosing the right strategy, several optimization techniques can further enhance the performance of your paginated APIs.

### 1. Strategies for Efficient Data Fetching

- **Index Your Data:** This is perhaps the most crucial step. Ensure that the columns used for sorting and filtering in your pagination queries (e.g., `id`, `timestamp`, `order_date`) are properly indexed in your database. Without indexes, the database will perform full table scans, rendering pagination ineffective.
- **Limit `SELECT *`:** Avoid `SELECT *` in your database queries. Instead, select only the columns truly needed by the client. This reduces data transfer size and database processing.
- **Avoid Subqueries in Pagination:** Complex subqueries or joins within pagination clauses can significantly degrade performance. Simplify your queries as much as possible.
- **Materialized Views:** For frequently accessed but less frequently updated large datasets, consider using materialized views to pre-aggregate or pre-sort data, making pagination queries much faster.
- **Connection Pooling:** Efficiently manage database connections using connection pooling to reduce overhead for each request.

### 2. Considerations for Database Indexing and Query Optimization

When using offset-based pagination, the `OFFSET` clause can be particularly problematic for performance. Consider this example:

```
SELECT * FROM orders ORDER BY created_at DESC LIMIT 10 OFFSET 100000;
```

This query tells the database to find 100,010 records, then discard the first 100,000 before returning the next 10. The database still has to read through those 100,000 records.

For cursor-based pagination, indexing on the cursor column (e.g., `id` or `created_at`) is vital.

```
SELECT * FROM orders WHERE id > [last_id] ORDER BY id ASC LIMIT 10;
```

This query can leverage an index directly to find records greater than `[last_id]`, making it significantly faster regardless of how far into the dataset you are.

For keyset pagination with multiple sort columns, a composite index covering all sorting columns is essential. For example, on `(order_date, order_id)`.

Regularly analyze your database query plans to identify performance bottlenecks related to pagination. Tools like `EXPLAIN ANALYZE` (PostgreSQL) or `EXPLAIN` (MySQL) can provide invaluable insights.

## Error Handling and Edge Cases

Robust API design includes meticulous error handling for pagination.

- **Invalid Parameters:** Clients might send non-numeric `limit` or `offset` values, negative values, or values outside acceptable ranges. The API should return appropriate HTTP status codes (e.g., `400 Bad Request`) with clear error messages.
- **No More Data:** When a client requests a page that contains no more data (e.g., `offset` is beyond the total number of records, or `cursor` points to the end), the API should return an empty array and potentially indicate `hasNextPage: false` or omit the `next_cursor`. Returning `200 OK` with an empty array is generally preferred over `404 Not Found`.
- **Cursor Expiration/Invalidation:** If using time-based or stateful cursors, implement mechanisms to handle expired or invalid cursors (e.g., `410 Gone` or `400 Bad Request`).
- **Data Integrity Issues:** While cursor pagination mitigates some consistency issues, large-scale concurrent operations can still present challenges. Ensure your backend logic and database transactions are designed to handle concurrent data modifications gracefully.

## Conclusion

By understanding the nuances of offset-based and cursor-based pagination, and by strategically leveraging the power of API gateways, developers can create robust data retrieval mechanisms.

Remember that continuous learning is a hallmark of good technical professionals. Regularly review and optimize your pagination strategies based on your data growth and evolving application needs.

By implementing these best practices, you'll ensure that your APIs can handle the ever-increasing volume of data, delivering a seamless experience for your users and maintaining the high expertise and trust expected of a professional API provider.

## Next Steps

Stay tuned for our upcoming column on the API 101, where you'll find the latest updates and insights!

Eager to deepen your knowledge about API gateways? Follow [our Linkedin](https://sg.linkedin.com/company/api7-ai) for valuable insights delivered straight to your inbox!

If you have any questions or need further assistance, feel free to contact [API7 Experts](https://api7.ai/contact).

[Previous article**Real-Time Data with Streaming API**](https://api7.ai/learning-center/api-101/real-time-data-with-streaming-apis)[Next article**Error Handling When Consuming APIs**](https://api7.ai/learning-center/api-101/error-handling-when-consuming-apis)

On this page

- [Introduction to API Pagination](#introduction-to-api-pagination)

- [Common Pagination Strategies](#common-pagination-strategies)

  - [1. Offset-Based Pagination (Page-Number Pagination)](#1-offset-based-pagination-page-number-pagination)
  - [2. Cursor-Based Pagination (Continuation Token Pagination)](#2-cursor-based-pagination-continuation-token-pagination)
  - [3. Keyset Pagination](#3-keyset-pagination)

- [Implementing Pagination with API Gateways](#implementing-pagination-with-api-gateways)

  - [1. Leveraging API Gateway Features for Pagination](#1-leveraging-api-gateway-features-for-pagination)
  - [2. Best Practices for API Gateway Configuration Related to Pagination](#2-best-practices-for-api-gateway-configuration-related-to-pagination)

- [Optimizing Pagination for Performance](#optimizing-pagination-for-performance)

  - [1. Strategies for Efficient Data Fetching](#1-strategies-for-efficient-data-fetching)
  - [2. Considerations for Database Indexing and Query Optimization](#2-considerations-for-database-indexing-and-query-optimization)

- [Error Handling and Edge Cases](#error-handling-and-edge-cases)

- [Conclusion](#conclusion)

- [Next Steps](#next-steps)
