Skip to content

GraphQL Federation: One Schema from Many Subgraphs

When one team can no longer carry a monolithic schema on its own, Federation splits the graph into subgraphs that a router composes into a supergraph. Using a users and orders example, this article shows how @key and __resolveReference hold entities together across subgraph boundaries.

≈ 11 min readSoftwareGraphQLAPI
$ rover supergraph compose --config ./supergraph.yaml

error[E029]: Encountered 1 build error while trying to build a supergraph.

Caused by:
    INVALID_GRAPHQL: [orders] Unknown directive "@key".

This message doesn’t come from a running server. It comes from a build step that a single GraphQL service doesn’t even know about: composition. The orders service uses @key without having imported the directive first – and this one missing entry is enough to keep several schemas from becoming a shared graph.

@key is the directive Apollo Federation uses to make a type referenceable across service boundaries. Everything else hinges on it: who owns which type, who contributes which fields, who assembles the parts into a response – and the question of how to cut apart a schema that three teams work on without the clients noticing. Drawn too early, though, this split costs more than it brings in; I’ll come back to that at the end.

The problem: a schema that nobody owns anymore#

At the beginning, a GraphQL schema is wonderful. One team, one repository, one type Query, everything in one place. After all, the appeal of GraphQL is that clients fetch exactly the fields they need from a single endpoint. I have already covered related questions in earlier posts – for example how to deliver lists cleanly with GraphQL pagination or how permissions are passed through with GraphQL auth in the context.

The problem starts with growth. As soon as several teams work on one schema, the file becomes a bottleneck. The users team wants to attach a field to type Order, but to do so it has to reach into the orders team’s code. Deployments become coupled. A type suddenly belongs to many, and in practice “belongs to many” means: to nobody. What shows up as a merge conflict in everyday work is a conflict of ownership.

Federation turns the question around. Instead of “How do teams share a schema?”, it asks: “How does each team run its own schema – and the client still sees only one graph?”

The basic idea: subgraphs, supergraph, one endpoint#

In Apollo Federation 2 – the generation that has been relevant since 2022 and the one I mean throughout this article – each team runs a subgraph. A subgraph is a perfectly normal GraphQL service with its own schema, its own database and its own deployment. The individual subgraph schemas are composed into a supergraph schema. At runtime, a router (or a gateway) sits in front of them, receives the incoming query, creates a plan and distributes the sub-queries to the responsible subgraphs.

The key point: the client notices none of this. It talks to one endpoint, sees one schema, sends one query. The split is purely an operational and team topology – invisible to the consumer.

flowchart TB
  Client["Client<br/>one query, one endpoint"]
  Router["Router / Gateway<br/>executes the query plan"]
  Users["Users subgraph<br/>Team A"]
  Orders["Orders subgraph<br/>Team B"]
  UDB[("Users DB")]
  ODB[("Orders DB")]

  Client --> Router
  Router --> Users
  Router --> Orders
  Users --> UDB
  Orders --> ODB

If you run the runtime, you have two established options in 2024: the @apollo/gateway in Node or the Apollo Router, written in Rust. Both are valid. The router is the faster option and the usual recommendation for new setups, but the gateway is by no means deprecated – if you already run a Node gateway, you don’t have to move.

Roles in the system#

Before writing code, it helps to keep the three building blocks clearly apart:

  • The subgraph contributes exactly its own fields. It knows its database, its schema, its deployment – and nothing else. This is where team autonomy lives.
  • The @key directive marks a type as an entity, meaning it’s referenceable across subgraphs. Without @key, another subgraph can neither extend the type nor point to it by reference.
  • The router plans the query. It breaks an incoming request into sub-queries, fetches each subgraph’s contribution and assembles the response again. Cross-subgraph joins are its job, not the teams’.

This separation is the whole trick: teams think locally, the router thinks globally.

A subgraph in Federation 2 states explicitly which Federation directives it wants to use. It does this through @link on the schema. That’s a deliberate break with Federation 1, where extend type ... @key implicitly came with certain behavior. In Fed 2, you import what you need:

extend schema
  @link(
    url: "https://specs.apollo.dev/federation/v2.0"
    import: ["@key", "@shareable", "@external"]
  )

If you forget the @link or use a directive that wasn’t imported, you don’t get a runtime error but a composition error – and you get it early, when composing or publishing. That regularly surprises people moving from Fed 1, but it’s the better moment for an error.

The users subgraph#

Let’s start with the easy part. The users subgraph owns the User entity. It defines it, marks it with @key and provides a reference resolver that resolves a User representation.

extend schema
  @link(url: "https://specs.apollo.dev/federation/v2.0", import: ["@key"])

type User @key(fields: "id") {
  id: ID!
  name: String!
  email: String!
}

type Query {
  user(id: ID!): User
}

The code for it uses buildSubgraphSchema from the @apollo/subgraph package. That’s the building block that turns typeDefs and resolvers into a federated GraphQLSchema that knows the Federation directives and the fields required by the spec, such as _entities.

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

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

  type User @key(fields: "id") {
    id: ID!
    name: String!
    email: String!
  }

  type Query {
    user(id: ID!): User
  }
`;

const resolvers = {
  Query: {
    user: (_parent, { id }) => fetchUserById(id),
  },
  User: {
    // The router hands us a representation: { __typename: "User", id }
    __resolveReference: (reference) => fetchUserById(reference.id),
  },
};

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

const { url } = await startStandaloneServer(server, { listen: { port: 4001 } });
console.log(`Users subgraph ready at ${url}`);

The heart of it is __resolveReference. This function receives a representation – an object with __typename and the @key fields – and returns the complete entity (or null if it doesn’t exist). The important thing to understand: a normal field resolver isn’t enough here, because the router starts the resolution process with only the key fields. Without a reference resolver, it can’t fill the gap.

The orders subgraph with a cross-reference#

Now it gets interesting. The orders subgraph owns Order. An order belongs to a user – but the orders subgraph only knows the user’s ID. It still wants to offer an order.user field. To do that, it includes User as a stub: with @key, but only with the key field, without resolving the other fields itself.

extend schema
  @link(url: "https://specs.apollo.dev/federation/v2.0", import: ["@key"])

type Order @key(fields: "id") {
  id: ID!
  total: Int!
  user: User
}

# User lives in the users subgraph; here it is only referenced.
type User @key(fields: "id") {
  id: ID!
}

type Query {
  order(id: ID!): Order
}

The resolver for Order.user does something that seems almost too simple at first: it only returns a reference – __typename plus the key field. The actual resolution of name or email happens later in the users subgraph.

const resolvers = {
  Query: {
    order: (_parent, { id }) => fetchOrderById(id),
  },
  Order: {
    __resolveReference: (reference) => fetchOrderById(reference.id),
    // Return just a reference; the users subgraph fills in the rest.
    user: (order) => ({ __typename: 'User', id: order.userId }),
  },
};

This way, each responsibility stays where it belongs. The orders team knows which user an order belongs to (the userId lives in its database), but it doesn’t need to know the user data itself. The router takes care of the rest.

What the router does behind the scenes#

Let’s take a client query that spans both:

query {
  order(id: "42") {
    total
    user {
      name
    }
  }
}

The client sees a query. The router sees a plan. It first fetches total and the user.id from the orders subgraph, then sends an _entities request with the representation { __typename: "User", id } to the users subgraph, whose __resolveReference uses it to get the name, and finally merges everything into one response.

sequenceDiagram
  participant C as Client
  participant R as Router
  participant O as Orders subgraph
  participant U as Users subgraph

  C->>R: order(id: 42) { total, user { name } }
  R->>O: order { total, user { id } }
  O-->>R: { total: 90, user: { id: 7 } }
  R->>U: _entities([{ __typename: User, id: 7 }])
  U-->>R: { name: "Ada" }
  R-->>C: { total: 90, user: { name: "Ada" } }

Once this flow sinks in, it clicks: @key says how an entity can be recognized, __resolveReference says how to make it complete from that recognition, and the router orchestrates in between.

Composing and starting#

The subgraph schemas have to be merged into a supergraph. That’s a build or publishing step, not a task the router performs during a request. Locally, you compose with rover supergraph compose and a configuration that points to the subgraphs:

# supergraph.yaml lists each subgraph and its endpoint
rover supergraph compose --config ./supergraph.yaml > supergraph.graphql

# Start the Apollo Router with the composed supergraph
./router --supergraph supergraph.graphql

In larger setups, managed federation through Apollo Studio / GraphOS takes over this step: each subgraph publishes its schema, composition happens centrally, and the router pulls the current supergraph version. The important point stays the same – composition is the moment errors show up, not runtime.

Shared fields: the difference from Federation 1#

A detail that regularly trips up people moving from Fed 1: in Federation 2, non-key fields are not shareable by default. If the same field of a type is resolved in several subgraphs, it has to be marked explicitly with @shareable – otherwise composition fails. This mainly affects value types that appear identically in several subgraphs.

type Money @shareable {
  amount: Int!
  currency: String!
}

@external is related: a field that this subgraph only references and that belongs to another one is marked as @external – often together with @requires or @provides, when a subgraph needs a foreign field for its logic. Fed 2 is stricter than Fed 1 here, and that’s intentional: ambiguities become errors instead of hiding quietly at runtime.

Three pitfalls#

Federation solves an organizational problem, but it brings technical quirks with it. Three of them carry particular weight.

N+1 lurks in the reference resolver. The router resolves entities one at a time or in batches, and if __resolveReference naively makes one database round trip per call, you end up with many small queries. A DataLoader per subgraph request bundles them – the same pattern you use against N+1 outside of Federation, too.

The key field also has to land reliably in the payload. A field with arguments, or a union or interface return type, doesn’t work as a @key; a nullable field is allowed but not recommended. Different key fields for the same entity across different subgraphs are permitted but error-prone – when in doubt, use the same key everywhere.

And the third point hits everyone who comes from a world where such things only blow up in production: a forgotten @shareable, a type mismatch, a missing @link import – all of these are rejected as early as composing or publishing, not at runtime. The right moment, but an unfamiliar one.

Federation 2 or schema stitching?#

If you have worked with GraphQL for a while, you’ll still know schema stitching – the older way of merging several schemas, today for example with @graphql-tools/stitch. With stitching, you combine remote schemas manually and write the delegation and merge logic yourself. That works, but the coupling lives in the gateway code, not in a spec. Federation instead declares the relationships in the schema (@key, @shareable) and leaves execution to the router. Stitching isn’t dead – for some special cases with third-party schemas you can’t change, it’s still useful. But for a new, team-driven architecture in 2024, I reach for Federation 2.

When I DON’T federate#

The most important point comes last, because it triggers the most pushback in architecture discussions: Federation is overhead. Router, composition, reference resolvers, an extra network hop for each cross-subgraph join – all of that has to be operated and understood. If a single team runs a schema that fits well into one service, Federation solves a problem this team doesn’t have. You take on a distributed system to model an organizational boundary that doesn’t even exist yet.

Federation follows the team structure, not the technology. Only when several teams get in each other’s way on one schema, when deployments become coupled, when a type no longer belongs to anyone – that’s when the split pays off. Before that, a good monolith with clear modules is almost always the better choice. And if you already work cleanly with Apollo Client caching on the client side, you’ll notice: Federation changes nothing on the client – there, it remains exactly the one graph it always was.

Further reading#

Revised and translated from German with the help of AI.