Graphql federation

From j4flmao/agent-skills · View interactive version

Graphql federation is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about GraphQL federation, Apollo Federation 2, composing subgraphs into one supergraph, @key, @shareable, Apollo Router or rover compose. Produces a federated supergraph design with subgraph code. Not for single-service GraphQL schemas (use backend-graphql-patterns).

How to use this skill

Skill file

GraphQL Federation

Purpose

Compose multiple team-owned GraphQL services (subgraphs) into one supergraph served by a router, so each team ships its part of the graph independently. The skill covers where to draw subgraph boundaries, how entities are shared and resolved, how composition is validated, and how to configure the router safely.

Agent Protocol

Trigger

Exact user phrases: "graphql federation", "apollo federation", "supergraph", "subgraph", "schema composition", "@key directive", "@requires", "@shareable", "apollo router", "rover compose", "federate graphql across teams".

Input Context

Output Artifact

Subgraph schemas with federation directives, entity resolvers, supergraph.yaml, CI check commands, and router.yaml. No files unless requested.

Response Format

Subgraphs: {name -> owner team, owned types}
Entities: {Type @key(fields) -> origin subgraph, contributing subgraphs}
Cross-subgraph fields: {field @requires/@provides}
Composition: {rover supergraph compose | GraphOS managed} + check in CI
Router: auth {jwt}, limits {depth/aliases}, demand control {mode}, timeouts {per subgraph}

When Federation Fits

| Situation | Recommendation |

|---|---|

| One team, one service | Single GraphQL server; federation adds a router hop and composition overhead |

| Several teams, distinct domains, all GraphQL-capable | Federation |

| Mostly REST/gRPC backends owned by others | Wrap them (GraphQL Mesh, Apollo Connectors, or a BFF subgraph) and compose |

| Strong need for cross-domain transactions in one mutation | Fix domain boundaries first; federation does not provide transactions |

Boundary rule: a subgraph per bounded context/team, not per database table. Many tiny subgraphs multiply query-plan fetches.

Subgraph Schemas (Federation 2)

Every Federation 2 subgraph opts in with @link and imports the directives it uses.

# accounts subgraph (origin of User)
extend schema
  @link(url: "https://specs.apollo.dev/federation/v2.7", import: ["@key", "@shareable"])

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

type Query {
  me: User
}
# orders subgraph contributes User.orders
extend schema
  @link(url: "https://specs.apollo.dev/federation/v2.7", import: ["@key"])

type User @key(fields: "id") {
  id: ID!
  orders(first: Int = 20): [Order!]!
}

type Order @key(fields: "id") {
  id: ID!
  totalCents: Int!
  status: OrderStatus!
}

enum OrderStatus { PENDING PAID SHIPPED CANCELLED }

In Federation 2, extend type / @extends is not needed to contribute fields to an entity; key fields are shareable automatically. Non-key fields defined in more than one subgraph must be marked @shareable (or one definition @external).

Directives

| Directive | Meaning |

|---|---|

| @key(fields: "id") | Declares an entity and the fields the router uses to reference it. Multiple keys allowed; resolvable: false for reference-only stubs |

| @shareable | Field (or type) may be resolved by more than one subgraph |

| @external | Field is defined elsewhere; used together with @requires or @provides |

| @requires(fields: "weight") | This field needs other subgraphs' fields; the router fetches them first and passes them in the representation |

| @provides(fields: "name") | On a field returning an entity: this subgraph can return those (@external) fields at this path, saving a fetch |

| @override(from: "old") | Moves a field's ownership to this subgraph (incremental migration; progressive label supported) |

| @inaccessible | Hides a field/type from the public API schema while still usable for composition |

| @interfaceObject | Lets a subgraph add fields to all implementations of an entity interface |

| @composeDirective | Preserves a custom directive in the supergraph |

@requires example:

# shipping subgraph
extend schema
  @link(url: "https://specs.apollo.dev/federation/v2.7", import: ["@key", "@external", "@requires"])

type Product @key(fields: "id") {
  id: ID!
  weightGrams: Int @external
  shippingCostCents: Int @requires(fields: "weightGrams")
}

Entity Resolution

The router asks a subgraph for entities through the _entities(representations: [_Any!]!) field. Each representation contains __typename, the key fields, and any @requires fields. The subgraph resolves them in __resolveReference; batch with DataLoader because one _entities call can carry many representations.

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { buildSubgraphSchema } from '@apollo/subgraph';
import DataLoader from 'dataloader';
import { parse } from 'graphql';
import { readFileSync } from 'node:fs';
import { usersRepo, type User } from './users-repo';

const typeDefs = parse(readFileSync('./accounts.graphql', 'utf8'));

type Ctx = { userById: DataLoader<string, User | null> };

const resolvers = {
  Query: {
    me: (_: unknown, __: unknown, ctx: Ctx & { userId?: string }) =>
      ctx.userId ? ctx.userById.load(ctx.userId) : null,
  },
  User: {
    __resolveReference: (ref: { id: string }, ctx: Ctx) => ctx.userById.load(ref.id),
  },
};

const server = new ApolloServer({ schema: buildSubgraphSchema({ typeDefs, resolvers }) });

await startStandaloneServer(server, {
  listen: { port: 4001 },
  context: async ({ req }) => ({
    userId: req.headers['x-user-id'] as string | undefined, // set only by trusted router
    userById: new DataLoader<string, User | null>(async (ids) => {
      const rows = await usersRepo.findByIds([...ids]);
      const byId = new Map(rows.map((u) => [u.id, u]));
      return ids.map((id) => byId.get(id) ?? null);
    }),
  }),
});

Composition and Schema Checks

# supergraph.yaml (local composition with Rover)
federation_version: =2.7.0
subgraphs:
  accounts:
    routing_url: http://accounts:4001/graphql
    schema:
      file: ./schemas/accounts.graphql
  orders:
    routing_url: http://orders:4002/graphql
    schema:
      file: ./schemas/orders.graphql
rover supergraph compose --config ./supergraph.yaml --output supergraph.graphql

# With GraphOS: check against real client traffic before merge, publish after deploy
rover subgraph check  my-graph@prod --name accounts --schema ./schemas/accounts.graphql
rover subgraph publish my-graph@prod --name accounts --schema ./schemas/accounts.graphql \
  --routing-url http://accounts:4001/graphql

Without GraphOS, run composition in CI on every subgraph PR and use a schema-diff tool (e.g. GraphQL Inspector) for breaking-change detection.

Common composition failures: a non-key field defined in two subgraphs without @shareable; @requires/@provides referencing fields not marked @external; inconsistent enum or field types across subgraphs; @key fields that do not exist on the type.

Router Configuration (Apollo Router)

# router.yaml
supergraph:
  listen: 0.0.0.0:4000
  introspection: false

health_check:
  listen: 0.0.0.0:8088
  enabled: true            # GET /health

authentication:
  router:
    jwt:
      jwks:
        - url: https://auth.example.com/.well-known/jwks.json

headers:
  all:
    request:
      - propagate:
          named: authorization   # subgraphs re-verify or trust the router network

limits:
  max_depth: 15
  max_aliases: 30
  max_root_fields: 20

demand_control:
  enabled: true
  mode: measure              # observe costs first, then switch to enforce
  strategy:
    static_estimated:
      list_size: 50
      max: 5000

traffic_shaping:
  router:
    global_rate_limit:
      capacity: 1000
      interval: 1s
  all:
    timeout: 10s
  subgraphs:
    accounts:
      timeout: 3s

telemetry:
  exporters:
    tracing:
      common:
        sampler: 0.1
      otlp:
        enabled: true
        endpoint: http://otel-collector:4317
        protocol: grpc

Notes:

Performance

Anti-Patterns

| Anti-pattern | Fix |

|---|---|

| Subgraph per table/microservice with chatty entity hops | Subgraph per domain/team |

| Exposing subgraphs publicly | Network policy: router-only access |

| Trusting x-user-id headers from any caller | Router injects, subgraphs only reachable from router, or verify JWT in subgraphs |

| Breaking changes merged without composition/check | Compose + check in CI as a required status |

| Shared "common" subgraph that every team edits | Clear ownership; use @shareable value types sparingly |

Checklist

References

Note: reference files may contain router configuration from older Router versions; verify keys against the current Apollo Router configuration reference.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.