Логотип Api Graphql Federation

Api Graphql Federation

Спільнота
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).

Огляд

Видавецьj4flmao
Репозиторійagent-skills
Назва навичкиapi-graphql-federation
Зірки
41
Форки
6
Файли в пакеті
14
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 14

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Опубліковано на GitHub користувачем j4flmao. Перегляньте вихідний вміст перед установленням.

Встановлення

Установіть навичку ШІ Api Graphql Federation у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до Плагіни → Навички.
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/api/graphql-federation
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Нова навичка → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

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
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Api Graphql Federation в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Api Graphql Federation, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції Markdown, а не код для певного постачальника, тому навичка Api Graphql Federation не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож невикористана навичка нічого не коштує.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

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.

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ 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...

Навіщо використовувати Api Graphql Federation у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Api Graphql Federation — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Api Graphql Federation у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/api/graphql-federation. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Api Graphql Federation?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Api Graphql Federation?

Зі скількома забажаєте. Якщо модель підтримує навички, ви можете використовувати з нею Api Graphql Federation — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama та інші — усе в TypingMind із власними ключами API.

Чи безкоштовна навичка ШІ Api Graphql Federation?

Так. Навичку опубліковано на GitHub: j4flmao, за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це багаторазовий набір інструкцій, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти для виклику — код, який десь виконується й повертає результат. Натомість навичка ШІ надає моделі знання та порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний ШІ-простір уже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇