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.
The shortcut
To choose between a query and a subscription, ask "does the user need to see a change the moment it happens?" Yes and it is small → subscription. No → query, re-fetched when needed.
Load the page
A normal query fetches the book and its current reviews.
The trap is using a subscription to load a page's initial data. Subscriptions report changes from now on; load the current state with a query.
Drills
Answer fast — trust the rule.
How many responses does one subscription produce?
Which transport is typical for subscriptions?
Is subscription { reviewAdded(bookId: "b1") { rating } priceChanged(bookId: "b1") { price } } valid?
Which feature fits a query re-run occasionally better than a subscription?
Remember
- Subscribe once; receive one result each time the event fires.
- Need to see a small change the moment it happens? Subscription. Otherwise a query.
- Trap: subscriptions report changes, not the current state; load that with a query.
