On this page

Deferred Responses (@defer)

Send the slow parts of a GraphQL response later with @defer in Hive Router, over multipart HTTP, SSE or WebSockets.

With @defer, a client marks part of an operation as one it can wait for. The router sends the rest of the response first, then each deferred fragment once its own data is in.

query {
  product(id: "1") {
    name
    price
    ... @defer(label: "reviews") {
      reviews {
        rating
        body
      }
    }
  }
}

Here name and price go out as soon as they’re resolved, and reviews follows in its own part once the reviews subgraph answers. With several @defers, a fast fragment doesn’t wait for a slow one.

Enable @defer

@defer is off by default. Turn it on with defer.enabled:

router.config.yaml
defer:
  enabled: true

With it on, @defer is part of the public schema. With it off, a supergraph that defines @defer itself gets it ignored: the client gets one response with every field.

Transports

A response with @defer goes out in parts, so the client has to accept a streaming transport:

Accept headerTransportFormat
multipart/mixedMultipart HTTPincrementalSpec=v0.2
multipart/mixed;deferSpec=20220824Multipart HTTP (Apollo Client 3)deferSpec=20220824
text/event-streamServer-Sent EventsincrementalSpec=v0.2

Over WebSockets, each part is its own next message, in the incrementalSpec=v0.2 format.

Each format goes by the q of the most specific Accept entry it matches, so q=0 on one turns off that format only.

A client that only accepts application/json and sends an operation with an active @defer gets a 406 with the DEFER_TRANSPORT_NOT_SUPPORTED error code, before anything is fetched.

Response format

The incrementalSpec=v0.2 format announces each deferred fragment in pending, sends its data in incremental, and closes it in completed. hasNext: false marks the last part.

curl 'http://localhost:4000/graphql' \
  -H 'accept: multipart/mixed' \
  --json '{"query": "{ product(id: \"1\") { name ... @defer(label: \"reviews\") { reviews { rating } } } }"}'
---
content-type: application/json

{"data":{"product":{"name":"Croissant"}},"pending":[{"id":"0","path":["product"],"label":"reviews"}],"hasNext":true}
---
content-type: application/json

{"incremental":[{"id":"0","data":{"reviews":[{"rating":5}]}}],"completed":[{"id":"0"}],"hasNext":false}
-----

Fetching

Deferred fields get subgraph fetches of their own. They start as soon as their inputs are in and never hold back the primary part. A nested @defer goes out after the fragment it’s nested in.

That works for fields of a subgraph the primary part already calls too, when the fragment is on an entity: the router goes back to that subgraph through the type’s @key. On a type that isn’t an entity in that subgraph (no @key, or only @key(resolvable: false)), those fields are fetched with the primary part, and only their delivery waits.

A field runs once, however many parts ask for it, and a deferred fragment leaves out the fields that already went out for the same object.

A client that goes away, or a WebSocket complete, stops the deferred work: fetches that haven’t started never do.

Conditional @defer

@defer(if: false), or an if variable that’s false, gives a regular response. An if variable that isn’t sent counts as true. One query plan covers both values.

query ($deferReviews: Boolean) {
  product(id: "1") {
    name
    ... @defer(if: $deferReviews) {
      reviews {
        rating
      }
    }
  }
}

Nulls and errors

A null from a deferred fragment can’t take away data another part delivers. When a non-null field fails and the null would land on a field that the primary part or another fragment sends too, the fragment fails instead: it’s completed with its errors and no data. A null on a field only that fragment has goes out as usual.

Fields that authorization rejects come out null in deferred parts too. The authorization errors go out with the primary part.

Subgraph extensions that come in after the primary part go out with the next part.

Limits and restrictions

  • limits.max_defers caps the @defers in one operation, 4 by default.
  • traffic_shaping.router.request_timeout covers every part over HTTP. Past it, the fragments still pending end with the timeout error.
  • @defer isn’t allowed in subscriptions (DEFER_IN_SUBSCRIPTION) or on the root selection set of a mutation. A literal @defer(if: false) is fine there, since it never defers.
  • Labels have to be static strings that don’t repeat in the document.

Requests with @defer aren’t deduplicated.

Plugins and observability

  • on_execute end callbacks run once, before the primary part, with has_next: true on their payload. on_graphql_error runs for every part, but only the primary part’s errors can change the status code. See Plugin hooks.
  • The usage report, the “graphql request completed” log line and the HTTP server metrics come after the last part, or when the client goes away, with the errors of every part. http.server.response.body.size counts every part.
  • The http.server, graphql.operation and graphql.execute spans stay open until the last part, and the deferred subgraph calls are in the same trace, under graphql.execute. http.server gets hive.defer.end_reason: completed, or client_disconnect when the client left first.
  • An exposed query plan shows deferred work in a Defer node, with a Deferred block per @defer. With @defer(if:) it shows the fragment both ways, each behind a variable the router sets ($_d0, $_d1, …).