GraphQL Federation

Federation joins several teams' subgraphs into one supergraph behind one router. An entity like Book is marked @key(fields: "id") in each subgraph that uses…

The Bookshop keeps growing. The stockroom team looks after titles, prices and stock. The community team looks after readers' reviews. Two teams, two servers, yet a customer still only asks one information desk, and the clerk knows which department to ask, in what order, then hands over one whole answer.

That's the job of Federation: it joins several GraphQL servers (subgraphs), each owned by one team, into one graph (the supergraph) behind one endpoint. A router takes the client's query, splits it, asks each part of the right subgraph, then puts the answers together.

Subgraphs and entities

Here are the Bookshop's two subgraphs with Apollo Federation 2:

# inventory subgraph (the stockroom team)
extend schema @link(url: "https://specs.apollo.dev/federation/v2.12", import: ["@key"])

type Query {
  books: [Book!]!
  book(id: ID!): Book
}

type Book @key(fields: "id") {
  id: ID!
  title: String!
  price: Int!
  stock: Int!
}
# reviews subgraph (the community team)
extend schema @link(url: "https://specs.apollo.dev/federation/v2.12", import: ["@key"])

type Query {
  latestReviews: [Review!]!
}

type Review {
  id: ID!
  rating: Int!
  comment: String!
  book: Book!
}

type Book @key(fields: "id") {
  id: ID!
  reviews: [Review!]!
  averageRating: Float
}

The router and the supergraph

The two SDLs are composed into one supergraph, with rover supergraph compose or through GraphOS, for example. The client sees only one schema: Book { id title price stock reviews averageRating }. The router (Apollo Router) holds that supergraph, takes queries at one endpoint, and makes a query plan for each: which requests to which subgraph, and in what order. The router stores no data and runs no subgraph resolvers; it only plans, sends and merges.

The query plan

This is the real query plan for { books { title averageRating reviews { rating } } }, made by @apollo/query-planner 2.14.4 from the two subgraphs above:

QueryPlan {
  Sequence {
    Fetch(service: "inventory") {
      {
        books {
          __typename
          id
          title
        }
      }
    },
    Flatten(path: "books.@") {
      Fetch(service: "reviews") {
        {
          ... on Book {
            __typename
            id
          }
        } =>
        {
          ... on Book {
            averageRating
            reviews {
              rating
            }
          }
        }
      },
    },
  },
}

It can run the other way too. { latestReviews { rating book { title } } } starts at reviews, then Flatten(path: "[email protected]") goes to inventory for the titles.

__resolveReference

When _entities arrives, the subgraph must turn each representation into an object. That's the job of the __resolveReference resolver. With @apollo/subgraph (version 2.15.1):

import { buildSubgraphSchema } from "@apollo/subgraph";

const resolvers = {
  Query: {
    latestReviews: () => reviews.slice().reverse(),
  },
  Book: {
    // { __typename: "Book", id: "1" } -> this subgraph's Book object
    __resolveReference: (ref) => ({ id: ref.id }),
    reviews: (book) => reviews.filter((r) => String(r.bookId) === book.id),
    averageRating: (book) => average(reviews.filter((r) => String(r.bookId) === book.id)),
  },
  Review: {
    // a reference is enough: the router fetches the title from inventory
    book: (review) => ({ __typename: "Book", id: String(review.bookId) }),
  },
};

const schema = buildSubgraphSchema({ typeDefs, resolvers });

buildSubgraphSchema adds _entities, union _Entity and scalar _Any to the subgraph's schema. In inventory, __resolveReference reads the book row from the database, so 50 representations can mean 50 queries: use DataLoader from the "N+1 Problem & DataLoader" lesson.

Other directives you'll meet: @shareable (a field more than one subgraph may answer), @external with @requires (a field needs another subgraph's field to be computed) or @provides, and @override(from: "...") (moving a field from one subgraph to another).

The tools and their licences

When a monolith is better

Federation adds a hop (the router), a composition step, and schema checks on every deploy. That's worth it when several teams must deploy their part of the graph on their own. For one team, or an app that's still small, one GraphQL schema (a monolith, which can still be split into modules in its code) is faster and simpler: one request, no query plan.

⚠️ When federation gets slow, breaks, or is overkill

TL;DR: Federation joins several teams' subgraphs into one supergraph behind one router. An entity like Book is marked @key(fields: "id") in each subgraph that uses it; other subgraphs only add their own fields (in Federation 2 without extend type). The router makes a query plan: { books { title averageRating } } becomes a Fetch to inventory (with __typename and id), then Flatten(path: "books.@") to reviews through _entities(representations:), in sequence. A subgraph answers representations with __resolveReference (use DataLoader). Apollo Router and its composition libraries are under the Elastic License 2.0, and the router's "licensed" features need GraphOS; alternatives are schema stitching, GraphQL Hive and WunderGraph Cosmo. For one team or a small app, a single monolith schema is simpler.

⚡ One graph from several services

Write:

type Book @key(fields: "id") {
  id: ID!
  reviews: [Review!]!
  averageRating: Float
}

Meaning: Federation combines several GraphQL services (subgraphs) into one whole graph. Book here is an entity: the reviews subgraph only adds reviews and averageRating, and @key(fields: "id") says id is enough to find the book.

⚡ The router and the supergraph

Meaning: Each subgraph's SDL is composed into one supergraph, so the client sees only one schema at one endpoint. The router makes a query plan for each query: which requests go to which subgraph, in what order. The router stores no data.

⚡ When a monolith is better

Guess first: one team, and the app is still small. Does it need federation?

No. Federation adds a hop (the router), a composition step, and schema checks on every deploy. One GraphQL schema is faster and simpler.

Meaning: Federation is worth it when several teams must deploy their part of the graph on their own.

What you will learn