Pagination limits the amount of data returned in one response. Offset pagination is simple and supports direct page navigation, while cursor pagination can be more efficient and stable for large or frequently changing datasets. Neither approach is correct for every endpoint.
Offset pagination
A request can specify a page number and page size, and the database skips earlier rows. This is easy to explain to users and supports page counts, but large offsets can become expensive because the database may still scan or traverse many rows. Concurrent inserts and deletes can also cause records to shift between pages.
Cursor pagination
A cursor represents a position in a stable ordering, often using the last row's sort key and a unique tie-breaker. The next query continues after that position. This works well for feeds and large tables, but clients cannot always jump directly to an arbitrary page number.
Make ordering deterministic
Pagination requires a stable ORDER BY. If the primary sort field is not unique, add a unique secondary key. Without deterministic ordering, records may appear twice or be skipped even when the dataset is unchanged.
Validate page size and cursor input
Set a maximum page size and validate cursor structure. Do not trust a cursor to authorize access to records. Apply normal authorization and filtering on every page request.
Checklist
- Use offset pagination for modest datasets and page-number UX.
- Consider cursor pagination for large or changing datasets.
- Always use deterministic ordering.
- Enforce a maximum page size.
- Treat cursors as navigation state, not authorization.