What is Gateway in Apollo Federation: Explanation and Example
gateway is a central service that combines multiple GraphQL subgraphs into one unified API. It acts like a traffic controller, routing client requests to the right subgraph and merging their responses into a single result.How It Works
Think of Apollo Federation as a team of specialists, each managing a part of a big project called a GraphQL API. Each specialist is a subgraph that knows about a specific domain, like users or products. The gateway is like the project manager who knows how to bring all these parts together.
When a client sends a query, the gateway looks at the query and decides which subgraphs need to answer which parts. It then sends requests to those subgraphs, collects their answers, and combines them into one smooth response. This way, clients see one API even though many services work behind the scenes.
Example
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 }); server.listen().then(({ url }) => { console.log(`🚀 Gateway ready at ${url}`); }); })();
When to Use
Use an Apollo Gateway when you want to build a large GraphQL API from smaller, focused services. It helps teams work independently on different parts of the API while providing clients a single endpoint.
Real-world cases include large companies splitting their API by business domains like accounts, orders, and inventory. The gateway makes it easy to add or update services without changing the client side.
Key Points
- The gateway combines multiple GraphQL subgraphs into one API.
- It routes queries to the right subgraphs and merges their responses.
- Clients interact with a single endpoint, hiding the complexity of multiple services.
- It supports independent development and scaling of subgraphs.