GraphQL Subscriptions
02 / 02

Scaling & Production Considerations

Scaling & Production Considerations

Scaling Across Instances

An in-memory PubSub only knows about events published within its own process. If a mutation lands on instance A but a subscriber's WebSocket is held open by instance B, that subscriber never hears about it — unless every instance shares a distributed broker.

const { RedisPubSub } = require('graphql-redis-subscriptions');

const pubsub = new RedisPubSub({
  connection: { host: 'redis', port: 6379 },
});
// Every instance publishes to and subscribes from the SAME Redis channels —
// now a mutation on any instance reaches subscribers connected to any other

Connection Lifecycle & Cleanup

Each subscribed client holds open server-side resources for as long as it stays connected — potentially hours, unlike a query's millisecond lifetime. Ping/pong heartbeats (built into graphql-ws) detect and close dead connections that disconnected uncleanly. Missing or buggy unsubscribe/teardown logic when a client disconnects is a real memory-leak source — most standard subscription server setups handle this automatically, but a custom async iterator implementation needs to get it right explicitly.

Testing a Subscription Resolver

test('messageAdded yields the published message', async () => {
  const iterator = resolvers.Subscription.messageAdded.subscribe(
    null, { channelId: 'general' }
  );

  pubsub.publish('MESSAGE_ADDED', {
    messageAdded: { channelId: 'general', text: 'hi' },
  });

  const { value } = await iterator.next();
  expect(value.messageAdded.text).toBe('hi');
});
// No real WebSocket connection needed — treat the async iterator like
// any other testable async stream

When to Reach for Subscriptions

Reserve subscriptions for data where realtime push genuinely matters to the user experience — live chat, live notifications, collaborative editing. For everything else, a regular query (refetched on a user action or a longer interval) avoids the added operational complexity of holding open many long-lived connections.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free