Real-Time Data with GraphQL WebSocket Subscriptions
Implement GraphQL subscriptions over WebSockets with Apollo Server and PubSub for real-time updates pushed to connected clients
GraphQL subscriptions push data to clients over a persistent WebSocket instead of answering one request at a time. The client opens the socket, sends a subscribe operation, and gets a result pushed back every time the event it cares about fires. The stack below does it with Apollo Server, graphql-ws (which speaks graphql-transport-ws) and a PubSub event source, and it goes end to end: schema, resolvers, server, and client.
Two details make or break this in production: the HTTP server must actually host the GraphQL endpoint (a bare http.createServer() does nothing), and each subscription needs a real publisher on the mutation side. Both are covered below.
When to Use This
Reach for subscriptions when the client has to react the instant something changes:
- Live dashboards or activity feeds that update as data changes
- Chat applications where messages appear instantly
- Collaborative editing with cursor presence or field-level updates
- Any scenario where polling is too slow or wasteful
Subscriptions are a poor fit when updates are rare (polling or refetching is cheaper), when the payload is large (emit a small event and let the client refetch), or when you need guaranteed delivery; WebSocket drops lose events unless you add your own replay layer.
Prerequisites
This recipe bolts onto a GraphQL server that already answers queries and mutations. Bring:
- Node.js 18+ with Apollo Server installed (see setting up Apollo Server)
- Express for the HTTP side (
express+cors) - A basic schema with queries and mutations already working
Solution
1. Install Dependencies
npm install @apollo/server @as-integrations/express4 graphql-ws graphql-subscriptions@^2 express cors ws graphql
graphql-subscriptions gives you the in-memory PubSub; graphql-ws speaks the WebSocket protocol the client uses. Version note: the examples pin graphql-subscriptions@^2 because the 3.x line dropped pubsub.asyncIterator (moved to PubSubAsyncIterableIterator), and graphql-redis-subscriptions still speaks the v2 API.
2. Define the Subscription Schema
// schema.ts
import gql from 'graphql-tag';
export const typeDefs = gql`
type Post {
id: ID!
title: String!
content: String!
authorId: ID!
createdAt: String!
}
type Query {
posts: [Post!]!
}
type Mutation {
createPost(title: String!, content: String!): Post!
updatePost(id: ID!, title: String, content: String): Post!
}
type Subscription {
postCreated: Post!
postUpdated(id: ID!): Post!
}
`;
Each subscription field wants an event source backing it. postUpdated(id: ID!) takes an argument, so somebody has to filter events per subscriber; the resolvers below show how.
3. Set Up PubSub and Resolvers
// resolvers.ts
import { PubSub, withFilter } from 'graphql-subscriptions';
const pubsub = new PubSub();
const POST_CREATED = 'POST_CREATED';
const POST_UPDATED = 'POST_UPDATED';
export const resolvers = {
Query: {
posts: (_: unknown, __: unknown, ctx: Context) =>
ctx.db.posts.findMany(),
},
Mutation: {
createPost: async (_: unknown, args: { title: string; content: string }, ctx: Context) => {
const post = await ctx.db.posts.create({
...args,
authorId: ctx.user.id,
createdAt: new Date().toISOString(),
});
// Payload key must match the subscription field name
pubsub.publish(POST_CREATED, { postCreated: post });
return post;
},
updatePost: async (_: unknown, args: { id: string; title?: string; content?: string }, ctx: Context) => {
const post = await ctx.db.posts.update(args.id, {
title: args.title,
content: args.content,
updatedBy: ctx.user.id,
});
pubsub.publish(POST_UPDATED, { postUpdated: post });
return post;
},
},
Subscription: {
postCreated: {
subscribe: () => pubsub.asyncIterator([POST_CREATED]),
},
postUpdated: {
// withFilter filters per subscriber, so each client only gets
// events for the id it asked for
subscribe: withFilter(
() => pubsub.asyncIterator([POST_UPDATED]),
(payload, { id }: { id: string }) => payload.postUpdated.id === id,
),
},
},
};
export { pubsub, POST_CREATED, POST_UPDATED };
Two things worth noticing. asyncIterator takes an array of topic strings, nothing else; passing { topic, payload } objects silently produces a subscription that never fires. And the payload you publish has to be shaped like { [fieldName]: value } because GraphQL resolves the subscription field against it. Get either wrong and clients stay connected but hear nothing; that combination is miserable to debug.
4. Start the HTTP and WebSocket Servers
The catch most snippets skip: the WebSocket server only handles the protocol upgrade. The HTTP side still needs a request handler, or every query and mutation will hang. Mount Apollo’s Express middleware on the same http.Server the WebSocket server attaches to.
// server.ts
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@as-integrations/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/use/ws';
import express from 'express';
import cors from 'cors';
import http from 'http';
import { typeDefs } from './schema';
import { resolvers } from './resolvers';
import { createContext, verifyToken } from './context';
const schema = makeExecutableSchema({ typeDefs, resolvers });
const app = express();
const httpServer = http.createServer(app);
// WebSocket server shares the HTTP server on the /graphql path
const wsServer = new WebSocketServer({ server: httpServer, path: '/graphql' });
const serverCleanup = useServer(
{
schema,
context: async (ctx) => {
const token = ctx.connectionParams?.authorization?.replace('Bearer ', '');
const user = token ? await verifyToken(token) : null;
if (!user) throw new Error('Unauthorized');
return createContext(user);
},
},
wsServer,
);
const apolloServer = new ApolloServer({
schema,
plugins: [
// Graceful shutdown: drain HTTP, then close WS sockets
ApolloServerPluginDrainHttpServer({ httpServer }),
{
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose();
},
};
},
},
],
});
await apolloServer.start();
app.use(
'/graphql',
cors<cors.CorsRequest>(),
express.json(),
expressMiddleware(apolloServer, {
context: async ({ req }) => createContext(req),
}),
);
httpServer.listen(4000, () => {
console.log('Server ready at http://localhost:4000/graphql');
});
Older examples import useServer from graphql-ws/lib/use/ws. That deep path breaks under the package’s exports map in current releases; use graphql-ws/use/ws.
5. Client-Side Subscription
// client.ts
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
import { ApolloClient, InMemoryCache, split, HttpLink, gql } from '@apollo/client';
import { getMainDefinition } from '@apollo/client/utilities';
const wsLink = new GraphQLWsLink(
createClient({
url: 'ws://localhost:4000/graphql',
connectionParams: () => ({
authorization: `Bearer ${getToken()}`,
}),
// Retry with exponential backoff when the socket drops
retryAttempts: 10,
shouldRetry: () => true,
}),
);
const httpLink = new HttpLink({ uri: 'http://localhost:4000/graphql' });
// Route subscriptions over WS, everything else over HTTP
const splitLink = split(
({ query }) => {
const def = getMainDefinition(query);
return def.kind === 'OperationDefinition' && def.operation === 'subscription';
},
wsLink,
httpLink,
);
const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
});
const POST_CREATED_SUBSCRIPTION = gql`
subscription OnPostCreated {
postCreated {
id
title
content
createdAt
}
}
`;
client.subscribe({ query: POST_CREATED_SUBSCRIPTION }).subscribe({
next: ({ data }) => {
console.log('New post:', data.postCreated);
},
error: (err) => console.error('Subscription error:', err),
});
How It Works
- PubSub is nothing fancier than an event emitter scoped to your process.
pubsub.publish(topic, payload)wakes every iterator registered on that topic. asyncIteratorwraps the PubSub stream into an async iterable the GraphQL executor consumes; each published event becomes the field’s next result.graphql-wstakes care of thegraphql-transport-wshandshake: the client sendsconnection_init, the server answersconnection_ack, and from then onsubscribecarries operations whilenextcarries results.withFilterwraps the iterator and drops events that fail its predicate, evaluated per subscriber, so two clients listening for differentidvalues get different streams.splitlink on the client sends subscriptions to the WebSocket link and queries/mutations to HTTP, so oneApolloClienthandles both transports.
Variants
Redis PubSub for Multi-Instance
The in-memory bus stops working the moment a second instance joins.
The in-memory PubSub stops at the process boundary. Publish on instance A and subscribers attached to instance B hear nothing, so behind a load balancer you need graphql-redis-subscriptions:
npm install graphql-redis-subscriptions ioredis
import { RedisPubSub } from 'graphql-redis-subscriptions';
import Redis from 'ioredis';
const pubsub = new RedisPubSub({
publisher: new Redis(process.env.REDIS_URL),
subscriber: new Redis(process.env.REDIS_URL),
});
The API is the same (publish, asyncIterator), so resolvers stay untouched.
Topic-per-Channel Subscriptions
Filtering gets cheaper when the argument happens to be an entity id.
Instead of filtering payloads, put the channel in the topic name and publish to a narrow topic:
// publish only to this post's channel
pubsub.publish(`${POST_UPDATED}.${post.id}`, { postUpdated: post });
// subscriber resolves its own topic
postUpdated: {
subscribe: (_: unknown, { id }: { id: string }) =>
pubsub.asyncIterator([`${POST_UPDATED}.${id}`]),
},
This skips withFilter entirely and does no wasted deliveries. The cost is more topics to keep track of, and wildcards aren’t supported. Per-entity channels fit; broad filters don’t.
Subscription Lifecycle Hooks
useServer lets you hook into each phase of the connection through its options.
Track connects and disconnects for cleanup and metrics:
const serverCleanup = useServer(
{
schema,
onConnect: async (ctx) => {
console.log('Client connected:', ctx.connectionParams);
},
onDisconnect: (ctx, code, reason) => {
console.log('Client disconnected:', code, reason);
},
},
wsServer,
);
Best Practices
A few rules keep a subscriptions deployment boring, which is what you want:
- Authenticate on connection: validate the token in
contextwhen the WebSocket opens, not per event. If permissions can change mid-session, re-check insidewithFilteror the resolver. - Use Redis PubSub in production: a single-process engine can’t reach subscribers sitting on your other instances.
- Filter server-side: publish narrow topics or use
withFilter; never broadcast and filter on the client, since every event still costs bandwidth and may leak data. - Register the drain plugins:
ApolloServerPluginDrainHttpServerplusserverCleanup.dispose()close sockets cleanly on shutdown; without them each deploy strands live connections. - Emit small events: push IDs or lightweight payloads and let clients refetch heavy fields; large payloads over WS amplify serialization cost per subscriber.
Common Mistakes
The failure modes below are the ones that actually bite, roughly in the order people meet them:
- Bare
http.createServer(): without Express (orgraphql-http) mounted, HTTP operations never get a response. The WS upgrade works, which makes the failure confusing. - Passing objects to
asyncIterator: it takes topic strings only.{ topic: X, payload: {...} }produces a silent dead subscription. - Payload key not matching the field name:
publish(TOPIC, { post: p })against a field calledpostCreatedgives every event a null payload, silently. - Using in-memory PubSub in a cluster: events published on one instance never reach subscribers on another.
- Forgetting the client
splitlink: subscriptions routed over HTTP fail outright. - Broadcasting sensitive data: every subscriber on the topic gets the payload; filter per user or per channel.
Troubleshooting
Ordered by symptom, with the most likely cause attached:
- Client connects but receives nothing: check the payload shape first (
{ postCreated: post }), then that something actually callspublishfor that topic, then thewithFilterpredicate. - Subscription works locally but not in production: almost always a load balancer or proxy dropping the
Upgradeheader. Confirm WS pass-through (nginxproxy_set_header Upgrade, ALB stickiness) before touching code. graphql-wsimport fails at runtime: the/lib/deep path doesn’t resolve anymore; switch tographql-ws/use/ws.- Reconnect loop after deploy: drain plugins missing, so the server kills sockets on shutdown. Add them and clients will retry cleanly instead of hammering.
- High memory with many subscribers: each
asyncIteratorbuffers events; drop slow consumers and prefer small payloads.
See Also
- graphql-transport-ws protocol reference: the message flow this recipe uses
- Apollo Server subscriptions docs: the official setup this builds on, including the drain plugins
- graphql-subscriptions: PubSub and
withFilterAPI details - graphql-redis-subscriptions: the multi-instance event engine
- GraphQL DataLoader batching: subscribers trigger resolver work per event; batching keeps it cheap
- Complete Guide to GraphQL Federation: includes the production guidance for realtime services inside a federated graph
Frequently Asked Questions
What transports work for subscriptions besides WebSocket?
WebSocket is the standard transport and the one graphql-ws uses. Server-Sent Events works for one-way server-to-client pushes and several gateways support it, but it can't carry the full bidirectional graphql-transport-ws protocol. HTTP/2 alone doesn't give you a push channel for this.
Is there a realistic ceiling on concurrent subscriptions?
Thousands per instance with graphql-ws; the practical limit is memory and how much work each event triggers. Each subscriber holds an iterator, and every published event runs the filter and serializer per subscriber. Scale out with Redis PubSub and spread connections across instances.
Are there cases where plain polling beats subscriptions?
Pick polling when updates arrive minutes apart, when clients are flaky (mobile networks kill sockets), or when you can't keep long-lived connections through your infra. Subscriptions earn their keep when events fire often, latency is the point, and you control the path between client and server.
What's a sane way to test subscriptions?
Open a real graphql-ws client in your test, subscribe, fire the mutation, and assert the event arrives; the subscriptions-transport-ws-era advice to mock the socket still applies for unit tests, where stubbing pubsub is simpler. Integration tests should hit a real server because the handshake and iterator wiring is where things break.
Does federation change anything for subscriptions?
The gateway pattern for subscriptions is still immature. Apollo Gateway doesn't route subscription operations the way it does queries; teams usually expose subscriptions from a dedicated service or a subgraph clients connect to directly. Check the federation onboarding doc for the surrounding setup.
Are events lost when a client disconnects?
They are gone. graphql-ws has no replay or durability layer; a dropped socket means missed events. If clients must catch up, include a version or timestamp in events and let them refetch the gap on reconnect.
Related Resources
Build a GraphQL API with Apollo Server and TypeScript
How to build a production-ready GraphQL API using Apollo Server, TypeScript, and DataLoader to solve the N+1 query problem
RecipeBatch and Cache Database Queries with GraphQL DataLoader
Implement DataLoader batching in GraphQL resolvers with Apollo Server: collapse N+1 database queries into single batched calls cached per request
RecipeBuild Real-Time APIs with WebSockets on Serverless
How to implement bidirectional real-time communication using WebSockets with AWS API Gateway, Lambda, DynamoDB, and what works in connection management.
RecipeSet Up a GraphQL Federation Gateway with Apollo
Compose multiple GraphQL services into a single federated supergraph using Apollo Federation and a gateway that routes queries across subgraphs.