Subscriptions over WebSockets and SSE

Intermediate · 5 min

Carry subscriptions over server-sent events with no setup, or WebSockets with graphql-ws, and choose by proxies, auth and connection limits.

Before thisSubscriptions

Jamie Barton · 5 min

Subscriptions over WebSockets and SSE

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Jamie BartonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • The GraphQL spec says nothing about transport. Subscriptions ride on either server-sent events over ordinary HTTP or WebSockets with the `graphql-ws` protocol.
  • With Yoga, SSE needs no setup: a subscription request, GET or POST, gets back `event: next` messages and a final `event: complete`.
  • WebSockets need a second server layer, here `ws` plus `graphql-ws`, and a client that speaks that protocol; in return the connection is bidirectional and one socket can carry many subscriptions.
  • SSE is plain HTTP, so it passes through proxies, reuses your auth headers and works with HTTP/2 multiplexing, but browsers limit HTTP/1.1 connections per origin.
  • Pick SSE by default for server-to-client events; reach for WebSockets when you need a long-lived socket for other traffic too.

The problem: the spec has no wire format

A subscription is a stream of results. The GraphQL specification describes the operation and its execution and says almost nothing about how bytes move. That is why queries over HTTP are a convention and subscriptions have two competing ones.

You have a connection that must stay open while the server pushes data, and you have two mature ways to get it: server-sent events (SSE), which is one long HTTP response, and WebSockets, which is a separate protocol that upgrades an HTTP connection. Both work with the same schema and the same resolvers from the last lesson.

Server-sent events

SSE is a streamed HTTP response with Content-Type: text/event-stream. The server writes blocks of text separated by blank lines. The browser’s EventSource reads them, and so does fetch with a stream reader.

With Yoga there is nothing to install. Any subscription request gets a stream back. This is the raw output from a server on Yoga 6.1.0, subscribing to a countdown:

$ curl -N -H 'accept: text/event-stream' \
    'localhost:4103/graphql?query=subscription%7Bcountdown(from:2)%7D'
:

event: next
data: {"data":{"countdown":2}}

event: next
data: {"data":{"countdown":1}}

event: next
data: {"data":{"countdown":0}}

event: complete
data:

A leading : line is a comment that keeps the connection warm. Each result is an event: next. The stream ends with event: complete. Notice the request is a GET with the query in the URL, which is what a browser EventSource sends. A POST with a JSON body and no Accept header gets the same text/event-stream response from Yoga; I checked.

Properties that follow from “it is just HTTP”:

  • Proxies, load balancers and CDNs already understand it.
  • Auth works the way it does for every other request: cookies, Authorization headers.
  • It is one-way, server to client. Mutations still go in separate requests.
  • Over HTTP/1.1 a browser allows only about six connections per origin, and each open subscription uses one. Open several tabs and you can starve the page’s own requests. HTTP/2 multiplexes many streams over one connection and removes the limit, so serve over HTTP/2 in production.

WebSockets with graphql-ws

A WebSocket is a long-lived, two-way connection that begins life as an HTTP request and then switches protocol. A WebSocket carries opaque messages, so the client and server need an agreed GraphQL protocol on top. The one to use is graphql-transport-ws, implemented by the graphql-ws library; the older subscriptions-transport-ws package is no longer maintained.

Yoga does not handle the upgrade itself, so you add a ws server and hand it to graphql-ws. This is the Yoga recipe, running on graphql-ws 6.4.3 and ws 8.23.0:

import { createServer } from 'node:http';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/use/ws';

const yoga = createYoga({ schema });
const server = createServer(yoga);
const wss = new WebSocketServer({ server, path: yoga.graphqlEndpoint });

useServer(
  {
    execute: (args) => args.rootValue.execute(args),
    subscribe: (args) => args.rootValue.subscribe(args),
    onSubscribe: async (ctx, id, payload) => {
      const { schema, execute, subscribe, contextFactory, parse, validate } =
        yoga.getEnveloped({
          ...ctx,
          req: ctx.extra.request,
          socket: ctx.extra.socket,
          params: payload,
        });

      const args = {
        schema,
        operationName: payload.operationName,
        document: parse(payload.query),
        variableValues: payload.variables,
        contextValue: await contextFactory(),
        rootValue: { execute, subscribe },
      };

      const errors = validate(args.schema, args.document);
      if (errors.length) return errors;
      return args;
    },
  },
  wss,
);

server.listen(4100);

That glue lets Yoga’s plugins and context apply to socket operations too. Then the client:

import { createClient } from 'graphql-ws';
import { WebSocket } from 'ws'; // in a browser, omit this

const client = createClient({ url: 'ws://localhost:4100/graphql', webSocketImpl: WebSocket });

client.subscribe(
  { query: 'subscription { countdown(from: 2) }' },
  { next: (d) => console.log(d), error: console.error, complete: () => console.log('done') },
);

I ran the SSE and WebSocket clients against one server at the same time, plus a postCreated subscription on both, and a mutation in the middle. The mutation’s event arrived on the socket and on the SSE stream. The WebSocket countdown printed:

{"data":{"countdown":2}}
{"data":{"countdown":1}}
{"data":{"countdown":0}}
done

A socket multiplexes many subscriptions over one connection, and the client sends its credentials once, in a connection_init message, rather than on every request. Browsers cannot set custom headers on a WebSocket, which is why that handshake exists.

Which to choose

SSE WebSocket
Server setup in Yoga none ws plus graphql-ws glue
Direction server to client both ways
Auth normal HTTP headers and cookies connection_init payload or cookies
Proxies works anywhere HTTP does needs upgrade support
Limits six connections per origin on HTTP/1.1 none comparable

Default to SSE for pushing events to a page. Choose WebSockets when you already need a socket for other reasons, or your infrastructure handles them better than long streaming responses. The best protocol is the one your clients, proxies and auth already support.

What the video covers

Jamie Barton’s five-minute video, “GraphQL Subscriptions with Server Sent Events,” is from 2022. Its description says subscriptions let you subscribe to data changes and suggests chat and notifications as uses, and the title names SSE as the transport. It does not mention the graphql-ws WebSocket route, so the WebSocket section is this lesson’s own. Laurin Quast’s talk from The Guild, a Yoga maintainer team, covers production issues and is listed below.

Where this fits

You can now deliver a stream of results to a client. A different delivery question is how to send one result in pieces, so the fast parts of a page arrive first. Next: defer and stream.

Check yourself

  1. 01What does a server-sent events response to a subscription look like on the wire?

    A `text/event-stream` response with one `event: next` block per result, each carrying a JSON `data:` line, and a closing `event: complete` when the subscription ends.

  2. 02Why does a WebSocket subscription need extra server setup that SSE does not?

    WebSockets upgrade a connection away from ordinary HTTP request handling, so the server needs a WebSocket server and a GraphQL protocol handler on top. SSE is a normal streamed HTTP response.

  3. 03What is the connection limit that affects SSE in browsers?

    Over HTTP/1.1 a browser opens only a handful of connections per origin, about six. Each open subscription uses one, so many tabs can exhaust it; HTTP/2 multiplexes many streams over one connection and removes the problem.

  4. 04Which WebSocket subprotocol should a new project use?

    The `graphql-transport-ws` protocol implemented by the `graphql-ws` library. The older `subscriptions-transport-ws` library is unmaintained.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark