⬡ GraphQL Advanced

What is the @defer and @stream directive and how do they work?

Answer

@defer and @stream are incremental delivery directives that allow GraphQL to send partial results as they become available, using HTTP multipart responses. @defer defers a fragment: query { user { name ... @defer(label: "profile") { bio posts { title } } } }. The server sends the initial response (with name, placeholder for deferred), then sends deferred chunks incrementally via multipart/mixed chunks. Each chunk has a hasNext flag. @stream streams list items: query { users @stream(initialCount: 3) { name } } — sends the first 3 immediately, streams the rest. Transport: uses multipart HTTP for HTTP/1.1 and can leverage HTTP/2 server push. The client (Apollo Client 3.7+) handles merging incremental results into the cache. Server support: Apollo Server 4 with @apollo/server and the ApolloServerPluginSchemaReporting pattern, GraphQL Yoga. Extremely valuable for dashboards and slow-loading pages.