Logo vun Api Graphql Federation

Api Graphql Federation

Communautéit
j4flmao
api-graphql-federation

Use this skill when the user says 'graphql federation', 'apollo federation', 'supergraph', 'subgraph', 'schema composition', '@key directive', '@requires', '@shareable', 'apollo router', 'rover compose', 'federate graphql across teams'. Designs and implements Apollo Federation 2 supergraphs: subgraph boundaries, entity keys and resolution, composition and schema checks in CI, and router configuration for security, limits and telemetry. Do NOT use for: single-service GraphQL schema design (backend-graphql-patterns), resolver N+1 and query-cost tuning inside one server (backend-graphql-optimization), REST API gateways (backend api-gateway skills).

Iwwersiicht

Editeurj4flmao
Repositoryagent-skills
Skill-Nummapi-graphql-federation
Stären
41
Forks
6
Matgeliwwert Fichieren
14
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 14 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    Vum j4flmao op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Api Graphql Federation an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/api/graphql-federation
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/universal/api/graphql-federation .claude/skills/api-graphql-federation
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Api Graphql Federation an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Api Graphql Federation automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Api Graphql Federation net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

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

  • Domains/teams and which data each owns.
  • Existing GraphQL servers and libraries (Apollo Server + @apollo/subgraph, GraphQL Yoga, Strawberry, gqlgen, DGS, Hot Chocolate).
  • Managed (GraphOS) or self-hosted composition; router choice (Apollo Router, or alternatives such as Hive Gateway / Cosmo Router).
  • Auth model and latency budget.

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

SituationRecommendation
One team, one serviceSingle GraphQL server; federation adds a router hop and composition overhead
Several teams, distinct domains, all GraphQL-capableFederation
Mostly REST/gRPC backends owned by othersWrap them (GraphQL Mesh, Apollo Connectors, or a BFF subgraph) and compose
Strong need for cross-domain transactions in one mutationFix 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.

graphql
# 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
}
graphql
# 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

DirectiveMeaning
@key(fields: "id")Declares an entity and the fields the router uses to reference it. Multiple keys allowed; resolvable: false for reference-only stubs
@shareableField (or type) may be resolved by more than one subgraph
@externalField 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)
@inaccessibleHides a field/type from the public API schema while still usable for composition
@interfaceObjectLets a subgraph add fields to all implementations of an entity interface
@composeDirectivePreserves a custom directive in the supergraph

@requires example:

graphql
# 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.

ts
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

yaml
# 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
bash
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)

yaml
# 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:

  • Supply the supergraph with --supergraph supergraph.graphql and --hot-reload (self-hosted), or via APOLLO_KEY + APOLLO_GRAPH_REF for managed federation, which delivers new supergraphs without restarts.
  • Some features (e.g. @authenticated/@requiresScopes authorization directives, demand control, some telemetry) require a GraphOS plan; confirm licensing before relying on them.
  • Subgraphs must not be reachable directly from the internet: _entities lets callers fetch any entity by key, bypassing router-level checks.

Performance

  • Minimize sequential fetches: each entity hop in the query plan adds a round trip. Look at query plans for hot operations.
  • Batch __resolveReference with DataLoader.
  • Use @provides when a subgraph already has denormalized data for a nested entity.
  • Set per-subgraph timeouts below the router timeout; return partial data with errors for non-critical subgraphs (nullable fields help).

Anti-Patterns

Anti-patternFix
Subgraph per table/microservice with chatty entity hopsSubgraph per domain/team
Exposing subgraphs publiclyNetwork policy: router-only access
Trusting x-user-id headers from any callerRouter injects, subgraphs only reachable from router, or verify JWT in subgraphs
Breaking changes merged without composition/checkCompose + check in CI as a required status
Shared "common" subgraph that every team editsClear ownership; use @shareable value types sparingly

Checklist

  • Subgraph ownership and entity origins documented.
  • All subgraphs on Federation 2 @link with explicit imports.
  • Entity resolvers batched; _entities not publicly reachable.
  • Composition and breaking-change checks block merges.
  • Router: JWT auth, introspection off in prod, depth/alias limits, demand control measured then enforced, per-subgraph timeouts.
  • Tracing across router and subgraphs with W3C trace context.

References

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

Matgeliwwert Fichieren

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill Api Graphql Federation?

Use this skill when the user says 'graphql federation', 'apollo federation', 'supergraph', 'subgraph', 'schema composition', '@key directive', '@requires', '@shareable', 'apollo router', 'rover compose', 'federate graphql across teams'. Designs and implements Apollo Federation 2 supergraphs: subgraph boundaries, entity keys and resolution, composition and schema checks in CI, and router configuration for security, limits and telemetry. Do NOT use for: single-service GraphQL schema design (backend-graphql-patterns), resolver N+1 and query-cost tuning inside one server (backend-graphql-optimi...

Firwat Api Graphql Federation op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Api Graphql Federation besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Api Graphql Federation an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/api/graphql-federation an. TypingMind liest d'Datei SKILL.md, bündelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Api Graphql Federation benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Api Graphql Federation benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Api Graphql Federation domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Api Graphql Federation gratis?

Jo. De Skill gëtt vum j4flmao ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇