Apollo Federation basics
Build two subgraphs sharing a Product entity with @key, resolve it through _entities, and compose them into a supergraph with Rover.
Apollo Federation basics
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A federated type that several subgraphs contribute to is an entity, declared with @key and identified by the key fields.
- A subgraph implements __resolveReference to turn a key representation, such as an id, into the entity object.
- The router calls each subgraph's _entities field with a list of representations, so one request can resolve many entities.
- Composition validates all subgraphs together and fails on conflicts such as incompatible field types or a non-shareable field defined twice.
- Subgraphs are ordinary GraphQL servers. You can test one on its own by calling _entities directly.
An entity is a type with a handle
Federation lets several services contribute fields to the same type. For that to work, the router needs a way to say “give me product 1” to a service that does not own the whole product. That handle is the key.
A type marked with @key is an entity. The key names the fields that identify it. Any subgraph that can find the entity by that key can contribute fields to it.
Two subgraphs
I built this in a scratch project using @apollo/subgraph 2.17.0 and @apollo/composition 2.14.5. The products subgraph owns the base type:
extend schema @link(url: "https://specs.apollo.dev/federation/v2.5", import: ["@key"])
type Product @key(fields: "id") { id: ID! name: String! }
type Query { products: [Product!]! }
The reviews subgraph adds a field to the same entity:
extend schema @link(url: "https://specs.apollo.dev/federation/v2.5", import: ["@key"])
type Product @key(fields: "id") { id: ID! reviews: [Review!]! }
type Review { id: ID! body: String! }
The @link line opts the schema into federation 2 and imports the directives it uses. Reviews does not define Product.name; products does not define Product.reviews. Each field has one owner, and both subgraphs know how to identify a product.
Resolving an entity
A subgraph that contributes to an entity implements __resolveReference. The router will hand it a representation, and the function returns the entity object:
import { buildSubgraphSchema } from "@apollo/subgraph";
const schema = buildSubgraphSchema([
{
typeDefs: parse(reviewsSDL),
resolvers: {
Product: {
__resolveReference: (ref) => ({ id: ref.id }),
reviews: (product) => [{ id: "r1", body: `Good ${product.id}` }],
},
},
},
]);
One version note from my run: passing a bare { typeDefs, resolvers } object to buildSubgraphSchema threw “doc.definitions is not iterable” in this version, while wrapping it in an array worked. Check the signature in your installed version.
buildSubgraphSchema adds two fields to the schema, _service and _entities, which a router uses. I called _entities directly, the way a router would, with no router running:
{ _entities(representations: [{ __typename: "Product", id: "1" }]) {
... on Product { id reviews { body } }
} }
It returned {"_entities":[{"id":"1","reviews":[{"body":"Good 1"}]}]}. That is the entire runtime contract of a subgraph. It receives a list of representations and returns the matching entities. Because it takes a list, a router resolving a page of fifty products makes one call, not fifty; and the subgraph should batch its own lookups, the same way DataLoader does for N+1.
This also means a subgraph is testable alone, with plain GraphQL calls, before any router exists.
Composing
Composition takes every subgraph and checks that together they make a valid supergraph. Two routes, both of which I ran:
import { composeServices } from "@apollo/composition";
const result = composeServices([
{ name: "products", typeDefs: parse(productsSDL), url: "http://localhost:4001" },
{ name: "reviews", typeDefs: parse(reviewsSDL), url: "http://localhost:4002" },
]);
// result.errors is undefined; result.supergraphSdl holds the supergraph
and the Rover CLI (@apollo/rover 1.1.0, which downloaded the federation 2.14.0 composition plugin on first use):
# supergraph.yaml
federation_version: =2.14.0
subgraphs:
products:
routing_url: http://localhost:4001
schema: { file: ./products.graphql }
reviews:
routing_url: http://localhost:4002
schema: { file: ./reviews.graphql }
rover supergraph compose --config supergraph.yaml
Both produced a supergraph schema annotated with @join__type and @join__field directives that record which subgraph owns what: Product.name came from PRODUCTS and Product.reviews from REVIEWS. That annotated schema is what a router loads.
What composition catches
When I changed Product.name to Int! in a second subgraph, composition returned two errors: the type was incompatible across subgraphs (String! versus Int!), and Product.name was non-shareable but resolved from two subgraphs. The second message points at a rule you will hit early. A field belongs to one subgraph unless every subgraph defining it marks it @shareable. Federation prefers loud conflicts to silent ones, which is why schema checks in CI run composition on every change.
Other directives you will meet and I did not run: @external and @requires (use a field another subgraph owns to compute your own), @provides, and @override for moving a field between subgraphs without downtime. Learn them as you need them, from Apollo’s documentation.
What the video covers
Apollo’s “Using the @key directive” is a four-and-a-half-minute video from January 2024 on the directive at the centre of this lesson. It has no chapters and I could not read a transcript, so I rely on the title. It is narrow: it does not cover composition or the router. The runner-up, Apollo’s 26-minute 2020 introduction with chapters on the problems federation solves and key concepts, likely predates federation 2 and the current @apollo/subgraph package, so use it for concepts only and the code above for syntax.
Where this fits
You can now write and compose subgraphs. The router and the supergraph explains the process that sits in front of them and executes queries across them.
Check yourself
What does @key(fields: "id") tell the supergraph?
That the type is an entity and that a subgraph can look it up, or be asked for it, by its id.
What is a representation in an _entities call?
An object with __typename and the key fields, for example { __typename: "Product", id: "1" }, which identifies one entity for a subgraph to resolve.
Why does a second subgraph defining the same plain field on Product fail composition?
A field is owned by one subgraph unless it is marked @shareable, so two subgraphs resolving the same field are ambiguous.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.