TExcelTAD
Home › GraphQL › Offset Pagination

Offset Pagination

A field like products: [Product!]! is fine for ten products and a disaster for ten million. Lists that can grow need pagination: the client asks for one page at a time. GraphQL doesn't prescribe a method; the two common designs are offset pagination (this lesson) and cursor pagination with connections (next lesson).

limit and offset

The simplest design mirrors SQL's LIMIT … OFFSET …: skip offset items, return the next limit:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Article { id: ID!, title: String! }
  type Query {
    articles(limit: Int = 3, offset: Int = 0): [Article!]!
  }
`);

const articles = Array.from({ length: 8 }, (_, i) => ({ id: String(i + 1), title: `Article ${i + 1}` }));

const rootValue = {
  articles: ({ limit, offset }) => articles.slice(offset, offset + limit),
};

const query = 'query Page($offset: Int) { articles(offset: $offset) { id } }';

for (const offset of [0, 3, 6, 9]) {
  const result = await graphql({ schema, source: query, rootValue, variableValues: { offset } });
  console.log(`offset ${offset}:`, result.data.articles.map((a) => a.id).join(',') || '(empty)');
}
offset 0: 1,2,3
offset 3: 4,5,6
offset 6: 7,8
offset 9: (empty)

It's easy to understand and lets users jump straight to "page 5" (offset = 4 * limit).

Returning page info

A bare list doesn't tell the client whether more pages exist or how many there are. Wrap the list in a page object with metadata:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Article { id: ID!, title: String! }

  type ArticlePage {
    items: [Article!]!
    totalCount: Int!
    hasMore: Boolean!
  }

  type Query {
    articles(limit: Int = 3, offset: Int = 0): ArticlePage!
  }
`);

const articles = Array.from({ length: 8 }, (_, i) => ({ id: String(i + 1), title: `Article ${i + 1}` }));

const rootValue = {
  articles: ({ limit, offset }) => ({
    items: articles.slice(offset, offset + limit),
    totalCount: articles.length,
    hasMore: offset + limit < articles.length,
  }),
};

const result = await graphql({
  schema,
  rootValue,
  source: '{ first: articles { items { id } hasMore totalCount } last: articles(offset: 6) { items { id } hasMore } }',
});
console.log(JSON.stringify(result.data));
{"first":{"items":[{"id":"1"},{"id":"2"},{"id":"3"}],"hasMore":true,"totalCount":8},"last":{"items":[{"id":"7"},{"id":"8"}],"hasMore":false}}

Guard the inputs

Never trust page sizes from clients. Without a cap, articles(limit: 1000000) loads your whole table. Validate and clamp in the resolver, and reject nonsense:

js · try it yourself
import { graphql, buildSchema, GraphQLError } from 'graphql';

const schema = buildSchema(`type Query { numbers(limit: Int = 10, offset: Int = 0): [Int!]! }`);
const all = Array.from({ length: 500 }, (_, i) => i);
const MAX_LIMIT = 50;

const rootValue = {
  numbers: ({ limit, offset }) => {
    if (limit < 1 || offset < 0) {
      throw new GraphQLError('limit must be >= 1 and offset >= 0', { extensions: { code: 'BAD_USER_INPUT' } });
    }
    return all.slice(offset, offset + Math.min(limit, MAX_LIMIT));
  },
};

for (const source of ['{ numbers(limit: 3) }', '{ numbers(limit: 100000) }', '{ numbers(offset: -5) }']) {
  const result = await graphql({ schema, source, rootValue });
  const nums = result.data?.numbers;
  console.log(source.padEnd(28), result.errors ? result.errors[0].message : `${nums.length} items, last ${nums.at(-1)}`);
}
{ numbers(limit: 3) }        3 items, last 2
{ numbers(limit: 100000) }   50 items, last 49
{ numbers(offset: -5) }      limit must be >= 1 and offset >= 0

The weakness: shifting data

Offsets are positions, and positions move when data changes. Imagine a feed sorted newest first. The client loads page 1, then a new post is published, then the client loads page 2:

js · try it yourself
const feed = ['p5', 'p4', 'p3', 'p2', 'p1'];   // newest first
const page = (offset, limit = 2) => feed.slice(offset, offset + limit);

console.log('page 1:', page(0));
feed.unshift('p6');                             // someone posts
console.log('page 2:', page(2));                // p4 again!
page 1: [ 'p5', 'p4' ]
page 2: [ 'p4', 'p3' ]

p4 appears twice. If an item had been deleted instead, the user would silently miss one. Large offsets are also slow in most databases: OFFSET 100000 still has to walk past 100,000 rows.

Offset pagination Cursor pagination
Jump to page N easy not directly
Stable when data changes no (duplicates/gaps) yes
Performance on deep pages degrades stays fast with an index
Typical use admin tables, search results with page numbers feeds, infinite scroll, public APIs

Tip: Even with offsets, always sort by a unique, stable key (e.g. createdAt, id). Without a deterministic order, the database may return rows in a different order on every request, and pages overlap randomly.

Test yourself

With limit: 10, which offset returns page 3?

  1. 3
  2. 20
  3. 30
  4. 10

Why should a resolver cap the limit argument?

  1. GraphQL requires it
  2. To stop clients from requesting huge pages that overload the server
  3. To make queries shorter
  4. Because Int is 32-bit

What goes wrong with offset pagination when new items are inserted at the top between page requests?

  1. Nothing
  2. Items can appear twice on consecutive pages
  3. The query fails validation
  4. The total count becomes negative