What Are GraphQL Subscriptions?
A GraphQL subscription is the third root operation type alongside query and mutation, but instead of returning a single response it opens a long-lived connection over which the server pushes a stream of payloads whenever a specific event occurs. Where a query is a one-time pull of data, a subscription is a standing request: the client declares 'notify me whenever X changes' and the server keeps that channel open, re-running a lightweight resolver each time the underlying event fires and streaming the shaped result back down the same connection.
Cricket analogy: A subscription is like following ball-by-ball commentary of a Virat Kohli innings on a cricket app instead of refreshing the scorecard page after every over — you open one channel and every run, wicket, or boundary pushes an update to you automatically.
The Subscription Lifecycle
On the server, a subscription resolver has two parts: a subscribe function that returns an AsyncIterator — typically sourced from a pub/sub system — and an optional resolve function that reshapes each published event into the exact response shape the client asked for. When the client sends a subscription document, the GraphQL execution engine calls subscribe once to obtain the iterator, then for every value the iterator yields it runs the normal field-resolution pipeline against that value and pushes the resulting payload to the client, keeping the connection open until the client unsubscribes or the server closes it.
Cricket analogy: The subscribe function is like a stadium's PA system tuning into the umpire's decision-review channel, while resolve is the commentator translating each raw signal — out, not out, wide — into the exact phrase broadcast to viewers at home.
type Subscription {
commentAdded(postId: ID!): Comment!
}
# Resolver (Node.js / graphql-js style)
const resolvers = {
Subscription: {
commentAdded: {
subscribe: (_parent, { postId }, { pubsub }) =>
pubsub.asyncIterator(`COMMENT_ADDED_${postId}`),
resolve: (payload) => payload.commentAdded,
},
},
};
# Client operation
subscription OnCommentAdded($postId: ID!) {
commentAdded(postId: $postId) {
id
body
author { name }
}
}Transport: WebSockets and SSE
Because HTTP request/response cycles cannot hold a channel open indefinitely, subscriptions run over a bidirectional or server-push transport — almost always WebSockets today via the graphql-ws protocol (the successor to the older, now-deprecated subscriptions-transport-ws protocol), though Server-Sent Events are gaining traction for simpler, unidirectional streaming use cases. The client sends a connection_init message to establish the socket and authenticate, then issues a subscribe message per active subscription; the server responds with a stream of next messages carrying each payload and a final complete message when the subscription ends.
Cricket analogy: Switching from HTTP to WebSockets for subscriptions is like upgrading from sending a runner back and forth with score updates to laying a direct radio line between the scorer's box and the commentary booth for the whole match.
graphql-ws and the older subscriptions-transport-ws use different, incompatible sub-protocols during the WebSocket handshake. Mixing a graphql-ws client with an Apollo Server still configured for subscriptions-transport-ws (or vice versa) will fail the connection silently in some setups — always confirm both ends agree on the same protocol string.
Scaling Subscriptions with PubSub
The default in-memory PubSub implementation shipped with libraries like graphql-subscriptions only broadcasts events within a single Node.js process, which breaks the moment an application is horizontally scaled across multiple server instances behind a load balancer — an event published on instance A never reaches a client whose WebSocket connection landed on instance B. Production deployments swap the in-memory implementation for a distributed backend such as Redis pub/sub, Kafka, or Google Pub/Sub, so any instance can publish an event and every instance holding a matching subscriber connection receives and forwards it.
Cricket analogy: In-memory PubSub failing across servers is like a stadium announcer's microphone only reaching one stand — fans in the stand connected to a different speaker system never hear that Rohit Sharma just reached his century.
Subscriptions hold a connection and often a resolver context open per client for the lifetime of the subscription. Unbounded subscription counts, missing authentication on the WebSocket handshake, or forgetting to clean up listeners on disconnect are common causes of memory leaks and denial-of-service exposure in production GraphQL servers — always enforce connection limits and timeouts.
When to Use — and Avoid — Subscriptions
Subscriptions are the right tool for genuinely event-driven, low-latency use cases: chat messages, live notifications, collaborative document editing cursors, order-status tracking, or live dashboards where seconds matter. They are the wrong tool for data that changes infrequently or where a client can tolerate polling every few minutes — maintaining thousands of idle WebSocket connections for rarely-changing data wastes server resources compared to a simple polled query or a cache-friendly REST endpoint with conditional requests.
Cricket analogy: Using subscriptions for a live scorecard during a T20 final makes sense, but keeping a socket open for something like a player's career batting average — which changes maybe once a week — is like stationing a live commentator just to announce a stat that barely moves.
- Subscriptions are the third GraphQL root operation type, delivering a stream of pushed payloads over a persistent connection rather than a single response.
- Server resolvers implement a
subscribefunction returning an AsyncIterator and an optionalresolvefunction that reshapes each event. graphql-wsis the modern WebSocket sub-protocol; it is incompatible with the deprecatedsubscriptions-transport-wsprotocol.- The default in-memory PubSub does not work across multiple server instances — use Redis, Kafka, or similar for horizontal scaling.
- Server-Sent Events are a lighter-weight alternative transport for unidirectional streaming use cases.
- Always enforce authentication, connection limits, and cleanup on disconnect to avoid resource leaks and DoS exposure.
- Reserve subscriptions for genuinely event-driven, low-latency data; prefer polling or cache-friendly queries for infrequently changing data.
Practice what you learned
1. What are the two parts of a GraphQL subscription resolver?
2. Why does the default in-memory PubSub break in a horizontally scaled deployment?
3. Which transport protocol is the modern standard for GraphQL subscriptions over WebSockets?
4. Which use case is the best fit for a GraphQL subscription rather than a polled query?
5. What message does a `graphql-ws` client send first to establish and authenticate a subscription connection?
Was this page helpful?
You May Also Like
Pagination Patterns: Cursor vs Offset
Compare offset-based and cursor-based pagination in GraphQL, and understand why the Relay connection spec is the industry-standard approach.
Directives in GraphQL
Understand built-in and custom GraphQL directives, how they alter query execution and schema behavior, and where to apply them safely.
Authentication and Authorization in GraphQL
Learn how to authenticate requests and enforce field-level authorization in a GraphQL API, and avoid common security pitfalls.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics