Schema stitching and federation

Intermediate · 3 min

Two ways to present several GraphQL services as one schema: stitching merges them in a gateway, federation has each service declare how types join.

Before thisResolversSchema design principlesA server with GraphQL Yoga

Apollo GraphQL · 3 min

Schema stitching and federation

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Apollo GraphQLReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A single GraphQL schema owned by one team stops scaling when many teams own different parts of the data, so the schema has to be assembled from parts.
  • Schema stitching builds the combined schema in a gateway, where you write the links between services yourself.
  • Federation puts the links in the subgraphs: each declares which types it owns and which fields identify them, and composition checks that the parts fit.
  • A type can be shared across services by an entity key, so one service can add fields to a type another owns without either calling the other directly.
  • Both approaches add a hop and a failure mode. Reach for them when team boundaries demand it, not before.

One schema, many owners

A GraphQL API starts as one server with one schema. That stays comfortable while one team owns it. Then the company grows. The product team owns products, the reviews team owns reviews, the accounts team owns users, and each wants to deploy on its own schedule. If they all edit one schema in one repo, every change collides. If they each run a separate GraphQL API, clients must talk to several endpoints and stitch the results together themselves, which gives up the best part of GraphQL.

The answer is to keep separate services but present one schema. There are two main ways to do that.

Stitching: the gateway merges

Schema stitching takes several independent GraphQL schemas and merges them into one in a gateway process. Where the schemas overlap, you tell the gateway how to link them.

I ran a stitched gateway with @graphql-tools/stitch 10.4.5. One Yoga server owned Product (id, name), another owned Review (id, body, productId) and exposed reviewsByProduct(productId). Neither knew the other existed. The gateway added the link:

const gateway = stitchSchemas({
  subschemas: [productsSubschema, reviewsSubschema],
  typeDefs: `extend type Product { reviews: [Review!]! }`,
  resolvers: {
    Product: {
      reviews: {
        selectionSet: "{ id }",
        resolve: (product, _args, ctx, info) =>
          delegateToSchema({
            schema: reviewsSubschema,
            operation: "query",
            fieldName: "reviewsByProduct",
            args: { productId: product.id },
            context: ctx,
            info,
          }),
      },
    },
  },
});

Executing { product(id: "7") { name reviews { body } } } against it returned the product name and the reviews, assembled from two services. The important detail is where the knowledge lives: the gateway author wrote the reviews field, chose which query to call, and mapped product.id to productId. The services are unaware.

That has an upside. You can stitch services you do not control, including third-party APIs. The downside is that the gateway becomes the place where cross-service knowledge accumulates, and whoever owns the gateway owns every relationship. When a service renames a field, the gateway breaks silently.

Federation: the services declare the join

Apollo Federation moves the link into the services. Each service becomes a subgraph and declares which types it owns and how to identify them using @key:

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

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

The reviews subgraph adds a reviews field to a Product it does not own, and says: I can find a product by its id. Neither subgraph calls the other. A router receives a client query, works out which subgraph holds each field, asks the products subgraph for the product, then asks the reviews subgraph for reviews by sending it a representation such as { __typename: "Product", id: "1" }. Apollo Federation basics goes through how that works.

Composition is the other half. A build step takes all subgraph schemas and checks that they fit together, producing a supergraph schema. I composed two subgraphs with @apollo/composition 2.14.5 and it succeeded. When I made the second subgraph declare Product.name as Int! while the first said String!, composition refused with: Type of field "Product.name" is incompatible across subgraphs. Catching that at build time, before the router ever sees traffic, is the main safety federation adds over stitching. The router and the supergraph covers how it is used at runtime.

Comparing them

Stitching Federation
Where links are defined gateway code or config @key and related directives in each subgraph
Services must know about it no yes, they use federation directives
Works with third-party APIs yes only with a wrapper subgraph
Checked before deploy by your own tests by composition
Ownership gateway team owns relationships teams own their types and extensions

Neither is free. Both add a network hop and both make a failure in one service visible in a query that touches several, so partial responses and error handling matter more. They also move the N+1 problem across the network, which is why subgraph entity lookups batch their keys.

Do you need either

Not usually at the start. A monolithic schema with good schema design can serve a lot of teams, and modules inside one server separate code ownership without separating deployment. Federation earns its cost when teams must ship independently and a shared deploy is the bottleneck. If the real problem is a messy schema, splitting it into services gives you the same mess across a network.

What the video covers

Apollo’s “What is GraphQL Federation?” is a short video from May 2022, under three minutes. Its chapters are: what is the deal with federation, the router, and GraphQL directives. It is made by the vendor of federation, so it covers federation only and does not compare it with stitching; the stitching half of this lesson comes from my run and the dotnet runner-up, a 30-minute 2020 walkthrough of stitching in Hot Chocolate on .NET, which is far from JavaScript but explains the gateway idea. The WunderGraph video under “go deeper” is about a minute long, so treat it as a recap. I did not have transcripts.

Where this fits

This opens the final group, which is about running GraphQL as a system. Next, Apollo Federation basics builds a federated pair of subgraphs.

Check yourself

  1. 01What problem do stitching and federation both solve?

    They present multiple GraphQL services as one schema to clients, so teams can own and deploy their part independently.

  2. 02Where does the cross-service link live in stitching, and where in federation?

    In stitching it is configuration and resolvers in the gateway. In federation it is declared in each subgraph's schema with directives such as @key.

  3. 03When is a single schema the better choice?

    When one team owns the data and the service, since splitting it adds a network hop, a composition step and a new failure mode for no organisational gain.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark