GraphQLgraphqlsubscriptionswebsocketreal-timeproduction-ready

GraphQL Subscriptions with WebSocket

Real-time GraphQL subscriptions using WebSocket transport for live data updates, with proper connection lifecycle management and authentication.


title: "GraphQL Subscriptions with WebSocket" description: "Real-time GraphQL subscriptions using WebSocket transport for live data updates, with proper connection lifecycle management and authentication." category: "GraphQL" language: "typescript" tags: ["graphql", "subscriptions", "websocket", "real-time", "production-ready"] createdAt: "2025-04-05" updatedAt: "2025-04-20"

Overview

GraphQL subscriptions provide real-time data delivery over WebSocket connections. This pattern uses the graphql-ws protocol (replacing the deprecated subscriptions-transport-ws) with proper authentication, filtered event delivery, and connection lifecycle management.

When to Use

  • Live chat or messaging features where users need instant message delivery
  • Dashboard updates that reflect database changes without polling
  • Collaborative editing where multiple users see changes in real time
  • Status indicators (online/offline) that update across connected clients

Notes

  • Use withFilter to prevent broadcasting events to unrelated subscribers
  • Always authenticate during the onConnect phase before accepting subscriptions
  • Create fresh PubSub instances per server (in-memory PubSub does not scale horizontally)
  • For production at scale, replace the in-memory PubSub with Redis-backed pub/sub (graphql-redis-subscriptions)
  • Handle disconnection cleanup to update user state and notify other subscribers
  • The graphql-ws library implements the newer GraphQL over WebSocket protocol; do not mix it with the legacy subscriptions-transport-ws