# Federation and Composing Services — GraphQL

Source: https://www.skillbyai.com/en/graphql/x-federation

> One graph from many teams.

## Subgraphs and a router

As organisations grow, one team cannot own the whole schema. **Federation** (for example Apollo Federation, also implemented by other routers) lets each service publish a **subgraph** that owns some types and fields; a **router** or gateway composes them into a single **supergraph** and plans queries across services. Entities shared between subgraphs are identified by keys (`@key(fields: "id")`). Alternatives include schema stitching and a single backend-for-frontend that calls other services.

## Two subgraphs contributing to one type

Apollo Federation-style SDL (a sketch).

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

# reviews subgraph adds fields to Product
type Product @key(fields: "id") {
  id: ID!
  reviews(first: Int = 5): [Review!]!
  averageRating: Float
}

# the router composes both, so clients query product { name reviews { rating } }
```

## Start with a monolith schema

Federation adds operational complexity; adopt it when several teams genuinely need to own parts of the graph.

**Quiz:** What does a federation router do?

- [ ] Replaces resolvers in every service
- [ ] Stores all data centrally
- [x] Composes subgraphs into one schema and plans queries across them
- [ ] Generates REST endpoints

*Answer:* Composes subgraphs into one schema and plans queries across them. One graph, many services.
