What is the difference between GraphQL federation and schema stitching?
Both approaches present many GraphQL services to clients as one schema. They differ in where the composition logic lives and who owns it.
In federation, each subgraph declares its part of the shared graph in its own schema. A subgraph marks an entity with a directive such as @key(fields: "id"), which says how other services can identify and join that type. A composition step merges every subgraph schema into a supergraph, and a router plans queries against it. The join rules travel with the service that owns the data, so the team that changes a type also changes how it is joined.
In schema stitching, the upstream services are ordinary GraphQL APIs. The gateway holds the merging rules: which types combine, which root field fetches a merged type by key, and how to delegate fields to each subschema. The join rules belong to whoever owns the gateway, and the upstreams don't need to know they are being composed.
| Dimension | Federation | Schema stitching |
|---|---|---|
| Composition location | Subgraph schemas, merged by a composition step | Gateway configuration |
| Ownership model | Each team owns its types and their join keys | Gateway team owns merge and delegation rules |
| Upstream requirements | Subgraphs must implement the federation spec | Any spec-compliant GraphQL API |
| Validation timing | At composition, which can run in CI before deploy | Typically when the gateway builds its schema |
| Third-party or legacy APIs | Need a wrapper subgraph | Usable as-is |
| Gateway-side transforms | Limited by design | Renaming, filtering, and wrapping supported |
Both approaches split one client operation into subrequests to upstream services and assemble the results, so neither removes the cost of fan-out.
How does entity resolution work in Apollo Federation?
Federation starts with entities: types that more than one subgraph can contribute fields to, identified by a key. In the example that follows, the products subgraph defines Product @key(fields: "id") with name and price. The reviews subgraph declares the same type with the same key and adds a reviews field. Neither subgraph imports the other's schema. They agree only on the type name and the key.
The key is the join condition. Suppose a client asks for a product's name and reviews. The router first queries the products subgraph and makes sure id is included in the selection, even if the client never asked for it. It then sends the reviews subgraph an _entities query containing a list of representations such as { __typename: "Product", id: "42" }. The reviews subgraph enters the graph through _entities, not through a root field like product(id:). That is why it needs a reference resolver (__resolveReference in the example): something has to turn a bare representation into an object that its field resolvers can work with. Here that resolver can be trivial, because looking up reviews requires nothing beyond id. A subgraph that needs more data would load it in the reference resolver, ideally batched across the whole representations list.
Composition validates all subgraph schemas together before anything is deployed:
subgraph SDLs → composition (CI) → supergraph schema → router
client → router → products subgraph, then reviews subgraph via _entities
Composition fails on a missing or mismatched key, or when two subgraphs disagree on a shared field's type. These conflicts surface in CI as a broken build, not as runtime errors in production.
import { buildSubgraphSchema } from "@apollo/subgraph";
import gql from "graphql-tag";
// products subgraph: owns Product and its core fields
export const productsTypeDefs = gql`
extend schema @link(url: "", import: ["@key"])
type Query { product(id: ID!): Product }
type Product @key(fields: "id") {
id: ID!
name: String!
price: Float!
}
`;
// reviews subgraph: same type name and key, contributes only `reviews`
const reviewsTypeDefs = gql`
extend schema @link(url: "", import: ["@key"])
type Product @key(fields: "id") {
id: ID!
reviews: [Review!]!
}
type Review { id: ID! rating: Int! body: String }
`;
// Placeholder data access; a real service would batch lookups by product id
declare function reviewsByProductId(id: string): Promise<object[]>;
const reviewsResolvers = {
Product: {
// Entry point for _entities: the router sends { __typename: "Product", id: "42" }.
// `id` is all the reviews lookup needs, so the resolver just passes it through.
__resolveReference(ref: { id: string }) {
return { id: ref.id };
},
reviews(product: { id: string }) {
return reviewsByProductId(product.id);
},
},
};
export const reviewsSchema = buildSubgraphSchema({ typeDefs: reviewsTypeDefs, resolvers: reviewsResolvers });
Two Federation 2 subgraphs share the Product entity through @key(fields: "id"), and the reviews subgraph adds a __resolveReference so the router can reach Product through _entities.
How does type merging work in schema stitching?
In stitching, the composition logic lives in the gateway rather than in the upstream schemas. The gateway loads each upstream's schema, usually by introspection, and you add merge rules that tell it how to fetch a given type from each service. A rule for User amounts to three facts per upstream:
- Which root field returns the type: for example,
accountsexposesuser(id)andbillingexposescustomerByUserId(userId). - Which key fields the gateway must already hold before calling that field, such as
id. - How to map the key into the field's arguments.
When a query selects User fields from both services, the gateway resolves the fields it can from the first upstream. It also selects the key, then delegates the remaining fields to the second upstream through its root field, passing the key along. It then merges the two results into one object.
Because merge rules point at ordinary query fields, the upstreams never need to know they are being composed. A third-party API or a legacy GraphQL service with no entity directives can join the graph as long as it exposes some field that looks a type up by an identifier. The same reasoning covers transforms. The gateway can rename types or fields to avoid collisions, filter out fields you don't want to expose, or prefix an entire upstream's types. None of these require changing the upstream.
The cost is that validation also moves into the gateway. You can build the stitched schema in CI and fail on type conflicts or broken merge rules. You can also run representative queries against it. Those checks are gateway code that the platform team writes and maintains, and an upstream team can break them without touching anything it owns.
# Conceptual gateway merge configuration (not tied to any specific library).
# The upstreams are unchanged. All composition logic lives here.
upstreams:
accounts:
url: # schema loaded by introspection
billing:
url: # legacy service, no entity directives
merge:
User:
accounts:
rootField: user # Query.user(id: ID!): User
keyFields: [id] # gateway must hold User.id before calling
args: { id: "$key.id" } # map the key into the field's arguments
billing:
rootField: customerByUserId # Query.customerByUserId(userId: ID!): Customer
keyFields: [id]
args: { userId: "$key.id" }
typeAlias: Customer # billing calls it Customer; the gateway treats it as User
transforms:
billing:
- prefixTypes: "Billing_" # avoid collisions for types not merged above
except: [Customer]
- renameField: { type: Customer, from: cust_email, to: billingEmail }
- filterFields: { type: Customer, remove: [internalRiskScore] } # never exposed
# Validation runs in CI and is owned by the platform team:
# 1. Build the stitched schema from the live upstream schemas; fail on type conflicts.
# 2. Check that every rootField and keyField named above still exists.
# 3. Run representative queries, e.g. { user(id: "u-123") { name billingEmail } }
# An upstream team can break these checks without touching anything it owns.
A conceptual stitching gateway configuration in which merge rules name the root field and key used to fetch User from each upstream, transforms rename, prefix and filter billing's schema, and the comments list the CI checks the platform team has to maintain.
How do query planning and fan-out affect performance?
Both models turn one client operation into several subrequests, so latency comes mostly from how those subrequests are arranged. The number of sequential round trips, how far a query fans out, and the slowest call in each fan-out matter more than the speed of any single resolver.
Take a query that reads orders, each order's product, and each product's inventory. Each level lives in a different service. Assume 30 ms per router-to-subgraph round trip and 20 orders per response. All figures below are illustrative estimates, not measurements.
| Query shape (illustrative estimate) | Round trips on critical path | Estimated network time |
|---|---|---|
| Per-item lookups, executed sequentially | 1 + 20 + 20 = 41 | ~1,230 ms |
| Batched entity lookups, one call per level | 3 | ~90 ms |
| Flattened keys: orders returns a key inventory accepts directly | 2 (products and inventory fetched in parallel) | ~60 ms |
Batching collapses each level into a single call. Federation's representation-based entity fetches do this by default. In stitching, it depends on how you configure delegation and merging. Flattening goes further. If the orders service exposes a key that the inventory service also understands, the router no longer has to wait for products to resolve before it can request inventory, so one level drops out of the critical path.
Parallel fan-out has its own cost. If each call has an assumed 1% chance of exceeding 200 ms, a step that fans out to 20 calls has roughly an 18% chance of being slow (1 − 0.99²⁰, an illustrative estimate). Composing schemas removes none of these hops; it only hides them behind one endpoint. To debug a slow field, you need distributed tracing that propagates context from the router through every subgraph. Only then can you see which hop sits on the critical path.
How do ownership and change management differ, and what does each cost to run?
In federation, each subgraph team publishes its own schema, and the supergraph is recomposed from all of them. In stitching, the platform team owns the gateway code that merges remote schemas, so most changes arrive as pull requests against that one codebase. In either model, check proposed changes against the operations clients actually send, either recorded from traffic or stored in a schema registry. Removing a field nobody queries is safe. Removing one that an old mobile build still requests is a breaking change. A plain schema diff cannot tell those two cases apart.
| Concern | Federation | Stitching |
|---|---|---|
| Who ships schema changes | Each subgraph team | Platform team, via gateway code |
| Composition failure on call | Owning subgraph team, but it can block other teams' deploys | Platform team |
| Per-service requirement | Federation-aware library in every subgraph | None; any spec-compliant GraphQL API works |
| Lock-in risk | Federation spec and tooling; check licensing and hosting terms for the router and registry | Gateway codebase grows large and fragile |
| Where it saves time | Teams extend shared entities in parallel | Integrates uncontrolled or third-party APIs without rewrites |
| Main bottleneck | Shared composition step | Platform team review queue |
Both models need explicit design for three things that cross service boundaries:
- Authorization: decide whether the gateway, each service, or both enforce it.
- Partial responses: define what clients should do when one service fails and others succeed.
- Null propagation: a non-null field that fails in one service nulls its nearest nullable parent. That can erase valid data returned by healthy services. Mark cross-boundary fields nullable unless a failure there should invalidate the parent.
How do you migrate a monolith to federation or stitching?
Start by putting the monolith behind the gateway unchanged. In federation it becomes the first subgraph. In stitching it becomes the first upstream schema. Clients switch to the gateway endpoint before any type moves, so routing problems show up while the schema is still identical to what they already use.
Next, have the monolith declare keys on the types other teams will extend. For example, type Product @key(fields: "id") lets a new reviews service define its own Product stub with the same key and add a reviews field. The monolith must resolve Product by id through the entity lookup. In stitching, the equivalent is a merge config that points Product at a root field such as productsByIds.
Then move one field or type at a time. Each step should run a schema check against the client operations recorded from production traffic. Passing composition alone is not enough, because a schema can compose cleanly and still break a query that a mobile client has cached for months. Delete the monolith's copy of a field only after the operation check shows that nothing still resolves it there.
Some services cannot speak the federation protocol, such as legacy REST backends or third-party GraphQL APIs. Wrap these in a thin adapter subgraph that implements entity resolution and calls the backend.
Switching approaches mid-migration is rarely worth it. Moving from stitching to federation pays off when merge configuration at the gateway has become a bottleneck that one team owns for everyone. The reverse makes sense mainly when you need to compose schemas you cannot modify.
# --- monolith subgraph (products.graphql) ---
# The monolith is the first subgraph. Declaring @key marks Product as an
# entity that other subgraphs can reference and extend by id.
# The monolith must also implement the entity lookup for Product
# (a reference resolver that loads a Product given { id }).
type Product @key(fields: "id") {
id: ID!
name: String!
price: Int
# Field still owned by the monolith; move it later, one field at a time,
# after operation checks show no client depends on this copy.
description: String
}
type Query {
product(id: ID!): Product
}
# --- new reviews subgraph (reviews.graphql) ---
# A stub of Product with the same key. The reviews service only needs the id;
# the gateway asks the monolith for everything else.
extend type Product @key(fields: "id") {
id: ID! @external
reviews: [Review!]!
}
type Review {
id: ID!
rating: Int!
body: String
}
# Syntax shown is Federation 1 style (extend + @external). In Federation 2
# subgraphs opt in with an @link schema directive, and the stub can be
# written as a plain `type Product @key(fields: "id")`.
The monolith subgraph declares Product as an entity keyed on id, so a new reviews subgraph can define a Product stub with the same key and add a reviews field without changing the monolith's other fields.
When should you use federation, stitching, or neither?
The choice depends on where your bottleneck is. If it is team autonomy, meaning many teams need to ship schema changes without waiting on a central owner, federation fits. If it is central control over heterogeneous APIs, meaning one team must unify services it doesn't own, stitching fits.
| Criterion | Federation | Stitching | Neither |
|---|---|---|---|
| Number of teams | Several, each owning a domain | Any; one team owns the gateway | One or two |
| Control over upstream services | Required, since subgraphs must adopt the spec | Not required | Usually full |
| Gateway-side transforms | Limited by design | Core strength (rename, filter, wrap) | Not needed |
| Tolerance for spec-specific directives | High: @key and related directives live in every subgraph |
Low: upstreams stay plain GraphQL | N/A |
| Platform capacity | Must run a router, a composition pipeline and schema checks | Must maintain merge config | Minimal |
When to avoid both
- One or two services, one small team. A single modular GraphQL server, split by domain modules inside one codebase, gives you schema cohesion without network hops or composition failures. Distributed composition solves an organizational problem you don't have yet.
- Clients need a few fixed screens, not ad hoc queries. REST endpoints or a backend-for-frontend that aggregates calls per client is simpler to cache, monitor and reason about.
- The schema works and teams aren't blocked. Stay with one schema. Split only when review queues and deploy coupling on that schema measurably slow teams down. Before that point, a router and a composition pipeline are an ongoing cost with no matching benefit.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to graphql federation vs schema stitching, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.