Skip to content

Pagination

Cursor-based pagination: why offset breaks down and how cursors stay fast at any scale.

Pagination is unavoidable for any collection that grows. The choice of strategy determines whether your API stays fast at a million rows or turns into a full-table scan every time someone scrolls.

Why not offset

Offset pagination (?page=5&per_page=20) seems simple but breaks in two ways at scale:

Performance. OFFSET 10000 LIMIT 20 tells the database to read and discard 10,000 rows before returning 20. The work grows linearly with the page number. Page 1 is fast; page 500 is slow regardless of indexes.

Instability. If a row is inserted or deleted between two requests, items shift. A new row at position 1 pushes everything else down; the client sees a duplicate on the next page. A deletion causes a skip. Offset pagination on a live dataset is eventually inconsistent by construction.

For a deep dive into how PostgreSQL executes offset queries and why the cost compounds, see Pagination in PostgreSQL.

Cursor-based pagination

A cursor encodes the position of the last item seen. The next request picks up exactly after that item, no matter what changed in the meantime. The database executes a WHERE id > :cursor LIMIT 20 keyed range scan, fast at any depth.

Request

GET /v1/users?limit=20 HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...

First page omits the cursor. Subsequent pages pass the cursor from the previous response:

GET /v1/users?limit=20&cursor=eyJpZCI6ImY0N2FjMTBiLTU4Y2MtNDM3Mi1hNTY3LTBlMDJiMmMzZDQ3OSIsImNyZWF0ZWRfYXQiOiIyMDI0LTAxLTAxVDAwOjAwOjAwLjAwMFoifQ HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...

Response

HTTP/1.1 200 OK
Content-Type: application/json

{
  "data": [
    {
      "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
      "email_address": "alice@example.com",
      "created_at": "2024-01-15T10:30:00.000Z"
    }
  ],
  "pagination": {
    "next_cursor": "eyJpZCI6ImY0N2FjMTBiLTU4Y2MtNDM3Mi1hNTY3LTBlMDJiMmMzZDQ3OSIsImNyZWF0ZWRfYXQiOiIyMDI0LTAxLTE1VDEwOjMwOjAwLjAwMFoifQ",
    "has_next_page": true,
    "limit": 20
  }
}

When the last page is reached:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "data": [...],
  "pagination": {
    "next_cursor": null,
    "has_next_page": false,
    "limit": 20
  }
}

Pagination fields

Field Type Description
next_cursor string | null Opaque token for the next page; null on the last page
has_next_page boolean Explicit flag; don’t make clients test next_cursor for null
limit integer The limit actually applied (useful when the server clamps the requested limit)

Note the deliberate omission of a total_count. Counting all matching rows requires a separate full scan and is often wrong by the time the client receives it. If you need a count, provide it as a separate endpoint (GET /v1/users/count) so clients can opt in to paying for it.

Cursor encoding

The cursor is opaque to clients; they treat it as a blob and pass it back unchanged. The server chooses what to encode. A common approach is base64url-encoding a JSON object with enough position information to reconstruct the WHERE clause:

{
  "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "created_at": "2024-01-15T10:30:00.000Z"
}

Include both id and the sort field. If two rows have identical created_at values, id breaks the tie and keeps the cursor stable. The id here is the external identifier from your API response; see Identities for how to choose its format. Sign or encrypt the cursor if you don’t want clients crafting their own, but don’t rely on that for security; validate the decoded values as you would any input.

Limits

Enforce a maximum limit server-side and document the default:

Parameter Default Maximum
limit 20 100

Return an error for out-of-range values rather than silently clamping; silent clamping means the client asked for 500 and got 100 without knowing why.

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "error": {
    "code": "INVALID_PARAMETER",
    "message": "limit must be between 1 and 100. Received 500."
  }
}

Sorting and cursors

Cursors are tightly coupled to sort order. A cursor generated for sort=-created_at is meaningless for sort=last_name. If you support multiple sort orders, include the sort key in the cursor or reject cursor + sort combinations that don’t match.

The safest default: sort by created_at DESC, id DESC and encode both in the cursor. This is stable, indexed, and the most common ordering clients want anyway.

Type to search…

↑↓ navigate↵ selectEsc close