StackPractices
intermediate By Mathias Paulenko

GraphQL Connection Pagination Pattern

Implement Relay-style cursor-based pagination with edges, nodes, and pageInfo for stable GraphQL list queries.

Overview

The Connection pattern is the GraphQL standard for paginating list fields. Instead of returning a plain array, a connection wraps results in edges (each containing a node and a cursor), a pageInfo object (with hasNextPage, hasPreviousPage, startCursor, endCursor), and an optional totalCount.

Cursor-based pagination is more stable than offset-based pagination. Insertions and deletions mid-pagination don’t move your cursors. Offsets shift, so you get skipped or duplicated items. If you want the step-by-step recipe version, see Paginate GraphQL results with Relay connections; for the bigger picture of designing these fields, check the GraphQL schema design guide.

When to Use

  • List fields that can return more items than fit in one response
  • You need stable pagination that survives inserts and deletes between pages
  • Clients need to fetch the next or previous page from any position
  • You want to comply with the GraphQL Relay Connection specification
  • You need bidirectional pagination (forward and backward)

Solution

Schema Definition

const typeDefs = `
  type PageInfo {
    hasNextPage: Boolean!
    hasPreviousPage: Boolean!
    startCursor: String
    endCursor: String
  }

  type UserEdge {
    node: User!
    cursor: String!
  }

  type UserConnection {
    edges: [UserEdge!]!
    pageInfo: PageInfo!
    totalCount: Int!
  }

  type User {
    id: ID!
    name: String!
    email: String!
  }

  type Query {
    users(
      first: Int
      after: String
      last: Int
      before: String
    ): UserConnection!
  }
`;

Resolver Implementation

import { base64, unbase64 } from './encoding';

const DEFAULT_PAGE_SIZE = 20;
const MAX_PAGE_SIZE = 100;

function encodeCursor(offset: number): string {
  return base64(`offset:${offset}`);
}

function decodeCursor(cursor: string): number {
  const decoded = unbase64(cursor);
  const offset = parseInt(decoded.split(':')[1], 10);
  return isNaN(offset) ? 0 : offset;
}

const resolvers = {
  Query: {
    users: async (_, { first, after, last, before }, context) => {
      const limit = Math.min(first || last || DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE);
      const direction = first !== undefined ? 'forward' : 'backward';

      let offset = 0;
      if (after) offset = decodeCursor(after) + 1;
      if (before) offset = Math.max(0, decodeCursor(before) - limit);

      const totalCountResult = await context.db.query(
        'SELECT COUNT(*) as count FROM users'
      );
      const totalCount = totalCountResult[0].count;

      const rows = await context.db.query(
        'SELECT id, name, email FROM users ORDER BY created_at DESC LIMIT $1 OFFSET $2',
        [limit + 1, offset]
      );

      const hasMore = rows.length > limit;
      const nodes = hasMore ? rows.slice(0, limit) : rows;

      const edges = nodes.map((node, index) => ({
        node,
        cursor: encodeCursor(offset + index),
      }));

      return {
        edges,
        totalCount,
        pageInfo: {
          hasNextPage: direction === 'forward' ? hasMore : offset + limit < totalCount,
          hasPreviousPage: offset > 0,
          startCursor: edges.length > 0 ? edges[0].cursor : null,
          endCursor: edges.length > 0 ? edges[edges.length - 1].cursor : null,
        },
      };
    },
  },
};

Client Query Example

query GetUsers($first: Int, $after: String) {
  users(first: $first, after: $after) {
    edges {
      cursor
      node {
        id
        name
        email
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}

Cursor with Sort Key (Instead of Offset)

For large datasets, use a sort key instead of an offset to avoid scanning skipped rows:

function encodeCursor(sortKey: string, id: string): string {
  return base64(`${sortKey}:${id}`);
}

function decodeCursor(cursor: string): { sortKey: string; id: string } {
  const decoded = unbase64(cursor);
  const [sortKey, id] = decoded.split(':');
  return { sortKey, id };
}

const resolvers = {
  Query: {
    users: async (_, { first, after }, context) => {
      const limit = Math.min(first || 20, 100);
      let query = 'SELECT id, name, email, created_at FROM users';
      const params = [];

      if (after) {
        const { sortKey, id } = decodeCursor(after);
        query += ' WHERE (created_at, id) < ($1, $2)';
        params.push(sortKey, id);
      }

      query += ' ORDER BY created_at DESC, id DESC LIMIT $' + (params.length + 1);
      params.push(limit + 1);

      const rows = await context.db.query(query, params);
      const hasMore = rows.length > limit;
      const nodes = hasMore ? rows.slice(0, limit) : rows;

      const edges = nodes.map((node) => ({
        node,
        cursor: encodeCursor(node.created_at, node.id),
      }));

      return {
        edges,
        pageInfo: {
          hasNextPage: hasMore,
          hasPreviousPage: false,
          startCursor: edges[0]?.cursor || null,
          endCursor: edges[edges.length - 1]?.cursor || null,
        },
      };
    },
  },
};

Explanation

Mermaid graph LR diagram

The Connection pattern wraps every paginated field in a standard structure:

  • edges: an array where each item contains a node (the actual data) and a cursor (an opaque string pointing to that item’s position)
  • pageInfo: metadata about the current page: whether more pages exist in either direction and the cursors of the first and last items
  • totalCount: optional but useful for UIs that show total result count

The LIMIT + 1 trick

The resolver never needs a separate “does another page exist” query. It asks the database for limit + 1 rows and keeps only limit. If the extra row came back, hasNextPage is true and the surplus row is discarded. So one round trip covers both “give me the page” and “is there more”.

Why cursors stay opaque

Clients should treat a cursor as an opaque token, not data to parse. Base64 the payload (offset:50, 2026-07-03:uuid) and clients can’t hand-roll cursors, so you’re free to change the format later without breaking anyone.

Offset cursors vs sort key cursors

On big tables, a sort-key cursor beats an offset cursor by a wide margin. OFFSET 100000 makes the database scan and discard 100,000 rows before returning yours; a (created_at, id) < ($1, $2) predicate jumps straight to the position through an index. Offset cursors are fine for small or static datasets; switch to keyset pagination once OFFSET starts showing up in slow query logs.

The cost of totalCount

SELECT COUNT(*) scans the whole filtered set, which gets expensive on large tables. If your UI doesn’t need an exact total, leave totalCount out or make it opt-in. Many APIs return it only when the client explicitly selects the field.

Backward pagination

last/before mirrors first/after: take the page before the cursor, read it in reverse order, then flip it back so edges still come out in sort order. With an offset cursor, hasPreviousPage comes down to offset > 0.

Variants

ApproachCursor TypeBest For
Offset cursorbase64("offset:50")Small datasets, simple implementation
Sort key cursorbase64("2026-07-03:uuid")Large datasets, stable ordering
Keyset cursorPrimary key + sort columnOrdered by indexed columns
Time-based cursorISO timestampChronological feeds
Hash cursorHash of last itemDistributed systems where offset is unknown

Best Practices

  • Make cursors opaque: base64-encode them so clients do not try to parse or construct them manually
  • Always request LIMIT + 1: fetch one extra row to determine hasNextPage without a separate count query
  • Use indexed columns for sort key cursors: (created_at, id) with a composite index avoids full scans
  • Cap page size: enforce a maximum (e.g. 100) to prevent clients from requesting 10,000 items
  • Return totalCount only when needed: counting all rows is expensive on large tables. Make it optional via a field directive or separate query

Common Mistakes

  • Using offset-based cursors on large tables: OFFSET 100000 scans 100,000 rows. Swap in a sort-key cursor with a WHERE clause.
  • Not encoding cursors: returning raw offsets or timestamps lets clients manipulate them. Always base64-encode.
  • Sorting that changes between requests: switch the ORDER BY and every cursor you already issued points at the wrong row. Bake the sort column into the cursor.
  • Forgetting hasPreviousPage: backward pagination requires tracking whether items exist before the current page. Calculate it from the offset or a reverse query.
  • Empty pages: zero edges means startCursor and endCursor still have to come back, as null. GraphQL doesn’t take undefined.

See Also

Frequently Asked Questions

What is the difference between offset and cursor pagination?

Offset pagination uses LIMIT 20 OFFSET 40 to skip rows. Cursor pagination reaches a position directly through a WHERE clause. Offset is simpler but slow on large datasets and unstable when items are inserted or deleted between requests. Cursor is stable and efficient.

Do I need to follow the Relay spec exactly?

Relay's Connection spec is a convention rather than a hard requirement. Feel free to bolt extra fields onto pageInfo or edges when your API needs them. The key structures (edges, cursor, pageInfo.hasNextPage) are what most clients expect.

How do I handle pagination with filtering?

Include the filter criteria in the cursor or re-apply the same WHERE clause on each request. The cursor only marks the position; the filter narrows the dataset. The filter narrows the dataset, the cursor marks the spot; together they land on the right page.

Can I use connection pagination with DataLoader?

Yes. Create a DataLoader that batches cursor-based queries. Its batch function gets several cursors and either fires one query per cursor or merges them when the data source allows it.

Should I pick cursor-based or offset-based pagination?

Cursors don't care about inserts: new rows between pages never shift the position you bookmarked. Offset-based is simpler (LIMIT/OFFSET) but items inserted mid-read make page 2 repeat or skip rows, and deep offsets get slow. Use cursors for feeds, timelines, and any list that changes while users paginate; offset is fine for reports, static tables, and admin panels. One trade-off to know: cursors only move next/previous, so you can't offer "jump to page 47" without extra work. For GraphQL specifically, cursor connections are the established convention.