What is the difference between GraphQL federation and schema stitching?
Both approaches present one GraphQL schema built from many services, but they disagree on where cross-service relationships are defined.
In federation, each subgraph declares its part of the graph with directives. A subgraph marks a type as an entity and names its key fields. It can also reference entities owned by other subgraphs and add fields to them. A composition step checks these declarations against each other and produces a supergraph schema. The gateway or router then reads that output to plan queries. The router holds no hand-written join logic, because it follows what the subgraphs declared.
In schema stitching, the downstream services expose ordinary GraphQL schemas. The gateway fetches or loads those schemas and merges them. Gateway-side configuration or resolvers then define how a type in one service links to data in another. The services do not need to know they are part of a larger graph.
The choice is not about which approach is newer. It is about who owns cross-service relationships: the teams that own the data, or a team that owns the gateway.
| Dimension | Federation | Schema stitching |
|---|---|---|
| Where join logic lives | In subgraph directives, interpreted by the router | In gateway configuration and resolvers |
| What downstream services must implement | Federation-aware schema and entity resolution by key | A standard GraphQL schema, plus lookup fields if needed for merging |
| How links are declared | Declaratively, inside each subgraph | In gateway code or merge config |
| Who reviews cross-team changes | Subgraph owners, with composition checks | Gateway owners |
| Flexibility of custom logic | Limited to what the directives express | Arbitrary code at the gateway |
How does a federated gateway or router resolve entities across subgraphs?
An entity is a type that more than one subgraph can contribute to, identified by key fields. Suppose a Products subgraph declares type Product @key(fields: "id") and implements a reference resolver (__resolveReference in Apollo's libraries). That resolver turns a stub such as { __typename: "Product", id: "42" } into a full object. A Reviews subgraph declares the same type with the same key and adds reviews: [Review!]!. It never loads product rows. It only needs the id to look up reviews.
Composition merges both schemas into a supergraph. The supergraph records which subgraph owns which field and which keys can join them. Composition fails if the definitions conflict, which is why conflicts are caught before deploy instead of at query time.
At runtime, the router uses the supergraph to build a query plan:
- The client sends one operation asking for
product(id: "42") { name reviews { body } }. - The router fetches
nameandidfrom Products. - The router sends the representation
{ __typename, id }to Reviews through the_entitiesfield. - Reviews resolves
reviewsfor each representation. - The router merges the results and returns one response.
This is why key fields matter. The representation is the only contract between the two teams. Neither team calls the other's service directly.
The most mature federation tooling, including the router, composition libraries and schema registry, comes from Apollo. Review the license terms and any dependency on hosted services yourself before you commit to it.
// Query plan for product(id: "42") { name reviews { body } }
// client -> router --(1) { product(id) { id name } }--------------> Products
// --(2) _entities([{ __typename: "Product", id: "42" }]) -> Reviews
// router merges both results into one response
import { buildSubgraphSchema } from "@apollo/subgraph";
import gql from "graphql-tag";
declare const db: any; // placeholder data access layer for each service
// Products subgraph: owns Product and can resolve it from just its key.
export const productsSchema = buildSubgraphSchema({
typeDefs: gql`
type Query { product(id: ID!): Product }
type Product @key(fields: "id") { id: ID! name: String! }
`,
resolvers: {
Query: { product: (_: unknown, { id }: { id: string }) => db.products.get(id) },
// Called via _entities: turns { __typename, id } into a full Product.
Product: { __resolveReference: (ref: { id: string }) => db.products.get(ref.id) },
},
});
// Reviews subgraph: contributes a field to Product without loading product rows.
// Federation 1 syntax shown; Federation 2 drops `extend`/@external for key fields
// but requires an `extend schema @link(...)` line importing @key.
export const reviewsSchema = buildSubgraphSchema({
typeDefs: gql`
extend type Product @key(fields: "id") {
id: ID! @external
reviews: [Review!]!
}
type Review { body: String! }
`,
resolvers: {
// `product` is the representation the router sent; only `id` is guaranteed.
Product: { reviews: (product: { id: string }) => db.reviews.byProductId(product.id) },
},
});
Two Apollo subgraphs sharing the Product entity by its id key: Products resolves full objects through __resolveReference, while Reviews adds a reviews field using only the key from the representation the router sends to _entities.
How does schema stitching merge types and delegate queries?
In stitching, the gateway builds one combined schema from several independent subschemas, none of which needs to know the others exist. Each root field in the combined schema is delegated to the subschema that defines it. When a query touches a type that is split across services, the gateway resolves the fields it can from the first service, then makes follow-up calls to the others for the rest. This is called delegation.
Merged types are what make this work. You tell the gateway how to fetch a type from each subschema, usually through a lookup query that takes a key. A conceptual configuration for linking Product across a catalog service and an inventory service would declare:
- Catalog subschema:
Productis fetched byidthrough aproductsByIdslookup. - Inventory subschema:
Productis also fetched byid, throughstockByProductIds. - Key selection: the gateway must always request
idso it can call the other service.
This is an illustrative sketch, not a specific library's API. Pointing these declarations at list-accepting lookups lets the gateway batch them. Fifty products in one response then become one call to inventory rather than fifty.
All of this join logic lives in gateway code, not in the services. So whoever maintains the gateway owns every cross-service relationship. Each new link between teams' data becomes a change to that shared codebase.
The upside is flexibility. A legacy GraphQL API, a third-party schema or a REST endpoint can be wrapped as-is. Transforms rename or hide its types and fields, and custom resolvers fill the gaps, with no change required from the upstream service.
// ILLUSTRATIVE ONLY: a generic shape for gateway-side merge config,
// not the exact API of any specific stitching library.
// It shows the join logic that lives in gateway code, not in the services.
const gatewayConfig = {
subschemas: [
{
name: "catalog",
endpoint: "",
mergedTypes: {
Product: {
// The gateway always requests the key so it can call the other service
keySelection: "{ id }",
// A list-accepting lookup lets the gateway batch many keys into one call
lookupField: "productsByIds",
keyFromObject: (product: { id: string }) => product.id,
argsFromKeys: (ids: string[]) => ({ ids }),
},
},
},
{
name: "inventory",
endpoint: "",
mergedTypes: {
Product: {
keySelection: "{ id }",
// Fifty products in one response become one call with fifty ids
lookupField: "stockByProductIds",
keyFromObject: (product: { id: string }) => product.id,
argsFromKeys: (ids: string[]) => ({ productIds: ids }),
},
},
},
],
};
// Neither service knows about the other. Adding a new cross-service link
// means editing this file, so the gateway's maintainers own every join.
export default gatewayConfig;
An illustrative, library-neutral gateway configuration that merges Product across catalog and inventory subschemas by id, using list-accepting lookups so the gateway can batch the follow-up calls.
Who should own cross-service relationships on a multi-team backend?
That flexibility is also where the ownership costs start. In stitching, the links between services usually live in the gateway's merge configuration and custom resolvers. A central platform team ends up writing or reviewing every new cross-service field. When three product teams each want a new link in the same sprint, they queue behind that one team. Over time the gateway becomes a codebase with its own bugs, test suite and on-call rotation. When a merged field breaks, people argue over whether the fault lies with the gateway or the downstream service.
Federation moves that work to the edges. A team that wants to add reviews to Product declares the extension in its own subgraph. The change is reviewed in that team's repository by the people who understand the data. The gateway, or router, composes the result and does not need hand-written glue. This favors organizations with many autonomous teams. Stitching suits a small group or a dedicated API team that already owns the unified schema.
Distributed ownership does not remove coordination. It moves coordination into conventions. Both models still need agreed rules for:
- Deprecations: how long a field stays deprecated before removal, and who confirms that no clients still use it.
- Nullability changes: making a field nullable can break clients that assume a value is always present.
- Key-field changes: altering an entity's identifying fields affects every service that references or resolves that entity.
- Shared value types: enums, custom scalars and common input types must stay consistent across services, which means someone has to own them.
How do schema composition checks in CI save engineering time?
Composition failures are cheap to fix on a branch and expensive to fix in a shared gateway. Suppose a subgraph drops a key field or a subschema changes a shared enum. The failure surfaces when the gateway reloads, or as runtime errors for clients owned by other teams. A CI gate moves that discovery to the pull request of the team that made the change. Other teams then no longer need to read every schema diff by hand to protect themselves. That benefit holds whether you run federation or stitching, which is why the gate matters more than the runtime choice.
A generic pipeline step looks like this:
- Fetch the current production schemas of every other subgraph or subschema from your registry or a versioned artifact store.
- Compose them with the branch's proposed schema, using the same composition logic and version the gateway runs. A mismatch here produces false passes.
- Diff the composed result against the production baseline. Classify each change as safe, dangerous (such as a new enum value that clients may not handle), or breaking (a removed field, or an argument that became required).
- Check recorded client operations against the new schema. These come from gateway traces or persisted query lists.
- Fail the build on composition errors or on breaking changes that hit recorded operations. Provide an explicit, audited override for intentional breaks.
The gate only catches what you configure it to check. Operations outside the recording window are not protected. Neither are rarely used paths or client versions that have not shipped yet. Composition also validates types, not behavior. A resolver that starts returning null where it used to return data still passes.
// check-schema.ts: CI gate run after the compose step has written the proposed
// client-facing (API) schema, built with the same composition version as the gateway.
import { readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { buildSchema, findBreakingChanges, findDangerousChanges, parse, validate } from "graphql";
const load = (p: string) => buildSchema(readFileSync(p, "utf8"));
const baseline = load("artifacts/production-api.graphql"); // fetched from the registry
const proposed = load("artifacts/proposed-api.graphql"); // output of the compose step
// Diff: report dangerous changes, collect breaking ones.
for (const c of findDangerousChanges(baseline, proposed)) console.warn(`DANGEROUS ${c.type}: ${c.description}`);
const breaking = findBreakingChanges(baseline, proposed);
for (const c of breaking) console.error(`BREAKING ${c.type}: ${c.description}`);
// Check recorded operations (exported from traces or the persisted query list).
const opsDir = "artifacts/recorded-operations";
let brokenOps = 0;
for (const file of readdirSync(opsDir).filter((f) => f.endsWith(".graphql"))) {
const errors = validate(proposed, parse(readFileSync(join(opsDir, file), "utf8")));
if (errors.length > 0) {
brokenOps++;
errors.forEach((e) => console.error(`${file}: ${e.message}`));
}
}
// Fail only when a recorded operation breaks, unless an audited approval was recorded.
// Breaking changes no recorded operation uses are reported above but do not fail the build.
const approved = process.env.SCHEMA_BREAK_APPROVAL_ID; // e.g. set by an approved change ticket
if (brokenOps > 0 && !approved) {
console.error(`${brokenOps} recorded operation(s) no longer validate; failing build.`);
process.exit(1);
}
if (brokenOps > 0) console.warn(`Override used: approval ${approved}`);
console.log(`Checked: ${breaking.length} breaking change(s), ${brokenOps} broken operation(s).`);
A graphql-js script for the diff and operation-check steps: it classifies changes against the production baseline and fails the build when recorded client operations no longer validate, unless an audited approval is set.
How do you keep query plans fast and operate the gateway safely?
Composition also cannot tell you whether a valid query will be fast. Latency comes mostly from the shape of the query. Parallel fan-out to several subgraphs costs roughly as much as the slowest one. Sequential dependency chains cost the sum of every hop. Fetching orders, then each order's product, then each product's inventory takes three round trips, because each step needs keys from the one before it.
Hidden entity fan-out is worse. An innocent-looking orders { product { name } } turns into one lookup per order unless two things happen. The router must batch the keys into a single _entities request. The subgraph must then resolve that batch with a loader instead of running one database read per key.
Reading a query plan
Look for nesting in the plan. A plan shaped like Sequence → Fetch(orders) → Flatten(orders.@.product) → Fetch(products) → Flatten(...) → Fetch(inventory) has three dependent hops. Fetches grouped under Parallel overlap in time.
Illustrative estimate: assume 20 ms per subgraph round trip and 2 ms of router overhead per hop. That three-hop chain costs about 66 ms before any resolver work. The same three fetches run in parallel would cost about 22 ms.
Operating the gateway
In both federation and stitching, the gateway adds a network hop and a single point of failure. Treat it as shared critical-path infrastructure:
- Deploy it through its own pipeline with canary releases, separate from subgraph releases.
- Record latency and errors per subgraph so you can see which service caused a slow or failed request.
- Propagate distributed trace context from day one.
- Set per-subgraph timeouts below the client's timeout.
- Decide in advance which fields may return partial data along with errors.
- Plan capacity for peak fan-out, not just peak client requests.
import DataLoader from 'dataloader';
type Product = { id: string; name: string };
// Placeholder data-access layer for the products subgraph.
declare const db: {
query<T>(sql: string, params: unknown[]): Promise<T[]>;
};
// One loader per request, so cached rows never leak between users.
function createProductLoader() {
return new DataLoader<string, Product | null>(async (ids) => {
// One database read for every key in the router's _entities batch.
const rows = await db.query<Product>(
'SELECT id, name FROM products WHERE id = ANY($1)',
[ids],
);
const byId = new Map(rows.map((r) => [r.id, r]));
// DataLoader requires results in the same order as the input keys.
// Missing entities become null instead of failing the whole batch.
return ids.map((id) => byId.get(id) ?? null);
});
}
export function buildContext() {
return { productLoader: createProductLoader() };
}
export const resolvers = {
Product: {
// Called once per representation in _entities. Calls made in the same
// tick are collected by the loader, so N keys produce one query, not N.
__resolveReference(
ref: { id: string },
ctx: ReturnType<typeof buildContext>,
) {
return ctx.productLoader.load(ref.id);
},
},
};
A products subgraph entity resolver that uses a per-request DataLoader, so a batched _entities request for N product keys runs one database query instead of N.
When should you avoid federation, avoid stitching, or migrate between them?
Avoid federation when you cannot change the downstream services. Subgraphs must expose entity keys and reference resolvers, so a vendor API, a legacy SOAP or REST service, or a team that won't adopt the spec has nothing to federate. Stitching can wrap these sources at the gateway without their cooperation. Also weigh tooling lock-in: Apollo Federation's directives, composition rules, and router features tie you to one ecosystem, and its licensing terms deserve legal review before you commit.
Avoid stitching when many teams contribute. Merge configuration and type-merging resolvers live in the gateway, so every cross-service relationship becomes a change request to whoever owns it. Without a funded platform team, that gateway becomes a bottleneck. Heavy custom transforms make it worse, because they are application code that nobody owns.
Neither may be necessary. A single modular GraphQL server, with modules owned by different teams, gives you one schema and no network hops. A REST API or a backend-for-frontend per client works when clients don't need arbitrary cross-domain queries.
To migrate, register the existing monolith as the first subgraph or subschema. Then move one type or field set at a time to a new service, and confirm composition passes before you remove the original resolver. Moving from stitching to federation follows the same pattern: convert merge configuration into entity keys service by service. Going the reverse way means turning those keys back into gateway resolvers.
| Factor | Favors |
|---|---|
| One or two teams | Modular monolith |
| Many autonomous teams | Federation |
| Downstream services can change | Federation |
| Services are fixed | Stitching |
| Third-party or non-GraphQL sources | Stitching or BFF |
| Strong central platform team | Stitching |
| Little central platform capacity | Federation |
| Low tolerance for vendor tooling or licensing | Stitching or modular monolith |
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 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.