TExcelTAD
Home › GraphQL › Subscriptions

Subscriptions

Queries and mutations follow request → response. Some features need the server to push data as things happen: chat messages, live scores, a progress bar for a long job, a stock ticker. GraphQL's third operation type, subscription, models that. The client subscribes once; the server sends a new result each time an event occurs.

In the schema

graphql
type Message { id: ID!, room: String!, text: String! }

type Subscription {
  messageAdded(room: String!): Message!
}

And a client subscribes like this:

graphql
subscription OnMessage {
  messageAdded(room: "general") { id text }
}

A subscription operation must select exactly one top-level field.

How it executes

A subscription field has two parts:

  1. subscribe: returns an async iterable of events (a stream).
  2. resolve: turns each event into the field's value, after which the selection set is executed just like a query.

graphql-js implements this in subscribe(), which returns an async iterator of results. We can run it right here, with an async generator as the event source:

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

const schema = buildSchema(`
  type Query { _unused: Boolean }
  type Subscription { countdown(from: Int!): Int! }
`);

const rootValue = {
  // With buildSchema, the root value provides the event stream for each field.
  countdown: async function* ({ from }) {
    for (let n = from; n >= 0; n--) {
      yield { countdown: n };   // each event is the root value for one result
    }
  },
};

const stream = await subscribe({
  schema,
  rootValue,
  document: parse('subscription { countdown(from: 3) }'),
});

for await (const result of stream) {
  console.log(JSON.stringify(result));
}
console.log('stream finished');
{"data":{"countdown":3}}
{"data":{"countdown":2}}
{"data":{"countdown":1}}
{"data":{"countdown":0}}
stream finished

Each event produced its own result, with the familiar { "data": … } shape.

A pub/sub event bus

In a real server, events come from mutations or other systems. A pub/sub object connects them: mutations publish events, and each subscriber gets its own async iterator filtered to the events it cares about. Here's a small in-memory version with a code-first schema and a subscribe + resolve pair:

js · try it yourself
import {
  subscribe, graphql, parse, GraphQLSchema, GraphQLObjectType,
  GraphQLString, GraphQLNonNull, GraphQLID,
} from 'graphql';

function createPubSub() {
  const listeners = new Set();
  return {
    publish(event) { for (const listener of listeners) listener(event); },
    asyncIterator(filter) {
      const buffer = [];
      let wake = null;
      const listener = (event) => {
        if (!filter(event)) return;
        buffer.push(event);
        wake?.();
      };
      listeners.add(listener);
      return {
        [Symbol.asyncIterator]() { return this; },
        async next() {
          while (buffer.length === 0) await new Promise((r) => (wake = r));
          return { value: buffer.shift(), done: false };
        },
        async return() { listeners.delete(listener); return { value: undefined, done: true }; },
      };
    },
  };
}

const pubsub = createPubSub();
let nextId = 1;

const Message = new GraphQLObjectType({
  name: 'Message',
  fields: { id: { type: GraphQLID }, room: { type: GraphQLString }, text: { type: GraphQLString } },
});

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({ name: 'Query', fields: { ok: { type: GraphQLString } } }),
  mutation: new GraphQLObjectType({
    name: 'Mutation',
    fields: {
      send: {
        type: Message,
        args: { room: { type: new GraphQLNonNull(GraphQLString) }, text: { type: new GraphQLNonNull(GraphQLString) } },
        resolve: (_root, { room, text }) => {
          const message = { id: String(nextId++), room, text };
          pubsub.publish({ type: 'MESSAGE_ADDED', message });
          return message;
        },
      },
    },
  }),
  subscription: new GraphQLObjectType({
    name: 'Subscription',
    fields: {
      messageAdded: {
        type: Message,
        args: { room: { type: new GraphQLNonNull(GraphQLString) } },
        subscribe: (_root, { room }) =>
          pubsub.asyncIterator((e) => e.type === 'MESSAGE_ADDED' && e.message.room === room),
        resolve: (event) => event.message,
      },
    },
  }),
});

const stream = await subscribe({
  schema,
  document: parse('subscription { messageAdded(room: "general") { id text } }'),
});

const send = (room, text) =>
  graphql({ schema, source: `mutation { send(room: "${room}", text: "${text}") { id } }` });

await send('general', 'Hi all!');
await send('random', 'Nobody sees this in #general');
await send('general', 'Anyone up for lunch?');

for (let i = 0; i < 2; i++) {
  const { value } = await stream.next();
  console.log(JSON.stringify(value.data));
}
await stream.return();   // unsubscribe
console.log('unsubscribed');
{"messageAdded":{"id":"1","text":"Hi all!"}}
{"messageAdded":{"id":"3","text":"Anyone up for lunch?"}}
unsubscribed

The subscriber to general received two messages; the one sent to random was filtered out.

Transport: WebSockets and SSE

HTTP request/response can't carry a stream of results, so subscriptions need a long-lived connection:

Transport Library Notes
WebSocket graphql-ws the de-facto standard protocol (graphql-transport-ws)
Server-Sent Events graphql-sse, GraphQL Yoga plain HTTP, works through most proxies

A server with GraphQL Yoga has subscriptions built in (Yoga uses SSE by default):

js
import { createServer } from 'node:http';
import { createSchema, createYoga, createPubSub } from 'graphql-yoga';

const pubsub = createPubSub();

const yoga = createYoga({
  schema: createSchema({
    typeDefs: `
      type Query { ok: Boolean }
      type Mutation { send(text: String!): String! }
      type Subscription { messageAdded: String! }
    `,
    resolvers: {
      Mutation: {
        send: (_, { text }) => { pubsub.publish('message', text); return text; },
      },
      Subscription: {
        messageAdded: { subscribe: () => pubsub.subscribe('message'), resolve: (text) => text },
      },
    },
  }),
});

createServer(yoga).listen(4000);

And a browser client using graphql-ws:

js
import { createClient } from 'graphql-ws';

const client = createClient({ url: 'wss://api.example.com/graphql' });

const unsubscribe = client.subscribe(
  { query: 'subscription { messageAdded }' },
  { next: (result) => console.log(result.data), error: console.error, complete: () => {} },
);

When to use subscriptions

Subscriptions keep a connection and some server state open per client, so they cost more than queries. Use them for small, frequent, latency-sensitive updates. For data that changes every few minutes, polling a query is simpler. For "something changed, refetch", a subscription that only sends ids, followed by a normal query, keeps payloads small.

Test yourself

What does a subscription field's subscribe function return?

  1. A single value
  2. An async iterable of events
  3. A WebSocket
  4. A Promise of a list

How many top-level fields may a subscription operation select?

  1. Any number
  2. Exactly one
  3. Two
  4. None

Which transport is commonly used for GraphQL subscriptions?

  1. Plain HTTP POST
  2. WebSockets (graphql-ws) or Server-Sent Events
  3. SMTP
  4. FTP