Cursor pagination (also called keyset pagination) is the preferred pagination strategy for large datasets — it avoids the OFFSET performance cliff and is stable under concurrent inserts. UUID v7’s timestamp-prefixed sort order makes it a natural cursor: the same column serves as both primary key and pagination key, using the existing primary key B-tree index. See UUID in Databases for the index fundamentals.

Basic keyset pagination with UUID v7

-- PostgreSQL — next page after cursor
SELECT id, status, created_at
FROM orders
WHERE id > $1          -- cursor: last UUID v7 from previous page
ORDER BY id            -- chronological, uses primary key index
LIMIT $2;              -- page size

Because UUID v7 sorts lexicographically in creation order, ORDER BY id is equivalent to ORDER BY created_at with no secondary index needed.

// TypeScript pagination helper
import { v7 as uuidv7 } from 'uuid';

interface Page<T> {
  items: T[];
  nextCursor: string | null;
}

async function getOrders(cursor: string | null, limit = 20): Promise<Page<Order>> {
  const rows = cursor
    ? await db.query<Order>(
        'SELECT * FROM orders WHERE id > $1 ORDER BY id LIMIT $2',
        [cursor, limit + 1]
      )
    : await db.query<Order>(
        'SELECT * FROM orders ORDER BY id LIMIT $1',
        [limit + 1]
      );

  const hasMore = rows.length > limit;
  const items   = hasMore ? rows.slice(0, limit) : rows;
  const nextCursor = hasMore ? items[items.length - 1].id : null;

  return { items, nextCursor };
}

Fetching limit + 1 rows and checking if the extra row exists is the standard pattern for detecting whether another page follows. See UUID in GraphQL for Relay-style cursor connections using this pattern.

Opaque cursor encoding

Exposing raw UUID v7 values as cursors leaks timing information (the timestamp is visible). For public APIs, encode the cursor:

// Encode UUID v7 as an opaque Base64url cursor
function encodeCursor(uuid: string): string {
  return Buffer.from(uuid).toString('base64url');
}

function decodeCursor(cursor: string): string {
  const uuid = Buffer.from(cursor, 'base64url').toString('utf8');
  // Validate before use
  if (!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(uuid)) {
    throw new Error('Invalid cursor');
  }
  return uuid;
}

See UUID URL-Safe Encoding for the full Base64url and Base58 options, and UUID Security for what UUID v7’s timestamp discloses.

Bidirectional pagination

-- Previous page (reverse direction)
SELECT id, status, created_at
FROM orders
WHERE id < $1          -- cursor: first UUID v7 from current page
ORDER BY id DESC
LIMIT $2;

Reversing the comparison and sort direction navigates backwards. UUID v7’s consistent sort order makes both directions reliable — UUID v4 cannot provide this without a separate timestamp column.

GraphQL cursor connection

// resolvers/orders.ts
export const ordersResolver = {
  Query: {
    orders: async (_: unknown, { first, after }: { first: number; after?: string }) => {
      const cursor = after ? decodeCursor(after) : null;
      const { items, nextCursor } = await getOrders(cursor, first);

      return {
        edges: items.map(item => ({
          node:   item,
          cursor: encodeCursor(item.id),
        })),
        pageInfo: {
          hasNextPage:     nextCursor !== null,
          endCursor:       nextCursor ? encodeCursor(nextCursor) : null,
        },
      };
    },
  },
};

See UUID in GraphQL for the full Relay Connection spec implementation and UUID in OpenAPI for documenting cursor parameters in REST APIs.

Nil UUID as the “start” sentinel

When no cursor is provided (first page), the Nil UUID (00000000-0000-0000-0000-000000000000) can serve as a lower-bound sentinel — all valid UUID v7 values are greater than the Nil UUID, so WHERE id > nil_uuid returns all rows. Similarly, the Max UUID (ffffffff-ffff-ffff-ffff-ffffffffffff) serves as an upper-bound sentinel for reverse pagination.

Further reading

External references

Frequently asked questions

Why is UUID v7 better than UUID v4 for cursor pagination?

Cursor pagination requires a stable, sortable key. UUID v4 is random — it has no meaningful order, so WHERE id > cursor ORDER BY id with a UUID v4 cursor returns rows in an arbitrary sequence with no relationship to insertion time. UUID v7's timestamp prefix makes its sort order match creation time, so cursor pagination using UUID v7 naturally traverses records chronologically. The same primary key index serves both the uniqueness constraint and the cursor scan. See UUID v4 vs v7.

How do I encode a UUID v7 cursor safely for use in URLs?

The simplest approach is Base64url-encoding the 36-character UUID string: btoa(uuid).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''). This produces a 48-character URL-safe token that is opaque to clients. On the server, decode and validate with Ecto.UUID.cast/1 or equivalent before using in a query. See UUID URL-Safe Encoding.