SyntaxStudy
Sign Up
GraphQL Apollo Federation: Building a Supergraph
GraphQL Beginner 1 min read

Apollo Federation: Building a Supergraph

Apollo Federation lets multiple GraphQL subgraph services each own a slice of the schema. The Apollo Router (or Apollo Gateway) composes them into a unified supergraph. Clients query one endpoint while the router plans and executes the query across relevant subgraphs in parallel. Entities are types shared across subgraphs. Each subgraph that extends an entity defines a @key directive identifying the primary key field and a __resolveReference function that can fetch the entity from its own data store. This enables cross-service relationships without tight coupling.
Example
// users-subgraph/schema.graphql
extend schema @link(url: "https://specs.apollo.dev/federation/v2.0", import: ["@key"])

type User @key(fields: "id") {
  id: ID!
  name: String!
  email: String!
}

type Query {
  user(id: ID!): User
  me: User
}

// orders-subgraph/schema.graphql — extends User from users-subgraph
extend schema @link(url: "https://specs.apollo.dev/federation/v2.0", import: ["@key", "@external"])

type User @key(fields: "id") {
  id: ID! @external        # owned by users-subgraph
  orders: [Order!]!        # added by this subgraph
}

type Order {
  id: ID!
  total: Float!
  status: String!
}

type Query {
  order(id: ID!): Order
}

// orders-subgraph/resolvers.js
const resolvers = {
  User: {
    // Federation calls this to load user's orders
    orders: (user) => db.orders.findAll({ userId: user.id }),
    // Reference resolver: reconstitute User from { id }
    __resolveReference: (ref) => ({ id: ref.id }),
  },
};

// Apollo Router config (router.yaml):
// supergraph:
//   listen: 0.0.0.0:4000
// subgraphs:
//   users:  { routing_url: http://users-service:4001/graphql }
//   orders: { routing_url: http://orders-service:4002/graphql }

This is the last lesson in this section.

Create a free account to earn a certificate