What are Subscriptions
A reader is looking at the page for The Salt Road when someone else posts a review. With queries alone, the page only sees it after a refresh. A subscription lets the page say "tell me when a review is added to this book" once, and the server pushes each new review as it arrives.
The rule
Subscribe once; receive one result each time the event fires.
Subscriptions are the third operation type, with their own root type in the schema:
type Subscription {
reviewAdded(bookId: ID!): Review!
}A client subscribes with the subscription keyword and, as always, selects fields:
subscription NewReviews($bookId: ID!) {
reviewAdded(bookId: $bookId) {
rating
text
}
}The difference is in timing. A query or mutation gets one response. A subscription stays open, and every time a matching review is added the server sends another response in the selection's shape:
{ "data": { "reviewAdded": { "rating": 5, "text": "Could not put it down." } } }This continues until the client unsubscribes or the connection closes.
Because the server must push, a single HTTP request and reply is not enough. Subscriptions usually travel over a WebSocket (a two-way connection that stays open) or Server-Sent Events (a one-way stream from server to client over HTTP). Client libraries hide these details.
A subscription operation must have exactly one root field. To listen for two kinds of events, open two subscriptions.
Use subscriptions for small, frequent changes the user should see straight away: new reviews, chat messages, a live auction price. For data that changes rarely, such as a daily bestseller list, re-running a query now and then (polling) is simpler and cheaper, since every open subscription holds a connection on the server.