The Query Planner: What "Fetch It Once" Really Means

From Query to Plan: Four Node Types

The planner compiles one client operation against the composed supergraph into a tree of four node types. Router plans also contain Condition (for @skip/@include on variables), Defer, and Subscription, but these four do all the work:

FetchOne GraphQL request to one subgraph. A root fetch runs a normal query. An entity fetch runs _entities(representations: $representations) and lists its inputs (the @key fields plus any @requires fields) before the =>.
Flatten(path)Tells the executor where in the partial response the fetch reads its inputs and merges its results. @ means "every element of this list", so rows.@.videos.@ covers every video in every row.
SequenceRuns its children in order, because a later child needs data from an earlier one (keys, or @requires inputs). Each level of a Sequence is one more round trip on the critical path.
ParallelRuns children concurrently and finishes when the slowest child finishes.

Inside the planner is a fetch dependency graph. Each node is a fetch group identified by a subgraph and a mergeAt response path. The rule that decides whether two pieces of work share an HTTP call is the same in the JS planner (canMergeSiblingIn in query-planner-js/src/buildPlan.ts) and in its Rust port (can_merge_sibling_in in apollo-federation/src/query_plan/fetch_dependency_graph.rs): same subgraph, same mergeAt path, same single parent, same defer block. If any of these differs, you get two fetches. Values never enter into it, because the planner has none.

That also makes plans cacheable. The Router keys its plan cache on the operation text, operation name, a schema-aware hash, authorization metadata and planner options. Variable values are not part of the key (see CachingQueryKey in caching_query_planner.rs). The in-memory LRU holds supergraph.query_planning.cache.in_memory.limit plans (default 512). After a schema reload, supergraph.query_planning.warmed_up_queries re-plans the hottest operations before the new schema starts serving (the docs say the default is 30% of the cache). You can add a Redis tier under supergraph.query_planning.cache.redis. The planner itself is now Rust: native since Router v1.49, the default since v1.59, and the only planner in 2.x, where the JS/V8 planner was removed.

The Running Example as a Real Plan

Here is the TV home page as six subgraphs. Two directives do real work. Personalization's homePage depends on the member's maturity level and language, and says so with @requires instead of calling the member service behind the graph's back. The image service renders a title treatment, so boxart @requires the catalog's title.

Subgraph SDL (Federation 2.7, trimmed to the fields used)

# member           — owns Member core fields; root field me
type Query  { me: Member }
type Member @key(fields: "id") { id: ID!  avatarUrl: String  language: String  maturityLevel: Int }

# membership       — contributes entitlements to the same entity
type Member @key(fields: "id") { id: ID!  entitlement: Entitlement }
type Entitlement { plan: String  maxStreams: Int  uhd: Boolean }

# personalization  — the page is computed FOR a member, so it hangs off Member
type Member @key(fields: "id") {
  id: ID!
  maturityLevel: Int @external
  language: String @external
  homePage(device: Device!): Page @requires(fields: "maturityLevel language")
}
type Page { rows: [Row!]! }
type Row  { title: String  videos: [Video!]! }
type Video @key(fields: "id", resolvable: false) { id: ID! }

# catalog          — type Video @key(fields: "id") { id: ID!  title: String  maturityRating: Int }
# image            — type Video @key(fields: "id") { id: ID!  title: String @external
#                        boxart(size: ArtworkSize!): Artwork @requires(fields: "title") }
# viewinghistory   — type Video @key(fields: "id") { id: ID!  bookmark: Bookmark }
#                    type Bookmark { positionSeconds: Int  profile: Member }

Client operation: five branches of the page need member 42 (avatar, language, maturity, entitlement, plan)

query TvHome {
  me {
    avatarUrl                         # header
    language                          # row titles, audio default
    entitlement { plan uhd }          # upsell banner, UHD badge
    homePage(device: TV) {            # maturity + language consumed via @requires
      rows { title videos { title  boxart(size: TV_LARGE) { url }  bookmark { positionSeconds } } }
    }
  }
}

The plan: real output from @apollo/query-planner 2.14.4 (Rust planner is a port with the same rules); selections condensed onto single lines

QueryPlan {
  Sequence {
    Fetch(service: "member") {                                            # wave 1
      { me { __typename id avatarUrl language maturityLevel } }
    },
    Parallel {
      Sequence {
        Flatten(path: "me") {
          Fetch(service: "personalization") {                             # wave 2
            { ... on Member { __typename id maturityLevel language } } =>
            { ... on Member { homePage(device: TV) { rows { title videos { __typename id } } } } }
          },
        },
        Parallel {
          Flatten(path: "me.homePage.rows.@.videos.@") {
            Fetch(service: "viewinghistory") {                            # wave 3
              { ... on Video { __typename id } } =>
              { ... on Video { bookmark { positionSeconds } } }
            },
          },
          Sequence {
            Flatten(path: "me.homePage.rows.@.videos.@") {
              Fetch(service: "catalog") {                                 # wave 3
                { ... on Video { __typename id } } =>
                { ... on Video { title } }
              },
            },
            Flatten(path: "me.homePage.rows.@.videos.@") {
              Fetch(service: "image") {                                   # wave 4
                { ... on Video { __typename title id } } =>
                { ... on Video { boxart(size: TV_LARGE) { url } } }
              },
            },
          },
        },
      },
      Flatten(path: "me") {
        Fetch(service: "membership") {                                    # wave 2
          { ... on Member { __typename id } } =>
          { ... on Member { entitlement { plan uhd } } }
        },
      },
    },
  },
}

Three things in this plan matter:

  • The member subgraph is called once. avatarUrl and language came from the client. maturityLevel is there only because personalization @requires it, and the planner put it into the same root fetch. Five needs became one selection set, and that's the real version of "fetch it once": fields merged at planning time.
  • Member 42 is still sent to two subgraphs. Membership owns entitlement, so it gets its own _entities call carrying {__typename:"Member", id:"42"}. Merging across owning subgraphs is impossible. Ownership is the boundary for dedup.
  • The critical path is four sequential waves: member → personalization → catalog → image. Without the @requires(fields: "title"), image would run in wave 3 next to catalog. Every @requires that crosses subgraphs adds a Sequence level.
The same plan as waves: plan depth, not fetch count, sets latency
The same plan as waves: plan depth, not fetch count, sets latency

latency(plan) ≈ Σ over Sequence levels on the critical path of max( latency of that level's Parallel fetches ) + router overhead — here: member + personalization + catalog + image. Membership and viewinghistory are off the critical path. Netflix measured the gateway's own share (planning, deserializing DGS responses, serializing the merged response) at "~10ms overhead in the worst case" (How Netflix Scales its API with GraphQL Federation, Part 1, Nov 2020).

Where Dedup Happens at Run Time

For an entity fetch, the executor walks every object at the Flatten path, projects each one through the fetch's requires selection to build a representation, and sends the list as $representations. On a TV page with, say, 40 rows × 75 videos, that path matches 3,000 video slots. Many of them are the same title showing up in "Trending", "Top 10" and "Because you watched". The two gateway implementations handle that list differently:

✓ Apollo Router: value-dedup, always on

// apollo-router/src/query_planner/fetch.rs
let mut inverted_paths: Vec<Vec<Path>> = Vec::new();
let mut values: IndexSet<Value> = IndexSet::default();
data.select_values_and_paths(schema, current_dir, |path, value| {
  let mut value = execute_selection_set(value, requires, ..);
  match values.get_index_of(&value) {
    Some(i) => inverted_paths[i].push(path.clone()),
    None    => { inverted_paths.push(vec![path.clone()]);
                 values.insert(value); }
  }
});
// 3,000 slots -> one representation per DISTINCT
// {__typename, id, ...requires}; results fan back
// out to every path via inverted_paths

✗ @apollo/gateway (JS): one representation per occurrence

// gateway-js/src/executeQueryPlan.ts (v2.14.4)
entities.forEach((entity, index) => {
  const representation = executeSelectionSet(
      context.supergraphSchema, entity, requires);
  if (representation && representation.__typename) {
    representations.push(representation);
    representationToEntity.push(index);
  }
});
// 3,000 slots -> 3,000 representations,
// duplicates included. Collapsing them is
// the subgraph's problem.

The Router docs call this "variable deduplication" and describe it as "always active". It began as an opt-in (traffic_shaping.deduplicate_variables, router issue #87). That config key is now marked "DEPRECATED, now always enabled". Equality is on the whole representation: __typename, key fields, and any @requires fields. Two occurrences of the same video that somehow carried different title values would be sent as two representations.

The subgraph still needs DataLoader. Router dedup shrinks the list. It doesn't make storage access batched. Apollo's subgraph libraries call the reference resolver "once for each key", and Netflix's DGS @DgsEntityFetcher is likewise invoked per representation. If, say, 1,800 of the 3,000 slots are distinct videos and the catalog DGS's entity fetcher does catalogClient.get(id) directly, those 1,800 become 1,800 backend lookups inside one _entities call. Apollo's advice is to use DataLoader "in every resolver". Under @apollo/gateway it's worse: the subgraph's per-request DataLoader memo is the only thing that collapses the other 1,200 duplicate representations. Batching (one storage round trip) belongs to the subgraph. Dedup (fewer keys on the wire) belongs to the Router. You need both.

The Verdict: When Member 42 Is Fetched Once, Twice, or Five Times

Each row below was planned against the SDL above (plans printed with the same planner). "Fetches" means HTTP calls that carry member 42's representation, or its root query, to one subgraph.

Shape of the needWhat the plan containsMember-42 fetches
All five needs are fields of me, all owned by one subgraphOne root Fetch with the merged selection1. Field merging, done at plan time.
Same, but fields split across owners (avatar/language/maturity in member; entitlement/plan in membership)Root fetch, plus one Flatten(path: "me") entity fetch per other owner1 per owning subgraph (2 here). Can't be reduced: ownership is the dedup boundary.
Member 42 appears thousands of times at one path, e.g. bookmark { profile { avatarUrl } } on every videoOne entity fetch at …videos.@.bookmark.profile1 call. The Router sends 1 representation; @apollo/gateway sends one per bookmark, and the subgraph's DataLoader memo collapses them.
Member 42 at two different paths: me and …bookmark.profileTwo member fetches, in wave 1 and wave 4 (merge rule fails on mergeAt)2 sequential. The second one sits on the critical path.
Two UI components alias the same field: header: me {…}, banner: me {…}Different response paths → two membership fetches in one Parallel2 in parallel. Collapses to 1 only if the two subgraph requests are byte-identical and traffic_shaping.all.deduplicate_query: true (off by default)
Services A–E each call the member service internally (the Netflix guide's diagram)Nothing. Those calls happen inside subgraph resolvers and never appear in the plan5. Federation changes nothing here unless the dependency moves into the schema.
The next home-page load, or another profile on the same accountA new execution of the cached planAgain, every time. Only a response cache or EVCache behind the subgraph avoids it.

Two-path case: the second member fetch is in wave 4, after viewinghistory returns the profile keys (abridged)

Sequence {
  Fetch(service: "member")            { me { __typename id avatarUrl maturityLevel language } },
  Flatten(path: "me")                 { Fetch(service: "personalization") { ... } },
  Flatten(path: "me.homePage.rows.@.videos.@") {
    Fetch(service: "viewinghistory")  { ... => { ... on Video { bookmark { positionSeconds profile { __typename id } } } } } },
  Parallel {
    Flatten(path: "me.homePage.rows.@.videos.@.bookmark.profile") {
      Fetch(service: "membership")    { { ... on Member { __typename id } } => { ... on Member { entitlement { plan } } } } },
    Flatten(path: "me.homePage.rows.@.videos.@.bookmark.profile") {
      Fetch(service: "member")        { { ... on Member { __typename id } } => { ... on Member { avatarUrl } } } },   # member 42 again
  },
}

Router query deduplication (deduplicate_query) is a different mechanism from representation dedup. It's a Tower layer keyed on the entire subgraph HTTP request (path, headers, body) plus authorization metadata. It only merges requests that are in flight at the same moment, it applies only to queries (not mutations), and it's skipped for client-batched requests. It can merge across different client requests, but only when the headers match. Per-user auth headers usually rule that out for member data.

Turning Hidden Calls into Plan Edges

So the lever is schema design. The gateway can only merge what it can see. Two directives move a dependency from inside a resolver into the plan:

@requires: same entity, one extra hop

homePage @requires(fields: "maturityLevel language") tells the planner that personalization needs those fields as inputs. The planner adds them to whatever fetch already touches the member subgraph (wave 1 above), so it costs no extra member call. It does impose ordering: personalization can't start until member returns. @requires only reads fields of the same entity (including nested selections of that entity). It can't reach member 42 from a Video.

@fromContext: reaching up to an ancestor (Federation 2.8)

With @context(name: "viewer") on Member and isPlayable(maturity: Int @fromContext(field: "$viewer { maturityLevel }")): Boolean on a playback subgraph's Video, a field four levels down gets member 42's maturity from the me object that's already in the response. The planner emits it as an argument (isPlayable(maturity: $contextualArgument_6_0)) on the Video entity fetch, with no extra member fetch. This is a Router feature. The JS planner library's default supergraph feature check rejects the context spec with UNSUPPORTED_LINKED_FEATURE. If contextual values differ between paths, the Router rewrites the subgraph operation with aliases, so the fetch gets wider.

Three Dedupe Windows, Compared

The Netflix guide's Hystrix discussion and the What GraphQL changes part's DataLoader both answer "fetch it once". What differs is when and where each one can see the duplicate:

MechanismWindowScopeMergesBlind to
Hystrix request cacheOne HystrixRequestContextOne inbound request, one JVM (ThreadLocal)Identical getCacheKey() callsEvery other process: the five services each ask again
Hystrix collapserA timer (timerDelayInMilliseconds, default 10 ms)REQUEST or GLOBAL, one JVMDifferent keys into one batch callOther JVMs; it adds up to the window in latency
DataLoaderOne dispatch: a tick in JS, a field level under graphql-java's dispatch instrumentationOne request inside one subgraphBatches keys and memoizes per requestOther HTTP calls, including a second fetch node from the same plan
Query plannerPlan time (compiled once, cached)One operation, all subgraphsSelections for the same subgraph + path + parentValues; calls hidden in resolvers
Router representation dedupBuilding one fetch node's variablesOne fetch nodeEqual representationsOther fetch nodes, other requests
Router query dedup / response cacheIn-flight / TTLAcross client requestsByte-identical requests / (subgraph, type, representation, subgraph-query hash, private-data key)Different selection sets, so different cache entries

These layer rather than compete. On a well-built graph, member 42's needs merge at plan time into one selection per owner. The Router sends the key once per fetch. The owning subgraph's DataLoader turns a list of keys into one storage call. EVCache below that absorbs the next page load. Remove any layer and a different kind of duplicate comes back.

Netflix's Gateway: What's Published and What Isn't

Netflix doesn't run the Apollo Router. Part 2 of "How Netflix Scales its API with GraphQL Federation" (Dec 2020) says: "Our GraphQL Gateway is based on Apollo's reference implementation and is written in Kotlin", and it uses coroutines "for efficient parallel fetches". Part 1 (Nov 2020) describes the same plan shape as above: a root query to the Movie DGS, then parallel _entities calls to Production and Talent DGSs with "10 representation objects" for 10 movies. Not published: whether the Kotlin gateway dedupes representations the way the Router does, whether it has query dedup, and how it caches plans. The reference implementation it was based on, @apollo/gateway, doesn't dedupe representations even today (v2.14.4). Assume nothing, and make your DGS entity fetchers DataLoader-backed either way. The Netflix's actual path part covers Netflix's path, and the Operating the gateway part covers operating the tier.

The Invariants

  • Guarantees: All fields one subgraph owns at one response path (under one parent) go out in one fetch. All entities that need one subgraph at one path go out as one _entities call per plan node. In the Apollo Router, identical representations inside that call are sent once and fanned back to every path. Plans depend only on the operation and the schema, so they're cached and identical for every member.
  • Does not guarantee: That an entity is fetched once per request. Different owning subgraphs, different response paths, aliases, and @requires hops all create additional fetches. It doesn't dedupe calls made inside subgraph resolvers, batch storage access for you (DataLoader is still your job), dedupe representations in @apollo/gateway or unpublished gateways like Netflix's Kotlin one, or share anything across requests without an explicit cache.