Defer and Stream
GraphQL Yoga v5 documentation (superseded by v6): Use @defer and @stream with GraphQL Yoga. Stream and defer are directives that allow you to improve latency for clients by sending the most important data as soon as it's ready.
Stream and defer are directives that allow you to improve latency for clients by sending the most important data as soon as it’s ready.
As applications grow, the GraphQL operation documents can get bigger. The server will only send the
response back once all the data requested in the query is ready. However, not all requested data is
of equal importance, and the client may not need all of the data at once. To remedy this, GraphQL
specification working group is working on
introducing new @defer and @stream directives
which allows applications to request a subset of data which is critical and get the rest of the data
in subsequent responses from the server. This
proposal is in
Stage 2, meaning
GraphQL libraries can start implementing this as experimental feature to provide feedback to the
working group.
Installation
Enabling support for the @defer and @stream directive requires installing a plugin.
Quick Start
The following schema shows a schema whose field resolvers are slow
Create this file and start the GraphQL server.
Using Defer
The @defer directive allows you to post-pone the delivery of one or more (slow) fields grouped in
an inlined or spread fragment.
Visit http://localhost:4000/graphql and paste the following operation into the left panel.
Then press the Play (Execute Query) button.
Alternatively, you can also send the defer operation via curl.
Using Stream
The @stream directive allows you to stream the individual items of a field of the list type as the
items are available.
Visit http://localhost:4000/graphql and paste the following operation into the left panel.
Then press the Play (Execute Query) button.
Alternatively, you can also send the stream operation via curl.
Writing safe stream resolvers
AsyncGenerators
as declared via the async * keywords are prone to memory leaks and leaking timers. In the previous
examples they are used for simplicity.
For real-world usage we recommend using Repeater as a safe alternative.
If you execute the following GraphQL operation via GraphiQL and click the stop button before the
last value has been sent to the client, no further values will be published as the underlying source
(Repeater) has been stopped and disposed. In contrast, just using a AsyncGenerator would continue
to run timers even after the client has stopped listening.