What is GraphQL Federation: Explanation and Example
GraphQL Federation is a way to combine multiple GraphQL services into one unified API. It lets different teams own parts of the graph and still provide a single endpoint for clients to query.How It Works
Imagine you have different teams building different parts of a big app, like one team for users and another for products. Each team creates its own GraphQL service with its own data and schema. GraphQL Federation acts like a friendly coordinator that stitches these separate services together into one big graph.
When a client sends a query, the federation gateway figures out which service owns which part of the data. It then asks each service for its piece and combines the results before sending them back. This way, clients see one smooth API, but behind the scenes, many services work together.
Example
This example shows two simple federated services: one for users and one for products. The gateway combines them so clients can query both in one request.
const { ApolloServer } = require('@apollo/server'); const { ApolloGateway } = require('@apollo/gateway'); const gateway = new ApolloGateway({ serviceList: [ { name: 'users', url: 'http://localhost:4001/graphql' }, { name: 'products', url: 'http://localhost:4002/graphql' } ] }); (async () => { const server = new ApolloServer({ gateway, subscriptions: false }); const { url } = await server.listen({ port: 4000 }); console.log(`🚀 Gateway ready at ${url}`); })();
When to Use
Use GraphQL Federation when you have multiple teams or services that own different parts of your data and want to keep them separate but still offer a single API to clients. It helps scale development by letting teams work independently.
For example, a large e-commerce site might have separate services for users, products, and orders. Federation lets these services combine their schemas so the frontend can query all data in one request without knowing about the backend split.
Key Points
- Federation stitches multiple GraphQL services into one graph.
- Each service owns its part of the schema and data.
- The gateway routes queries to the right services and combines results.
- It enables team autonomy and scalable API development.