Budi is waiting for This Earth of Mankind to be back in stock. He can phone the shop every 5 minutes, "is it in yet?", when the answer is almost always "not yet". That's polling. Or he leaves his phone number with the cashier, who texts him the moment the stock arrives.
The second way is a subscription, GraphQL's third kind of operation after query and mutation. A query asks once and is done. A subscription says "tell me every time this changes", and the server then pushes data over a connection that stays open.
The schema and the subscribe resolver
In the schema, subscriptions have a root type of their own:
type Subscription {
stockChanged(bookId: ID!): Book!
}
Budi sends this operation. A subscription may select only one top-level field. An unnamed one that selects two is refused with Anonymous Subscription must select only one top level field. A named one gets its name in the message: Subscription "WatchStock" must select only one top level field.
subscription WatchStock($bookId: ID!) {
stockChanged(bookId: $bookId) {
title
status
}
}
On the server, a subscription field has a subscribe resolver that returns a stream of events (an AsyncIterable). The events are sent by the mutation through a PubSub. With the graphql-subscriptions package, version 3:
import { PubSub, withFilter } from "graphql-subscriptions";
const pubsub = new PubSub();
const resolvers = {
Mutation: {
updateStock: (_, { id, stock }, context) => {
// ...check for staff and change the stock as in the earlier lessons
pubsub.publish("STOCK_CHANGED", { stockChanged: { ...book } });
return book;
},
},
Subscription: {
stockChanged: {
subscribe: withFilter(
() => pubsub.asyncIterableIterator("STOCK_CHANGED"),
(payload, args) => String(payload.stockChanged.id) === args.bookId,
),
},
},
};
publish("STOCK_CHANGED", ...)broadcasts an event to everyone listening on that topic.asyncIterableIterator(calledasyncIteratorin version 2) gives one subscriber its stream of events.- Each event runs like a small query, with the event as the root value.
stockChangedis read frompayload.stockChanged, thentitleandstatusare filled in as usual. So Budi gets one response per event:{ "data": { "stockChanged": { "title": "This Earth of Mankind", "status": "IN_STOCK" } } }. - The event holds a copy,
{ ...book }, not the row itself. The event runs a moment later; if it held the row and the stock changed twice quickly, both messages could carry the last stock.
Filtering per subscriber
Every stock change goes to the same topic. withFilter filters per subscriber: its second function gets the event and that subscriber's arguments, and only events that pass go through. Budi subscribed with bookId: "2". Then Sari, a staff member, sets the stock of The Rainbow Troops to 11, and that event has id: 1. The filter returns false, so Budi gets nothing. As soon as Sari sets the stock of This Earth of Mankind to 7, the filter passes and Budi gets status: "IN_STOCK".
Transport: WebSocket with graphql-ws
The GraphQL spec doesn't say how events travel. The most common way is a WebSocket with the protocol of the graphql-ws package (version 6.3.0). Here is the real conversation, recorded from an actual graphql-ws server:
| Direction | Message |
|---|---|
| Budi → server | {"type":"connection_init","payload":{"authorization":"Bearer token-budi"}} |
| server → Budi | {"type":"connection_ack"} |
| Budi → server | {"id":"1","type":"subscribe","payload":{"query":"subscription WatchStock(...) {...}","variables":{"bookId":"2"}}} |
| server → Budi | {"id":"1","type":"next","payload":{"data":{"stockChanged":{"title":"This Earth of Mankind","status":"IN_STOCK"}}}} |
| Budi → server | {"id":"1","type":"complete"} |
- The WebSocket opens with the subprotocol
graphql-transport-ws. The first message must beconnection_init; the server answersconnection_ack. subscribestarts one operation with anid. Each event comes asnextwith the sameid.completefrom the client means stop; from the server it means the operation is finished. A validation error comes as{"type":"error"}, andping/pongkeep the connection alive.
On the client:
import { createClient } from "graphql-ws";
const client = createClient({
url: "wss://api.bookshop.test/graphql",
connectionParams: { authorization: "Bearer token-budi" },
});
const stop = client.subscribe(
{ query: WATCH_STOCK, variables: { bookId: "2" } },
{ next: (response) => console.log(response.data), error: console.error, complete: () => {} },
);
You may run into the old library subscriptions-transport-ws. Its last release is 0.11.0 (November 2021), and the package is marked deprecated on npm with a message to move to graphql-ws. The protocols differ and don't work together. Confusingly, that old library's subprotocol is named graphql-ws.
Auth in connection_init
A WebSocket in the browser can't be given an Authorization header. That's why the token travels in the connection_init payload, and the server checks it once per connection:
import { WebSocketServer } from "ws";
import { useServer } from "graphql-ws/use/ws";
const wsServer = new WebSocketServer({ port: 4000, path: "/graphql" });
useServer(
{
schema,
// Once per connection. false: the connection is closed with code 4403 Forbidden.
onConnect: async (ctx) => Boolean(await userFromBearer(ctx.connectionParams?.authorization)),
// For each operation on that connection.
context: async (ctx) => ({ user: await userFromBearer(ctx.connectionParams?.authorization) }),
},
wsServer,
);
- A fake token:
onConnectreturnsfalse, and the connection closes with code4403and the reasonForbidden. - Sending
subscribebeforeconnection_ack: closed with4401 Unauthorized. - Field rules still run on every event. If Budi (a customer) also asks for
stock, everynextmessage carriesstock: nulland aFORBIDDENerror, just as in the "Authentication & Authorization" lesson.
Alternative: SSE with graphql-sse
Server-Sent Events (SSE) use one ordinary HTTP request whose answer keeps flowing. The graphql-sse package (version 2.6.2) uses it for subscriptions. The client sends POST /graphql/stream with Accept: text/event-stream, and the server answers 200 with content-type: text/event-stream; charset=utf-8, then each event:
event: next
data: {"data":{"stockChanged":{"title":"This Earth of Mankind","status":"IN_STOCK"}}}
Because it's plain HTTP, the token simply goes in the Authorization header, and proxies or load balancers that understand HTTP need no special setup. It only flows from server to client; a client that wants to send something uses an ordinary HTTP request. For a subscription that only listens, that's enough.
Subscription or polling?
Polling every 5 seconds means 12 requests a minute for each user, even when the stock doesn't change. A subscription only sends a message when there's an event. But subscriptions have a cost: every user holds an open connection, and an in-memory PubSub only works inside one server process. With more than one server, events must go through something shared, such as Redis PubSub. Use subscriptions for small, frequent changes that must arrive fast (chat, stock, notifications). For data that rarely changes, polling or a plain refetch is simpler.
⚠️ What makes a subscription go quiet, go astray, or leak
- An in-memory PubSub with more than one server. A mutation on server A isn't heard by subscribers on server B. Use a shared PubSub (Redis and the like).
- Forgetting the filter. Without
withFilter, every subscriber gets every book's changes. - The token in the WebSocket URL. URLs often end up in logs. Send it through
connectionParams. - Mixing the two protocols. A
graphql-wsclient can't talk to asubscriptions-transport-wsserver, and the other way round.
TL;DR: A subscription is the operation for receiving real-time data: type Subscription { stockChanged(bookId: ID!): Book! }, one top-level field per operation. The subscribe resolver returns a stream of events (say pubsub.asyncIterableIterator("STOCK_CHANGED")), the mutation calls pubsub.publish, and each event runs like a small query, so there is one response per event. withFilter makes Budi receive only the changes of the book he watches. The common transport is a WebSocket with graphql-ws: connection_init, connection_ack, subscribe, next, complete, with the token in the connection_init payload (a fake token: 4403 Forbidden). subscriptions-transport-ws is no longer maintained (last release 2021) and is marked deprecated on npm. SSE with graphql-sse is the alternative over plain HTTP. A subscription is cheaper than polling for data that changes often, but needs open connections and a shared PubSub when there's more than one server.
⚡ Subscriptions: the server lets you know
Write:
subscription WatchStock($bookId: ID!) {
stockChanged(bookId: $bookId) {
title
status
}
}
Meaning: A subscription is the operation for receiving data in real time as soon as an event happens on the server. Budi doesn't have to keep asking. Every time book 2's stock changes, the server sends one response over a connection that stays open.
⚡ The mutation broadcasts an event
Write:
pubsub.publish("STOCK_CHANGED", { stockChanged: { ...book } });
Guess first: Budi subscribed with bookId: "2". Sari changes the stock of The Rainbow Troops (book 1). Does Budi get a message?
No. Every stock change goes to the same topic, but withFilter only lets through events whose id matches Budi's bookId.
Meaning: The mutation broadcasts the event through a PubSub, the subscribe resolver gives each subscriber its own stream of events, and withFilter filters them per subscriber.
⚡ Subscription or polling?
Meaning: Polling every 5 seconds means 12 requests a minute for every user, even when the stock doesn't change. A subscription only sends a message when there's an event, but every user holds one open connection, usually a WebSocket with graphql-ws.