Logo di Api Graphql Federation

Api Graphql Federation

Community
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).

Panoramica

Autorej4flmao
Repositoryagent-skills
Nome della skillapi-graphql-federation
Stelle
41
Fork
6
File inclusi
14
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • 14 file inclusi

    Script, modelli di documento e riferimenti che il modello può leggere mentre lavora. I file sono di sola lettura e non vengono mai eseguiti.

  • Open source

    Pubblicata da j4flmao su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Api Graphql Federation in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/api/graphql-federation
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Nuova skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella nella cartella delle skill di quell'agente.

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
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Api Graphql Federation in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Api Graphql Federation non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Api Graphql Federation non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

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.

File inclusi

Il modello legge questi file quando servono, mentre la skill è caricata. Sono accessibili in sola lettura e non vengono mai eseguiti.

Domande frequenti

Cosa fa la skill IA 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...

Perché usare Api Graphql Federation su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Api Graphql Federation è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Api Graphql Federation in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/api/graphql-federation. TypingMind legge il file SKILL.md, include i file associati e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Api Graphql Federation?

Qualsiasi modello che colleghi in TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Api Graphql Federation?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Api Graphql Federation: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Api Graphql Federation è gratuita?

Sì. È pubblicata su GitHub da j4flmao con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, modelli o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Vedi tutti

Crea subito la tua area di lavoro IA

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇