Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท Evolving and Testing

Schema Evolution, Federation and Tooling

Change a GraphQL schema without breaking clients: additive changes, deprecation, breaking-change detection, registries, federation and field usage.

A REST API often ships /v2 when it needs to break things. GraphQL takes a different route: there is one schema, it keeps growing, and old fields are retired gently. That only works if you know which changes are safe, have a process for removing fields, and have tools that catch mistakes before they reach a client you cannot update.

This lesson covers that process, then looks at how large organizations split one graph across many teams (federation), and how to see which fields are really used. Remember: no real GraphQL server runs on this site. Commands and server code are read-only; the runnable examples are small stand-ins that show the idea.

Safe, risky and breaking changes

Three kinds of change

Safe Old queries behave exactly as before.
Risky Old queries still run, but clients may be surprised.
Breaking Some existing query now fails or changes meaning.

Clients you cannot update decide what counts as breaking.

1 / 2

Because a client states exactly the fields it wants, adding things is almost always safe: new fields, new types, new optional arguments, new queries and mutations. Nobody selected them, so nobody is affected.

Breaking changes are the ones that make a previously valid query invalid, or change what its answer means:

  • Removing or renaming a type, field, argument or enum value.
  • Changing a field's type (Int to String).
  • Making an output field nullable (String! to String): clients that did not handle null now may crash.
  • Making an input stricter: a nullable argument becomes non-null, or a new required argument or input field appears. Old queries do not send it.

The nullability rules point in opposite directions for output and input. An output field becoming more guaranteed (String to String!) is safe, while an input becoming more demanding is not. See Lists and Non-Null Types for the background.

Risky (sometimes called "dangerous") changes still validate, but behavior shifts. Adding an enum value is the classic one: a client with an exhaustive switch over Genre may have no branch for the new value. Changing a default argument value or adding a new member to a union belongs here too.

The deprecation workflow

To remove a field safely, you do not delete it. You walk it through stages:

  1. Add the replacement. Ship price: Money! next to the old price: Float.
  2. Deprecate the old field with the built-in directive, always with a reason that points to the replacement.
  3. Watch usage. Track how many requests still select the old field, and from which client versions.
  4. Remove it only when usage is zero (or a published sunset date has passed).
GRAPHQL
type Book {
  id: ID!
  title: String!
  price: Float @deprecated(reason: "Use priceInfo, which includes the currency.")
  priceInfo: Money!
}

Deprecated fields still work. Introspection reports them (see Input Types, Custom Scalars and Introspection), so editors strike them through and linters can warn. Arguments and input fields can be deprecated too in current versions of the specification, but check that your server and tools support it before depending on it.

Detecting breaking changes automatically

Humans miss things, so teams compare the new schema with the old one in CI and fail the build on breaking changes. Real tools do this from the schema files (for example graphql-inspector diff, or the checks built into schema registries). The stand-in below does a tiny version of it on a type map, using the rules above. It is not a real tool: it knows only object types, input types and enums.

JS A tiny schema diff

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real tools are smarter in two ways. They understand every schema feature (interfaces, unions, directives, arguments), and the better ones compare against real traffic: a "breaking" removal of a field nobody has queried for months can be allowed, while an apparently safe change that clients depend on gets flagged.

Schema registries

A schema registry is a service that stores every published version of your schema, runs checks on proposals, and shows history. Typical flow: a pull request publishes a proposed schema, the registry compares it with the current production schema and with recent usage, and the check shows up as a pass or fail on the PR. After merge, the new version becomes the live one. Hosted registries exist (Apollo GraphOS is the best known), and open-source options and plain CI scripts are common for smaller teams. For a single team, committing the schema file to Git and diffing it in CI is a perfectly good start.

One graph, many teams: stitching and federation

As an organization grows, one team can no longer own the whole schema. Two families of solutions exist:

  • Schema stitching merges several schemas at a gateway, which you configure with the glue (which field of service A links to which field of service B). It is flexible, and the gateway owns the knowledge of how services relate.
  • Federation (Apollo Federation is the dominant version; other vendors implement the same idea) lets each service, called a subgraph, declare in its own schema how its types relate to types owned elsewhere. A router combines them into a supergraph and plans queries across subgraphs.

The central idea is the entity: a type with a key that more than one subgraph can contribute fields to. Here is the read-only shape of two subgraphs in Federation 2 style:

GRAPHQL
# Catalog subgraph
type Book @key(fields: "id") {
  id: ID!
  title: String!
}

type Query {
  books: [Book!]!
}

# Reviews subgraph
type Book @key(fields: "id") {
  id: ID!
  reviews: [Review!]!
}

type Review {
  stars: Int!
  text: String!
}

A client sees one Book with title and reviews. Behind the scenes the router asks the catalog subgraph for books, then sends the reviews subgraph a list of representations such as { "__typename": "Book", "id": "1" }, and the reviews subgraph resolves each one through a special entity resolver. These details (the _entities field, @external, @requires, composition rules) are specific to the federation specification; check its documentation for your version before building on them.

This stand-in plays the router. It is deliberately simple, but it shows the two-step plan and why a representation list lets the second subgraph work in one batch.

JS A stand-in router joins two subgraphs

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real routers do much more: they parse the query, plan with the supergraph schema, run independent steps in parallel, and handle keys with several fields. What is real here is the idea (keys, representations, a batch call per subgraph); what is invented is every line of code.

Federation is not free. It adds a router to operate, a composition step that can fail on conflicting schemas, and cross-service latency. Start with a single schema and move to federation when team boundaries, not fashion, demand it.

Monitoring field usage

You can only remove a deprecated field if you know who uses it. Production GraphQL servers therefore record, for each request, the operation name, the client name and version (usually sent in a header such as apollo-graphql-client-name, or one you define), and the set of fields selected. Aggregated, this answers questions like "which clients still select Book.price?" and "which fields can we delete?". Registries and observability platforms offer this; you can also log field names from the parsed query yourself. Never put variable values in these logs, since they may hold personal data.

Adopting GraphQL at scale: patterns and a case study

Schema evolution and federation are easiest to understand when you watch them used in a real migration. Large organizations have shared their experiences in conference talks and engineering blogs, and the same patterns show up again and again. Rather than quote any company, this section describes those recurring patterns and follows one fictional, composite company, "Northwind Shop", whose details are invented for teaching. Treat the numbers as illustrations, and read the public write-ups of real adopters (search for GraphQL case studies from large retailers, media and social companies) for their specifics.

The usual starting point

Northwind runs an online shop with a web app, an iOS app and an Android app. Behind them are about forty REST services owned by different teams, and a handful of "aggregation" endpoints built for particular screens. Symptoms that push teams toward GraphQL are almost always the same:

  • Screens waiting on back-end teams for a new field or endpoint.
  • Slow mobile screens, because they chain several requests (the under-fetching problem from GraphQL vs REST).
  • Many near-duplicate endpoints, each serving a slightly different shape.
  • Inconsistent models: "product" means different things in search, cart and checkout.

Pattern 1: start with a gateway, not a rewrite

Northwind does not rewrite anything. One small team builds a GraphQL server in front of the existing REST services (the integration layer from GraphQL Server Architectures) and begins with a single screen, the product page. The first schema covers only what that page needs. Risk is small because the old endpoints still work, and the web team can compare the two versions side by side.

Pattern 2: design the graph for clients, not for services

The first schema draft copies the REST resources one to one, and the front-end teams complain: they need product.price as a formatted value with currency, and they do not care that price lives in one service and stock in another. The team redesigns around the domain: Product, Cart, Order, Customer. Resolvers hide which service answers which field. This is the advice from Schema Design Best Practices, and it is the step that makes later migrations possible.

Pattern 3: migrate field by field behind a stable schema

Because clients only see the schema, the back end can change underneath it. Northwind moves fields from "proxy the old REST API" to "read the new database", one by one, starting with the hottest, simplest reads. The stand-in below tracks this: each field is marked rest or native, and a report shows how much traffic already runs on new code. The schema never changes, so no client is touched.

Node.js A field-by-field migration behind a stable schema

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The important line is the last one: zero client changes. This is the "strangler" approach: grow the new system around the old one, and retire the old parts when no field depends on them. The usage numbers come from the field-usage monitoring described above, which is how you know what to move first and when a legacy endpoint can finally be switched off.

Pattern 4: governance before growth

With three client teams adding fields every week, Northwind adds guardrails early, before the schema has hundreds of types:

  • A schema registry and CI checks that fail on breaking changes (see "Detecting breaking changes automatically" above).
  • Naming and design guidelines (nouns for types, verbs for mutations, payload types, pagination with connections) and a small review group for new top-level types.
  • Ownership: every type and field has a responsible team, visible in the schema (for example in a directive or a description).
  • Operation names required and persisted queries for the mobile apps, so production traffic is predictable and attributable.

Pattern 5: federation when teams need to own their part

After a year the single gateway team is a bottleneck: Search, Cart and Reviews teams all need to change the graph. Northwind moves to federation. Each team publishes a subgraph (Product fields from Search, Cart from Cart, Review from Reviews), and a router composes the supergraph, as shown earlier in this lesson. The move works because the schema was already designed around the domain, and because the registry already checks changes. The costs are the ones listed above: a router to operate, composition failures to handle in CI, and extra cross-service latency that needs tracing and caching.

What tends to go wrong

  • Skipping the design step and exposing REST resources as the schema, which locks every backend shape into the API.
  • No query limits: the first mobile developer who nests six levels can take down a service. Add depth, cost and timeout limits (see Query Depth, Complexity and Other Attacks) before launch, not after.
  • N+1 across services: a field resolver that calls a service per item turns a single query into hundreds of calls. Batch with DataLoader and monitor calls per query.
  • A big-bang switch: moving all clients at once. Migrate screen by screen and keep the old endpoints until usage is zero.
  • Federation too early: adopting it for two teams adds operational load that a shared schema repository would avoid.

A migration playbook from REST

  1. Inventory what clients actually use: the screens, their requests, and the slowest chains.
  2. Pick one screen with clear pain and an enthusiastic front-end team.
  3. Build a gateway with a domain-shaped schema covering only that screen, reading from the existing REST services.
  4. Add guardrails: operation names, limits, tracing, a schema check in CI.
  5. Ship, measure and compare: requests per screen, bytes, time to interactive.
  6. Grow screen by screen, moving fields from proxy to native code when it pays off.
  7. Split ownership with federation only when team boundaries demand it, and retire old endpoints once monitoring shows no remaining callers.

Public case studies of large adopters follow roughly this arc. Their details differ, but the lessons (design the graph around the domain, migrate gradually, invest in governance, add limits early) are consistent.

Python servers

If your backend is Python, three libraries cover most needs. Their code is read-only here, because they cannot run on this site:

  • Strawberry is code-first and built on type hints: you write dataclass-like classes and the schema is generated from them.
  • Ariadne is schema-first: you write SDL, then bind plain Python functions to fields.
  • Graphene is an older code-first library with explicit field objects.
Python
import strawberry

@strawberry.type
class Book:
    id: strawberry.ID
    title: str

@strawberry.type
class Query:
    @strawberry.field
    def books(self) -> list[Book]:
        return [Book(id=strawberry.ID("1"), title="Tides")]

schema = strawberry.Schema(query=Query)

All three support deprecation reasons, and all three can print their schema as SDL, which is the file you feed to a diff or registry check. Check each library's documentation for the exact syntax of your installed version.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which change is usually safe for existing clients?

    Clients only receive fields they select, so a new field affects nobody. The other changes can make old queries fail or change meaning.
  2. 2. Why is changing an output field from String! to String a breaking change?

    Clients written against the non-null guarantee may crash on null. The reverse change, String to String!, is safe for outputs.
  3. 3. What is the best order for retiring a field?

    Deprecation gives clients time to move, and usage data tells you when removal is safe.
  4. 4. In federation, what lets two subgraphs contribute fields to the same type?

    An entity declares a key; the router passes representations containing that key to the subgraph that owns the extra fields.

Summary

  • Adding fields, types and optional arguments is safe; removing, renaming, retyping and tightening inputs are breaking; new enum values are risky.
  • Output nullability and input nullability are checked in opposite directions.
  • Retire fields through deprecation, usage monitoring and only then removal.
  • Diff the schema in CI, ideally together with real usage data, and keep schema versions in a registry.
  • Federation splits one graph across subgraphs joined by entity keys; use it when teams need it, not earlier.
  • Strawberry, Ariadne and Graphene can all print SDL for your checks.

Next: Project: A Bookstore Query API.