0
0
GraphqlConceptBeginner · 3 min read

What is Subgraph in Federation in GraphQL: Explained Simply

In GraphQL federation, a subgraph is a separate GraphQL service that defines part of the overall schema. Multiple subgraphs combine to form a single, unified API, allowing teams to build and maintain different parts of the API independently.
⚙️

How It Works

Think of a subgraph as a piece of a big puzzle. Each subgraph is a GraphQL service that owns a specific part of the data and schema. When you use federation, these subgraphs connect together to create one complete API that clients can query.

This setup is like having different departments in a company each managing their own data but sharing it through a common interface. The gateway service acts like a receptionist who knows how to ask each department for the right information and then combines the answers into one response.

💻

Example

This example shows two subgraphs: products and reviews. Each defines part of the schema and can be developed separately.

javascript
const { buildSubgraphSchema } = require('@apollo/subgraph');
const { ApolloServer, gql } = require('apollo-server');

// Products subgraph schema
const productsTypeDefs = gql`
  type Product @key(fields: "id") {
    id: ID!
    name: String
  }

  type Query {
    product(id: ID!): Product
  }
`;

const productsResolvers = {
  Query: {
    product(_, { id }) {
      return { id, name: `Product ${id}` };
    },
  },
  Product: {
    __resolveReference(product) {
      return { id: product.id, name: `Product ${product.id}` };
    },
  },
};

const productsServer = new ApolloServer({
  schema: buildSubgraphSchema({ typeDefs: productsTypeDefs, resolvers: productsResolvers }),
});

productsServer.listen({ port: 4001 }).then(({ url }) => {
  console.log(`Products subgraph ready at ${url}`);
});
Output
Products subgraph ready at http://localhost:4001/
🎯

When to Use

Use subgraphs in federation when you want to split a large GraphQL API into smaller, manageable parts. This is helpful for teams working on different features or domains, allowing them to work independently without conflicts.

For example, an e-commerce site might have separate subgraphs for products, reviews, and users. Each team can update their subgraph without affecting others, and the gateway combines them seamlessly for clients.

Key Points

  • A subgraph is a GraphQL service owning part of the schema.
  • Multiple subgraphs combine via federation to form one API.
  • Subgraphs allow teams to work independently on different data domains.
  • The gateway merges subgraphs and resolves queries across them.

Key Takeaways

A subgraph is a separate GraphQL service that owns part of the overall schema in federation.
Federation combines multiple subgraphs into a single unified API for clients.
Subgraphs enable teams to develop and maintain different API parts independently.
The gateway service merges subgraphs and resolves queries across them seamlessly.