TExcelTAD
Home › GraphQL › Federation

Federation

As an organization grows, one GraphQL server owned by one team becomes a bottleneck. Federation lets several teams each own a part of the graph (a subgraph, a normal GraphQL service), while clients still see one unified schema served by a router (also called a gateway).

text
                   ┌───────────────┐
  client ────────▶ │    router     │  one endpoint, one composed schema
                   └──────┬────────┘
            ┌─────────────┼─────────────┐
            ▼             ▼             ▼
      ┌──────────┐  ┌──────────┐  ┌──────────┐
      │ accounts │  │ products │  │ reviews  │   subgraphs, owned by
      └──────────┘  └──────────┘  └──────────┘   different teams

The most widely used implementation is Apollo Federation (router: Apollo Router, written in Rust). Alternatives include GraphQL Mesh/Hive Gateway and WunderGraph Cosmo; the GraphQL Foundation's Composite Schemas working group is standardizing the idea.

Entities: one type, many owners

The key concept is an entity: a type that several subgraphs contribute fields to, identified by a key. The products team defines Product and its core fields; the reviews team adds reviews to the same Product:

graphql
# products subgraph
type Product @key(fields: "id") {
  id: ID!
  name: String!
  price: Int!
}

type Query { topProducts: [Product!]! }
graphql
# reviews subgraph
type Product @key(fields: "id") {
  id: ID!
  reviews: [Review!]!
}

type Review { stars: Int!, text: String! }

Clients query it as if it were one type:

graphql
{ topProducts { name price reviews { stars } } }

The router builds a query plan: fetch topProducts { id name price } from products, then send the ids to reviews and ask for reviews of those Product entities, then merge the results.

A mini router, by hand

Real federation involves schema composition and an _entities protocol, but the core idea fits in one example: two independent schemas, and a gateway resolver that fetches from the first, then batch-resolves the entity references in the second:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

// --- products subgraph (team A) ---
const productsSchema = buildSchema(`
  type Product { id: ID!, name: String!, price: Int! }
  type Query { topProducts: [Product!]! }
`);
const productsRoot = {
  topProducts: () => [
    { id: 'p1', name: 'Headphones', price: 199 },
    { id: 'p2', name: 'Keyboard', price: 89 },
  ],
};

// --- reviews subgraph (team B) ---
const reviewsSchema = buildSchema(`
  type Review { stars: Int!, text: String! }
  type ProductReviews { id: ID!, reviews: [Review!]! }
  type Query { productsById(ids: [ID!]!): [ProductReviews!]! }   # stands in for _entities
`);
const reviewsByProduct = {
  p1: [{ stars: 5, text: 'Great sound' }, { stars: 4, text: 'Comfy' }],
  p2: [{ stars: 3, text: 'Loud keys' }],
};
const reviewsRoot = {
  productsById: ({ ids }) => ids.map((id) => ({ id, reviews: reviewsByProduct[id] ?? [] })),
};

// --- the router: a query plan for `topProducts { name price reviews { stars } }` ---
const log = [];
async function callSubgraph(name, schema, rootValue, source, variableValues) {
  log.push(`${name}: ${source}`);
  const result = await graphql({ schema, rootValue, source, variableValues });
  return result.data;
}

async function routerTopProducts() {
  const step1 = await callSubgraph('products', productsSchema, productsRoot,
    '{ topProducts { id name price } }');
  const ids = step1.topProducts.map((p) => p.id);
  const step2 = await callSubgraph('reviews', reviewsSchema, reviewsRoot,
    'query ($ids: [ID!]!) { productsById(ids: $ids) { id reviews { stars } } }', { ids });
  const byId = new Map(step2.productsById.map((p) => [p.id, p]));
  return step1.topProducts.map((p) => ({ name: p.name, price: p.price, reviews: byId.get(p.id).reviews }));
}

console.log(JSON.stringify(await routerTopProducts()));
console.log(log.join('\n'));
[{"name":"Headphones","price":199,"reviews":[{"stars":5},{"stars":4}]},{"name":"Keyboard","price":89,"reviews":[{"stars":3}]}]
products: { topProducts { id name price } }
reviews: query ($ids: [ID!]!) { productsById(ids: $ids) { id reviews { stars } } }

Two subgraph calls, regardless of how many products there are: the router batches the entity references just like DataLoader.

What a subgraph looks like in Apollo Federation

Each subgraph adds a reference resolver that turns a key ({ id }) into the full entity:

js
import { ApolloServer } from '@apollo/server';
import { buildSubgraphSchema } from '@apollo/subgraph';
import gql from 'graphql-tag';

const typeDefs = gql`
  extend schema @link(url: "https://specs.apollo.dev/federation/v2.7", import: ["@key"])

  type Product @key(fields: "id") {
    id: ID!
    reviews: [Review!]!
  }
  type Review { stars: Int!, text: String! }
`;

const resolvers = {
  Product: {
    __resolveReference: ({ id }) => ({ id }),
    reviews: ({ id }) => reviewsRepo.forProduct(id),
  },
};

const server = new ApolloServer({ schema: buildSubgraphSchema({ typeDefs, resolvers }) });

The subgraph schemas are composed into a supergraph schema (with the rover CLI or a schema registry), and the router uses it to plan queries.

Federation vs schema stitching vs monolith

Approach How it works Good for
Single server (monolith) one schema, one codebase most apps; start here
Schema stitching a gateway merges schemas with hand-written glue combining a few existing APIs
Federation subgraphs declare entities and keys; composition is automatic many teams owning parts of one graph

Note: Federation adds operational complexity: a router, composition checks in CI, cross-service query plans and tracing. It pays off with several teams and services; for one team, a well-structured single schema (split into modules in code) is simpler.

Test yourself

In federation, what is a subgraph?

  1. A fragment
  2. A GraphQL service owning part of the overall schema
  3. A cached query
  4. A type of directive

What does @key(fields: "id") declare?

  1. A primary key in a database
  2. That the type is an entity other subgraphs can reference and extend by id
  3. A unique index on the client
  4. An authorization rule

Who sends queries to the individual subgraphs?

  1. The client directly
  2. The router, following a query plan
  3. Each subgraph calls the others
  4. The database