@defer and @stream
The book page shows the title and price instantly from a fast table, but the reviews come from a slow service that takes two seconds. Normally the whole response waits for the slowest field, so the reader stares at a blank page. @defer and @stream let the server send the fast part now and the slow part when it is ready, all in one request.
The rule
@defersends a fragment later;@streamsends a list a few items at a time.
This is called incremental delivery. It is still being added to the GraphQL specification, and some servers and clients already support it, so check yours before relying on it.
@defer goes on a fragment spread or an inline fragment, never on a plain field:
query BookPage($id: ID!) {
book(id: $id) {
title
price
... @defer(label: "reviews") {
reviews(first: 5) { rating text }
}
}
}The first part of the response holds title and price. A later part adds reviews once they are ready.
@stream goes on a field that returns a list:
query BrowsePage {
books(first: 50) @stream(initialCount: 10) {
title
price
}
}The first part holds the first 10 books; the rest arrive in later parts as the server produces them.
Both directives take an optional if: (so a variable can turn them off) and a label to help the client tell parts apart. Over HTTP, the parts travel in one response that stays open until the last part is sent. This is not a subscription: when everything has arrived, the request is over. Put the parts together and you get exactly the data the same query would return without the directives.