Collaborative real-time updates
A collaborative editor needs to show changes made by other users as they happen.
GraphQL · Const
GraphQL subscriptions are long-lived operations for receiving incremental updates when server-side events occur. They use fields on a Subscription root type and are started with the subscription keyword.
A GraphQL subscription is a long-lived operation for receiving selected data when server-side events occur. The schema exposes subscription fields on a Subscription root type; clients use the subscription operation keyword, while the server commonly connects those fields to a pub/sub system and a stateful transport.
subscription OperationName { rootField { selectedFields } }A stream of selected GraphQL responses produced as new server-side events occur.
type Review {
rating: Int
commentary: String
}
type Subscription {
reviewCreated: Review
}
subscription NewReviewCreated {
reviewCreated {
rating
commentary
}
}Defines a subscription root field and requests selected fields when the event occurs.
A collaborative editor needs to show changes made by other users as they happen.
A dashboard must display newly arriving metrics without repeated polling.
A client needs notifications whenever a particular domain event is created.
A subscription is a long-lived GraphQL request that delivers selected data for events over time. It is intended for incremental updates that should reach the client close to real time.
Follow-up: Why does a subscription operation have one root field? Each subscription represents one event stream, so its top-level selection must identify exactly one subscription field.
The schema defines fields on a Subscription root object, in the same way Query and Mutation fields are defined. The client starts an operation with the subscription keyword and selects the fields it wants in each update.
Follow-up: How would a client request two event types? Use separate named subscription operations, because one subscription operation cannot contain multiple root fields.
GraphQL leaves transport selection to the server. Implementations commonly use WebSockets or server-sent events, and clients must support the chosen protocol.
Follow-up: Why is transport choice significant? Subscriptions are long-lived and typically stateful, so connection lifecycle and support requirements are greater than for queries and mutations.
QueryMutationSubscription root typeWebSocketsserver-sent eventspub/sub