Pagination is a design pattern used to limit the number of records returned in a single response from a resource collection. It helps in efficiently managing and navigating through large datasets by dividing them into smaller, more manageable sections.

Details

Pagination is critical in scenarios where fetching a large amount of data can be impractical or may lead to performance bottlenecks. By breaking down the dataset into multiple “pages,” clients can request ma specific subset of data. This approach not only improves the response time of the API but also reduces the load on the server and network. Common methods of pagination include page number-based, cursor-based, and offset-based pagination.

Common Pattern Names/Synonyms

  • Page-based Navigation
  • Cursor-based Navigation
  • Offset-based Navigation
  • Incremental Loading
  • Chunking

Common Use Cases

  • API performance and resource management: Reduces the load on the API by avoiding the need to fetch all data and transform it to JSON or another format, thus also reducing infrastructure cost.
  • Social media feeds: Loading posts incrementally to ensure smooth user experience as more content loads dynamically.
  • Data reporting: Generating reports from large datasets that are easier to handle and view in segments.

Mermaid Sequence Diagrams

Page Number-based Pagination

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: Request page 1 (limit=10)
    S->>C: Response with data 1-10
    C->>S: Request page 2 (limit=10)
    S->>C: Response with data 11-20
    Note right of S: Repeats until all data is fetched or client stops

Cursor-based Pagination

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: Request start with cursor=0 (limit=10)
    S->>C: Response with data 1-10, cursor=10
    C->>S: Request start with cursor=10 (limit=10)
    S->>C: Response with data 11-20, next cursor=20
    Note right of S: Continues with the new cursor each time

Offset-based Pagination

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: Request start with offset=0 (limit=10)
    S->>C: Response with data 1-10
    C->>S: Request start with offset=10 (limit=10)
    S->>C: Response with data 11-20
    Note right of S: Continues with new offset each time

Examples

Page Number-based Pagination Example

GET /api/products?page=1&limit=10

Response:

{
  "data": [/* array of products */],
  "meta": {
    "totalPages": 50,
    "currentPage": 1,
    "totalRecords": 500
  }
}

Cursor-based Pagination Example

GET /api/posts?cursor=eyJ... (encoded cursor)&limit=10

Response:

{
  "data": [/* array of posts */],
  "nextCursor": "eyJ...",
  "previousCursor": "aWQ1"
}

Offset-based Pagination Example

GET /api/items?offset=20&limit=10

Response:

{
  "data": [/* array of items */],
  "nextOffset": 30,
  "totalRecords": 200
}

Updated: