GraphQL Subscriptions over SSE: Real Time Without Being Forced into WebSocket
Subscriptions don’t need a WebSocket. Server-Sent Events are enough for the one-way server-to-client channel, while queries and mutations stay plain HTTP, and the schema decides what counts as a domain event in the first place.
If you set up a WebSocket for a one-way update flow, you bring a second protocol into operations: the upgrade handshake, sticky sessions, proxies and load balancers that need to know about it, plus reconnect and heartbeat as your own responsibility. The reason for it is usually modest – an order changes its status, a dashboard tile updates without a reload. The reason is done after one sprint; the transport stays and needs to be operated for years.
So behind “real time” there is rarely a syntax problem and almost always an operations decision. A bidirectional full-duplex channel, like the one a WebSocket opens, is not a feature you get for free; it is an operations class of its own, with its own protocol, its own handshake and its own failure patterns. That is why this text is less about how to wire up subscriptions and more about the decision before that: SSE, WebSocket or plain polling – decided by operating cost, complexity and scaling, not by what sounds modern right now.
And GraphQL subscriptions don’t even prescribe a WebSocket. The specification is transport-agnostic at this point: it says that a subscription delivers an event stream – not over which wire that stream flows. And for the common case “server informs client,” there is a candidate that has been built into every browser for years and runs over ordinary HTTP: Server-Sent Events.
Queries and mutations stay as they are#
Before we get to the event stream, it’s worth looking at what doesn’t change at all. A query fetches data, a mutation changes state – both are request and response, one request, one response, done. That is plain HTTP, usually a POST /graphql. Nothing about subscription support forces you to touch it. Only the third operation type, the subscription, needs an open channel through which the server sends events over time.
This is exactly where Server-Sent Events come in. SSE is a one-way channel from the server to the client over ordinary HTTP. The server responds with the content type text/event-stream and keeps the connection open; the client opens it through the built-in EventSource interface. The browser takes care of quite a lot that you would have to bolt on painfully in a homegrown solution: it reconnects automatically when the connection drops, and on reconnect it sends the last seen event ID in the Last-Event-ID header so the server can pick up where it left off.
flowchart LR
subgraph Client
UI[Browser app]
end
subgraph Server
GQL[GraphQL server]
end
UI -- "HTTP POST /graphql<br/>Query & Mutation" --> GQL
GQL -- "HTTP response (JSON)" --> UI
GQL -- "text/event-stream<br/>Events via EventSource" --> UIThe diagram shows the core: two channels, one transport. Queries and mutations take the familiar path of request and response. The event stream uses the same HTTP infrastructure; the response just stays open and trickles events through. There is no protocol switch, no upgrade handshake, no special treatment by proxies that don’t know WebSocket frames.
The server side: an AsyncIterable from PubSub#
On the server side, a subscription resolver is not an ordinary field resolver. Instead of a function that returns a value, it is an object with a subscribe method that returns an AsyncIterable. The GraphQL server pulls the events from this iterable and sends them to the matching client. The usual tool for this is the graphql-subscriptions package, currently at version 2.0.0. It comes with a PubSub class whose asyncIterator(topic) creates exactly such an iterable.
import { PubSub, withFilter } from 'graphql-subscriptions';
const pubsub = new PubSub();
const ORDER_STATUS_CHANGED = 'ORDER_STATUS_CHANGED';
const resolvers = {
Subscription: {
orderStatusChanged: {
subscribe: withFilter(
() => pubsub.asyncIterator(ORDER_STATUS_CHANGED),
(payload, variables) =>
payload.orderStatusChanged.customerId === variables.customerId,
),
},
},
Mutation: {
advanceOrder: (_root, { id }) => {
const orderStatusChanged = advanceOrderInStore(id);
pubsub.publish(ORDER_STATUS_CHANGED, { orderStatusChanged });
return orderStatusChanged;
},
},
};
Two things matter here. First, the withFilter helper: it takes the iterator function and a predicate function that decides per event whether it concerns this subscriber at all. That way each customer only gets the status changes of their own orders, even though all of them run over the same topic. Second, the publish point in the mutation: when something happens in the domain – here, an order moves forward – the event is pushed into the stream with pubsub.publish. The subscribe resolver and the mutation are decoupled through the topic; the mutation knows nothing about who is listening right now.
One note that in practice often comes up too late: the bundled PubSub implementation keeps its state in memory and only works within a single process. As soon as several server instances sit behind a load balancer, events fizzle out – one instance publishes, but the subscribers are attached to another. For production you then need an external backend, such as a Redis-backed variant that distributes the publish across the process boundary. For local development and getting started, the built-in variant is completely sufficient.
The SSE endpoint: the stream to the outside#
For the events from the iterable to actually reach the browser, you need an endpoint that delivers the stream as text/event-stream. Conceptually, in Express it looks like this:
app.get('/graphql/stream', (req, res) => {
res.set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});
res.flushHeaders();
const iterator = pubsub.asyncIterator(ORDER_STATUS_CHANGED);
(async () => {
for await (const event of iterator) {
res.write(`event: next\n`);
res.write(`data: ${JSON.stringify(event)}\n\n`);
}
})();
req.on('close', () => {
if (typeof iterator.return === 'function') iterator.return();
});
});
The format of an SSE frame is deliberately simple: lines with field names and a colon. The data: field carries the payload, here the serialized event; the browser would join several data: lines with a line break. With event: you name the event type so the client can listen for it specifically; without that line, everything ends up at the general onmessage handler. The id: field sets the event ID that the browser sends back as Last-Event-ID on reconnect, and retry: specifies in milliseconds how long the browser should wait before trying to reconnect. A frame ends with an empty line, that is, a double \n. Lines that start with a colon are comments and work as a heartbeat to keep intermediate layers from cutting a quiet connection.
The req.on('close') part is not an extra. When the client closes the connection, the iterator has to be shut down cleanly; otherwise subscriptions pile up and the process leaks resources. This cleanup is where an SSE integration becomes either solid or brittle.
The client: EventSource, nothing more#
On the client side, the work is surprisingly small because the browser handles most of it:
const es = new EventSource('/graphql/stream', { withCredentials: true });
es.addEventListener('next', (e) => {
const payload = JSON.parse(e.data);
render(payload.orderStatusChanged);
});
es.onerror = () => {
// The browser reconnects on its own; the retry: field controls the interval.
};
No manual reconnecting, no timer, no heartbeat protocol of your own. If the connection fails, the browser tries on its own to rebuild it and sends the last received event ID along. The withCredentials option makes sure cookies are sent across the origin boundary – handy when authentication runs over a session cookie and the endpoint needs to know who is listening. If you want to place authorization in the GraphQL server cleanly in the execution context, you’ll find the matching pattern in GraphQL auth in the context; the same logic applies to the SSE endpoint – the identity is established at the HTTP layer and is available to the resolver.
sequenceDiagram participant B as Browser (EventSource) participant S as GraphQL server participant P as PubSub B->>S: HTTP POST advanceOrder (mutation) S->>P: pubsub.publish(topic, payload) P-->>S: asyncIterator delivers event S-->>B: data: frame (event: next) Note over B,S: Connection drops B->>S: Reconnect with Last-Event-ID S-->>B: Events since the last ID
The schema is a domain model, not an event pipe#
That outlines the technical part, but the more important point from project practice is a different one. As soon as there is an easy way to send events to the client, the temptation grows to pump everything possible through subscriptions: every keystroke, every internal tick, every log line. But the schema is a domain model, not a collection point for technical signals. A subscription should represent an event that means something in the domain – “order changed its status,” “comment was added,” “payment was received.” An orderStatusChanged tells a consumer something about the domain. A serverTick or internalMetric tells them nothing they would look for in the schema.
The same modeling discipline you apply to lists and paging – see the thoughts in GraphQL pagination and connections – applies here just the same: the schema describes the language of the domain, not the internals of the transport. If an event is not part of that language, it doesn’t belong in a subscription.
Avoiding the wrong abstraction#
That brings us to the actual decision, and it happens one level below GraphQL: in the architecture. SSE, WebSocket and messaging solve different problems, and the most common source of errors is treating one as a substitute for the other.
- Server-Sent Events are one-way from server to client, run HTTP-native, reconnect on their own and carry only UTF-8 text. They fit exactly when the UI should show live updates: status changes, notifications, a dashboard that refreshes itself.
- WebSockets are bidirectional and have their own protocol with their own handshake. They are the right choice when the client itself continuously sends data to the server in real time – chat, collaborative editing, a game state, anything with a busy back channel.
- Messaging and brokers such as Kafka, AMQP or Redis solve integration between systems. They offer persistence, fan-out and decoupling in the backend. A GraphQL subscription doesn’t replace that. It covers the last mile to the browser; the nervous system between the services remains the broker’s job.
If you keep these three cleanly apart, you won’t build the wrong thing. If you mix them – say, setting up a WebSocket to serve a purely one-way update flow, or misusing subscriptions to integrate services – you pay later with complexity that no feature justifies.
Decision framework: SSE, WebSocket or polling#
Separating the transports cleanly is one thing; in a project I eventually have to pick one, and a framework along three axes helps with that: operating cost, complexity and scaling. These three questions answer the transport choice more reliably than any feature list, because they ask about the price in operations, not about the feature set.
Polling is the honest starting point that people skip too quickly. The client asks at an interval, “is there anything new?”, and across HTTP, caching and load balancers that is the best-understood pattern of all. The operating cost is conceptually close to zero, but the load on the server grows linearly with the number of clients and the frequency, and most of the work goes into empty responses. The complexity is minimal because there is no open channel that would need cleanup or reconnects, and scaling horizontally is trivial because each request stands on its own. For updates in the range of seconds to minutes, where a bit of latency hurts no one, polling is often the economically right answer – and the option you should check first, before you build something more elaborate.
SSE sits in the middle and hits exactly the case “server informs client promptly.” The operating cost consists of one open HTTP connection per client, but it stays HTTP-native and requires no special handling in the infrastructure. The complexity is low on the client because EventSource comes with reconnect and Last-Event-ID; on the server, the effort lies mainly in cleaning up the streams properly. Scaling has its cost center in the many open connections, and the PubSub state has to be distributed across instance boundaries as soon as more than one process runs. The gain over polling is low latency without idle traffic; the price is the open channel you have to operate.
WebSocket is the most expensive class and only justifies itself with a real back channel. The operating cost includes a protocol of its own with a handshake, sticky sessions and proxies that need to know about the upgrade. The complexity rises because reconnect, heartbeat and state recovery are on me, not on the browser. Scaling is hardest because long-lived, stateful connections are the least easy to distribute horizontally. This effort pays off when the client itself sends continuously in real time – chat, collaborative editing, game state. For a one-way update flow, it is effort without return.
So the decision criterion is short: first check whether polling is enough; if you need prompt server-to-client updates without a back channel, SSE; and WebSocket only for busy, bidirectional traffic. If you ask in this order, you pick the cheapest transport that meets the requirement instead of the most powerful one you know – and exactly this order separates an operations decision from a matter of taste.
Where the SSE idea comes from – and what applies today#
The combination of GraphQL and SSE is not new, and its history helps put today’s state in context. In the early days of Apollo Client, the 1.x era, there was the subscriptions-transport-sse package. Back then, it was plugged into an Apollo Client through the networkInterface concept:
// HISTORICAL — Apollo Client 1.x, not today's API.
import {
SubscriptionClient,
addGraphQLSubscriptions,
} from 'subscriptions-transport-sse';
const sseClient = new SubscriptionClient('/subscriptions');
const client = new ApolloClient({
networkInterface: addGraphQLSubscriptions(httpInterface, sseClient),
});
This is explicitly legacy and has no place in a new project. Both networkInterface and the SubscriptionManager of that time – the predecessor of today’s pattern with PubSub.asyncIterator – are concepts of a generation that was replaced long ago. I show the fragment only to make the origin of the idea visible: SSE as a transport for GraphQL events is an old idea, not an experimental one.
On the WebSocket side, it’s worth looking at the current state because it frames the transport question. The formerly common subscriptions-transport-ws is now considered unmaintained; its repository has carried a deprecation notice for quite a while and is no longer actively developed. The recommended successor for the WebSocket path is graphql-ws, with a different subprotocol that is not compatible with the old one. That is only context here: graphql-ws is the answer when you actually need a WebSocket. It doesn’t compete with SSE; it covers the other, bidirectional case.
What I take away from practice#
When someone says “real time” in a requirements conversation, the first useful follow-up question is not “WebSocket or SSE?” but “In which direction does the data flow, and how fast does it need to arrive?” Usually it flows from the server to the client and can tolerate some latency, and then Server-Sent Events are the calmer solution that is easier to operate: ordinary HTTP, built-in reconnect, no special handling in the infrastructure. Queries and mutations stay untouched; only the event stream gets its own open channel. On the server, the subscribe resolver returns an AsyncIterable from a PubSub, events come in via publish, and withFilter makes sure everyone only gets what concerns them.
You can feel the gain of this mapping in everyday project work. If you choose the cheapest viable transport, you shorten the cycles to a working live update, because half of the infrastructure discussion this text started with goes away. You reduce friction in operations, because an HTTP-native stream creates fewer special cases in proxies, load balancers and deployments. And you raise quality, because the schema stays a domain model and only carries events that mean something in the language of the domain. I deliberately keep two limits in view: the built-in PubSub keeps its state in memory and needs an external backend across multiple instances, and the transport choice remains a simple mapping – polling when latency is acceptable, SSE for the one-way path to the client, WebSocket only for a real back channel. These clear limits are what make the shorter cycles and lower friction possible in the first place.
Further reading#
- MDN – Using server-sent events: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
- MDN – EventSource: https://developer.mozilla.org/en-US/docs/Web/API/EventSource
- graphql-subscriptions (README/API): https://github.com/apollographql/graphql-subscriptions
- graphql-subscriptions (npm): https://www.npmjs.com/package/graphql-subscriptions
- Apollo Server – Subscriptions: https://www.apollographql.com/docs/apollo-server/data/subscriptions
- subscriptions-transport-ws (legacy/archived): https://github.com/apollographql/subscriptions-transport-ws
- subscriptions-transport-sse (historical origin): https://github.com/CodeCommission/subscriptions-transport-sse
- GraphQL Spec: https://spec.graphql.org/
Revised and translated from German with the help of AI.