Working with Schema Stitching

1. Understanding Schema Composition

ApproachUse
Schema stitchingMerge schemas from independent services into one
FederationSubgraphs declare entities + ownership; gateway plans queries
Modular monolithSingle schema split across files in one process

2. Merging Type Definitions

Example: stitchSchemas

import { stitchSchemas } from "@graphql-tools/stitch";

const gateway = stitchSchemas({
  subschemas: [
    { schema: usersSchema, executor: usersExecutor },
    { schema: ordersSchema, executor: ordersExecutor }
  ]
});

3. Delegating to Subschemas

Example: delegateToSchema

import { delegateToSchema } from "@graphql-tools/delegate";

resolvers: {
  Order: {
    customer: (order, _, ctx, info) => delegateToSchema({
      schema: usersSubschema, operation: "query",
      fieldName: "user", args: { id: order.customerId }, context: ctx, info
    })
  }
}

4. Transforming Schemas

TransformUse
RenameTypesResolve naming clashes
RenameRootFieldsNamespace by service
FilterTypesHide internal types
WrapTypeAdd wrapping fields/connections

5. Handling Type Conflicts

StrategyDetail
RenamePrefix conflicting types per subschema
MergeCombine fields from multiple sources
Resolve lastLast subschema wins

6. Implementing Type Extensions

Example: Extend across services

# In gateway:
extend type User {
  orders: [Order!]!
}

7. Forwarding Context

ConcernDetail
Auth headersForward Authorization to subschemas
TracingPropagate traceparent (W3C)
LocalePass Accept-Language

8. Batching Delegated Queries

MechanismDetail
batchDelegateToSchemaGroup sibling delegations
DataLoader at gatewayAvoid N+1 across subschemas
Batched executorSend array of operations downstream

9. Handling Errors in Stitching

SourceBehavior
Subschema errorPropagated with adjusted path
Network failureCatch in executor, return GraphQLError
Partial resultOther subschemas still resolve

10. Testing Stitched Schema

TestDetail
Cross-service queryVerify combined data
Subschema mockReplace executor with mock
Schema validityLint after stitching