Overview of GraphQL Subscription Support
Enable clients to receive real-time updates
GraphQL subscriptions enable clients to manage real-time data updates effectively, without the need for constant polling. This is particularly crucial in applications that need live updates, such as notifications, stock tickers, or chat applications. Using subscriptions improves performance and user experience by ensuring that clients receive the latest information as soon as changes occur on the backend.
subscription OnStockPricesChanged {
stockPricesChanged {
symbol
price
}
}
The router supports both the callback and multipart protocols for handling subscriptions. With subscription support enabled, you can add Subscription
fields to the schema of any subgraph that supports common WebSocket protocols for subscription communication:
type Subscription {
stockPricesChanged: [Stock!]!
}
What are subscriptions for?
GraphQL subscriptions enable clients to receive continual, real-time updates whenever new data becomes available. Unlike queries and mutations, subscriptions are long-lasting. That means a client can receive multiple updates from a single subscription:
Subscriptions are best suited to apps that rely on frequently changing, time-sensitive data such as stock prices, IoT sensor readings, live chat, or sports scores.
How subscriptions work
A client executes a GraphQL subscription operation against your router over HTTP:
GraphQLExample subscription1subscription OnStockPricesChanged { 2 stockPricesChanged { 3 symbol 4 price 5 } 6}
The client doesn't use a WebSocket protocol. Instead, it receives updates via multipart HTTP responses.
By using HTTP for subscriptions, clients can execute all GraphQL operation types over HTTP instead of using two different protocols.
Apollo Client, Apollo Kotlin, and Apollo iOS all support GraphQL subscriptions over HTTP with minimal configuration. See each library's documentation for details. Apollo Client also provides network adapters for the Relay and urql libraries.
When your router receives a subscription, it executes that same subscription against whichever subgraph defines the requested field—
stockPricesChanged
in the code snippet above.This communication usually does use a WebSocket subprotocol, for compatibility with most subgraph libraries.
With a self-hosted router, you can also configure an HTTP-callback-based protocol.
The subgraph periodically sends new data to your router. Whenever it does, the router returns that data to the client in an additional HTTP response part.
A subscription can include federated entity fields that are defined in other subgraphs. If it does, the router first fetches those fields by querying the corresponding subgraphs, such as the Portfolios subgraph in the diagram above. These queries use HTTP as usual.