⬡ GraphQL Advanced

How do you scale GraphQL subscriptions using Redis pub/sub?

Answer

A single-server GraphQL subscription implementation (using in-memory EventEmitter) does not scale horizontally — a mutation on Server A cannot notify a subscriber connected to Server B. Redis Pub/Sub solves this by providing a shared message bus. When a mutation occurs, the resolver publishes to a Redis channel: pubsub.publish("MESSAGE_ADDED", { messageAdded: newMessage }). Each server instance subscribes to the Redis channel and pushes events to its connected WebSocket clients. graphql-redis-subscriptions wraps Redis into a GraphQL PubSubEngine. For very high subscriber counts, consider Redis Cluster for horizontal scaling and fan-out patterns where a single publish reaches sharded channels. Apollo Router (Federation gateway) can handle subscription routing, avoiding the need for clients to know which subgraph handles a given subscription. Proper backpressure handling, connection cleanup on client disconnect, and TTL-based channel cleanup are essential for production reliability.