Why Pagination Is Essential
Returning an entire collection from a GraphQL API is easy to implement but dangerous at scale.
This schema looks harmless:
type Query {
users: [User!]!
}
But if the database contains five million users, a request for users could attempt to retrieve and serialize an enormous amount of data.
Large responses create pressure on:
- Database memory
- Database CPU
- Network bandwidth
- Node.js memory
- JSON serialization
- GraphQL execution
- Client memory
- Browser rendering
Pagination places an explicit boundary on each request.
A basic API might use:
users(limit: Int!, offset: Int!): [User!]!
A more structured API can return metadata:
type UserPage {
items: [User!]!
totalCount: Int!
hasNextPage: Boolean!
}
Pagination should be enforced server-side. Do not simply trust the client to request reasonable values.
For example, an API may cap limit at 100 even if the schema accepts an integer.
Pagination does not only improve UX. It protects databases, servers, networks, and clients from accidentally or intentionally requesting enormous collections.
- Large GraphQL collections should be bounded.
- Pagination protects infrastructure as well as improving UI behavior.
- Server-side limits should prevent excessive page sizes.
- Pagination metadata helps clients navigate large datasets.
Why should a GraphQL server enforce a maximum page size?