Catalog My learning Blog
API Design Course: REST and GraphQL Best Practices · Phase 3 · Lesson 18 · 4 min read

GraphQL Subscriptions for Real-Time Data

On this page
  1. When to use GraphQL subscriptions
  2. Defining a subscription and its resolver
  3. Testing a subscription with curl
  4. Server-Sent Events vs WebSockets for subscriptions
  5. Scaling subscriptions across servers
  6. Alternatives to subscriptions
  7. Check yourself

When to use GraphQL subscriptions

A comment thread should show new comments as they arrive, without the user refreshing. Polling every few seconds wastes requests and still lags. A subscription lets the client say "tell me when this happens", and the server pushes each event.

Defining a subscription and its resolver

GraphQL
type Subscription {
  commentAdded(postId: ID!): Comment!
}

The resolver returns an async stream of events instead of a single value. With GraphQL Yoga's built-in pub/sub:

JavaScript
const pubsub = createPubSub();

const resolvers = {
  Mutation: {
    addComment: async (_, { input }, ctx) => {
      // ... validate and save
      pubsub.publish(`comment:${input.postId}`, comment);
      return { comment, errors: [] };
    },
  },
  Subscription: {
    commentAdded: {
      subscribe: (_, { postId }) => pubsub.subscribe(`comment:${postId}`),
      resolve: (payload) => payload,
    },
  },
};

Publishing to a topic per post means each subscriber receives only the events it asked for, rather than every comment on the site filtered afterwards.

A client subscribes with a query; when a mutation publishes an event to that topic, the server resolves the subscription's fields and pushes the result over an open connection.
A client subscribes with a query; when a mutation publishes an event to that topic, the server resolves the subscription's fields and pushes the result over an open connection.

Testing a subscription with curl

A subscriber opens a stream for post 7 using Server-Sent Events:

Shell
curl -N http://127.0.0.1:7072/graphql \
  -H 'Accept: text/event-stream' -H 'Content-Type: application/json' \
  -d '{"query":"subscription { commentAdded(postId: \"7\") { id text } }"}'

Then two mutations add a comment to post 7 and another to post 8. The subscriber's stream receives exactly one event:

YAML
event: next
data: {"data":{"commentAdded":{"id":"1","text":"Great post"}}}

The post-8 comment never reached it.

Server-Sent Events vs WebSockets for subscriptions

  • Server-Sent Events (SSE): plain HTTP, one-way server-to-client, works through most proxies and with HTTP/2. GraphQL Yoga supports it out of the box (the GraphQL over SSE protocol).
  • WebSockets: two-way, using the graphql-ws protocol (the older subscriptions-transport-ws is deprecated). Needs proxy support for the upgrade and long timeouts.

SSE is like a radio station: the server broadcasts and the client listens. A WebSocket is like a phone call: both sides can talk at any time. Comments arriving on a post only need the radio, so SSE is often simpler when clients only need to receive updates.

Scaling subscriptions across servers

  • Shared pub/sub across servers: the in-memory pub/sub above only reaches subscribers on the same process. With several servers, publish through Redis, NATS, Kafka or a managed service, so an event raised on server A reaches subscribers on server B.
  • Many open connections: each subscriber holds a connection; plan memory and file-descriptor limits, and load-balance per connection.
  • Missed events: a client that disconnects briefly misses events. Have it re-query current state on reconnect (or resume from an event ID), and treat subscriptions as a way to stay fresh, not as the only source of truth.
  • Authorization on every event: check access when subscribing and when delivering, since permissions can change while a subscription is open.
  • Keep payloads small: push an ID or a small change, and let clients fetch more if needed.

Alternatives to subscriptions

For high-frequency data (cursor positions, live game state), a dedicated WebSocket protocol or a real-time service may fit better. For infrequent updates, polling or live queries over cached data can be simpler. Subscriptions suit event-driven updates to specific objects: new comments, order status changes, notifications.

Check yourself

Each subscriber receives only events for the post it's watching. With one global topic, every server receives every comment and filters it for every subscriber, which wastes resources as traffic grows.

Events published on one server never reach subscribers connected to another, because each server has its own memory. A shared broker such as Redis pub/sub or a message queue is needed to fan events out to all servers.

It re-fetches the current comments, or resumes from the last event id if the server supports replay, and then continues with the subscription. Subscriptions only deliver events while connected, so anything during the gap must be recovered explicitly.

When updates are infrequent or a few seconds of delay is fine, polling or refetching on focus is simpler, scales with normal HTTP infrastructure and needs no long-lived connections.

Check authentication when the connection opens, and authorize each subscription and each event, since a user's access can change while they stay connected.