⬡ GraphQL Intermediate

How do GraphQL subscriptions work over WebSocket?

Answer

GraphQL subscriptions use a persistent WebSocket connection between client and server. The client sends a subscription document over the WebSocket, and the server registers a listener on a pub/sub system (e.g., Redis Pub/Sub, in-memory EventEmitter). When the triggering event occurs (e.g., a new message is created), the server publishes to the channel, the subscription resolver is executed for each subscriber, and the resulting data is pushed to the client over their WebSocket. The graphql-ws protocol (or the older subscriptions-transport-ws) standardizes the handshake and message format. Apollo Server and other servers implement this protocol out of the box.