Federation and distributed graphs

GraphQL · Expert · 15 min

Large organisations split one GraphQL API across many services and teams.

One GraphQL schema for a whole company becomes a bottleneck when dozens of teams own the data. Federation lets each team run a subgraph, a normal GraphQL service declaring the types it owns, while a router (gateway) exposes the composed supergraph to clients.

The core idea is entities: types that several subgraphs contribute fields to, identified by a key. In Apollo Federation:

# products subgraph
type Product @key(fields: "upc") { upc: ID!  name: String!  price: Int! }
# reviews subgraph
type Product @key(fields: "upc") { upc: ID!  reviews: [Review!]! }

Composition checks that subgraphs agree and produces a supergraph schema. At runtime the router builds a query plan: fetch from products, then send the upc keys to reviews through the special _entities field, then merge.

The GraphQL Foundation's Composite Schemas working group is standardizing these ideas vendor-neutrally; implementations include Apollo Federation (Router), WunderGraph Cosmo, Grafbase and The Guild's Hive Gateway.

Trade-offs: federation adds a network hop, query planning, and a schema registry and composition checks in CI. Cross-subgraph N+1 patterns become entity batching problems. Choose it for organisational scale; a single well-modularised server is simpler for one team. Schema stitching is an older, more manual alternative.

Example

# Client query against the supergraph
query ProductPage($upc: ID!) {
  product(upc: $upc) {
    name            # resolved by products subgraph
    price           # resolved by products subgraph
    reviews {       # resolved by reviews subgraph
      body
    }
  }
}

# Router query plan (simplified):
# 1. products: { product(upc: $upc) { __typename upc name price } }
# 2. reviews:  _entities(representations: [{ __typename: "Product", upc }])
#                { ... on Product { reviews { body } } }
# 3. merge results and return

Remember

  • Subgraphs own types; a router serves the composed supergraph
  • Entities with @key are extended across subgraphs
  • Composition and schema checks run in CI
  • Adopt for team scale, not for small apps

Watch out for

  • Federating a small single-team API and paying the operational cost for nothing.

Check yourself

  1. How does a router fetch `reviews` for a Product owned by another subgraph?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: graphql.org/learn/federation/

Builds on

Unlocks

Nothing builds on this yet.