GraphQL subscriptions push real-time events to clients over WebSocket connections. Each event needs a stable, ordered identity for deduplication, cursor-based replay after reconnection, and cross-service event correlation. UUID v7 is well-suited to this role — it is time-ordered, globally unique, and embeds a creation timestamp that clients can use to detect gaps without querying the server. This page covers UUID v7 in GraphQL subscriptions using Apollo Server, GraphQL Yoga, and the graphql-ws library.

Schema design

type OrderEvent {
  eventId:   String!   # UUID v7 — unique, time-ordered event identifier
  orderId:   String!   # UUID v7 — the order this event relates to
  eventType: OrderEventType!
  payload:   OrderPayload!
  timestamp: String!   # ISO-8601 (can also be extracted from eventId)
}

enum OrderEventType {
  CREATED
  UPDATED
  SHIPPED
  DELIVERED
}

type Subscription {
  orderEvents(
    tenantId: String!
    after: String       # UUID v7 resume cursor — replay events after this ID
  ): OrderEvent!
}

The after argument accepts a UUID v7 string, enabling clients to resume subscriptions from their last received event without storing server-side session state.

Apollo Server implementation

import { v7 as uuidv7 } from 'uuid';
import { PubSub } from 'graphql-subscriptions';

const pubsub = new PubSub();

const resolvers = {
  Mutation: {
    createOrder: async (_, args) => {
      const order = {
        id: uuidv7(),
        ...args,
        createdAt: new Date().toISOString(),
      };
      await db.orders.create(order);

      // Publish with UUID v7 event ID
      const event = {
        eventId: uuidv7(),   // New UUID v7 for the event itself
        orderId: order.id,
        eventType: 'CREATED',
        payload: order,
        timestamp: new Date().toISOString(),
      };
      pubsub.publish(`ORDER_EVENTS_${args.tenantId}`, { orderEvents: event });

      return order;
    },
  },

  Subscription: {
    orderEvents: {
      subscribe: async function* (_, { tenantId, after }) {
        // Replay missed events if cursor provided
        if (after) {
          const missed = await db.events.findAfter(tenantId, after);
          for (const event of missed) {
            yield { orderEvents: event };
          }
        }
        // Then stream live events
        yield* pubsub.asyncIterator(`ORDER_EVENTS_${tenantId}`);
      },
    },
  },
};

The findAfter query uses WHERE event_id > $after ORDER BY event_id ASC — UUID v7 lexicographic ordering guarantees the correct sequence per RFC 9562. The Apollo Server subscriptions documentation covers async iterator patterns and PubSub engine options.

GraphQL Yoga with graphql-ws

import { createYoga } from 'graphql-yoga';
import { v7 as uuidv7 } from 'uuid';

const yoga = createYoga({
  schema,
  context: () => ({
    generateEventId: () => uuidv7(),  // Injected for testability
  }),
});

GraphQL Yoga’s subscriptions documentation covers the createPubSub helper and Server-Sent Events as an alternative to WebSockets for subscription transport.

Client-side deduplication

// Apollo Client — deduplicate subscription events by UUID v7 event ID
let lastEventId: string | null = null;

const subscription = client.subscribe({ query: ORDER_EVENTS, variables: { tenantId } });

subscription.subscribe({
  next({ data }) {
    const { eventId } = data.orderEvents;

    // Discard events we've already processed
    if (lastEventId && eventId <= lastEventId) {
      console.log(`Duplicate event ${eventId} — skipping`);
      return;
    }

    lastEventId = eventId;
    processEvent(data.orderEvents);
  },
});

UUID v7 comparison (eventId <= lastEventId) works as a string comparison because UUID v7 lexicographic order equals creation order. The Apollo Client subscriptions documentation covers useSubscription, cache updates, and reconnection handling.

Resume token storage

Store the last received event ID in localStorage for reconnection across page reloads:

const CURSOR_KEY = `subscription_cursor_${tenantId}`;

function onEvent(event: OrderEvent) {
  processEvent(event);
  localStorage.setItem(CURSOR_KEY, event.eventId);
}

function getResumeCursor(): string | null {
  return localStorage.getItem(CURSOR_KEY);
}

// On reconnect — pass stored cursor as 'after' argument
const after = getResumeCursor();
client.subscribe({
  query: ORDER_EVENTS,
  variables: { tenantId, after },  // Server replays missed events
});

Because UUID v7 embeds a millisecond timestamp, the cursor also tells the server approximately when the client disconnected — useful for detecting stale cursors (e.g. refuse to replay events older than 24 hours). Extract the timestamp with parseInt(cursor.replace(/-/g,'').slice(0,12), 16) as documented in the uuid npm package README.

Further reading

External references

Frequently asked questions

How does UUID v7 help with GraphQL subscription resume tokens?

A resume token lets a client reconnect after a disconnect and receive only events that occurred after the disconnect. UUID v7 event IDs work directly as resume tokens because their lexicographic order equals creation order — the server can query WHERE event_id > $resumeToken with no additional timestamp field. UUID v4 tokens require a separate created_at cursor. The Apollo Server subscriptions documentation covers pub/sub patterns and cursor handling.

Can I use UUID v7 to deduplicate GraphQL subscription events?

Yes. Assign a UUID v7 event ID at publish time and include it in every subscription payload. Clients track the last seen event ID and discard any event with a UUID v7 value less than or equal to the last seen ID. This handles network retransmission and at-least-once delivery semantics without a separate deduplication store. The graphql-ws library on npm supports custom message extensions for carrying event IDs alongside subscription payloads.

How do I implement cursor-based subscription pagination with UUID v7?

Expose the UUID v7 event ID as a cursor field in the subscription payload. On reconnect, the client sends the last received cursor in the subscription arguments. The server loads missed events from the database using WHERE id > $cursor ORDER BY id ASC and replays them before resuming live events. UUID v7's time-ordering per RFC 9562 §5.7 guarantees the correct replay sequence.