To limit the amount of data returned in a single API response, improving performance and user experience when dealing with large lists.
- Listing users, products, or orders.
- Any endpoint returning an array that could grow indefinitely.
- Choose Strategy:
- Offset-based (
skip/limit): Simple, good for page numbers. Slow on large offsets. - Cursor-based (
after_id): Faster, good for infinite scroll. No random page access.
- Offset-based (
- Parse Query Params: Extract
page,limit, orcursorfrom request. Set defaults (e.g., limit=20). - Query Database:
- Apply
limit+ 1 (to check if there's a next page). - Apply sort order (crucial for cursor).
- Apply
- Format Response:
- Return
dataarray. - Return
metaobject:{ total, page, hasNextPage, nextCursor }.
- Return
- Validation: Cap the maximum
limitto prevent users requesting 10,000 rows.
- Ensure the sort column is indexed.
- For cursor pagination, the sort column must be unique (or use a tiebreaker like ID).
A reusable service function or helper that wraps DB queries and returns a standardized paginated response structure.