⬡ GraphQL Intermediate

How do you implement real-time subscriptions with GraphQL?

Answer

GraphQL subscriptions require: (1) A WebSocket transport — the standard protocol is graphql-ws (newer, preferred over the older subscriptions-transport-ws). (2) A pub/sub system to broadcast events. In-memory EventEmitter for single-server; Redis pub/sub for multi-server deployments. Apollo Server setup: configure WebSocketServer alongside the HTTP server; use useServer from graphql-ws. Subscription resolver structure: subscribe function (returns an AsyncIterator/AsyncGenerator that yields events) and resolve function (transforms the event into the response shape). Example: Subscription: { messageAdded: { subscribe: (_, { channelId }, { pubsub }) => pubsub.asyncIterableIterator(['MESSAGE_ADDED_' + channelId]), resolve: (payload) => payload.message } }. Trigger from mutations: pubsub.publish('MESSAGE_ADDED_1', { message: newMessage });.