What is Supergraph in Federation in GraphQL: Explained
supergraph in GraphQL federation is a single, unified GraphQL schema that combines multiple smaller schemas (called subgraphs) into one. It lets clients query data from many services through one endpoint, simplifying data fetching and integration.How It Works
Imagine you have several small shops, each selling different products. Instead of visiting each shop separately, a supergraph acts like a big mall that brings all these shops under one roof. In GraphQL federation, each small shop is a subgraph—a GraphQL service with its own schema. The supergraph combines these subgraphs into one big schema.
This combination is done by a gateway that understands how to merge the different schemas and resolve queries across them. When a client sends a query to the supergraph, the gateway breaks it down and sends parts to the right subgraphs, then combines the results before sending them back. This way, clients get a seamless experience querying multiple services as if they were one.
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 }); await server.listen({ port: 4000 }); console.log('Supergraph running at http://localhost:4000/graphql'); })();
When to Use
Use a supergraph when your application needs to combine data from multiple GraphQL services into one easy-to-use API. This is common in large projects where different teams manage different parts of the data, like users, products, or orders.
It helps avoid clients having to call many endpoints separately and manage data stitching themselves. Instead, the supergraph gateway handles all the complexity, making development faster and queries simpler.
Key Points
- A supergraph merges multiple GraphQL subgraphs into one schema.
- It uses a gateway to route queries to the right services.
- Clients query the supergraph as if it were a single API.
- It simplifies working with distributed GraphQL services.