StackPractices
advanced By Mathias Paulenko

GraphQL Federation Onboarding Template

Template for onboarding a service to a federated GraphQL graph: subgraph setup, entities, resolvers, gateway integration, testing, deployment, and monitoring.

Topics: graphql

Overview

This template walks a team through onboarding an existing service into a federated GraphQL graph — the point where a standalone GraphQL service becomes a subgraph behind a shared gateway. It assumes the federation already exists: a gateway is running, at least one subgraph is live, and your team owns a bounded domain such as products, reviews, or orders.

Work through the sections in order. Most production incidents during onboarding come from skipped steps: an entity registered without __resolveReference, a schema that composes locally but conflicts with another subgraph, or a subgraph deployed before its health checks and alerts exist. If the gateway itself isn’t running yet, start with Set Up a GraphQL Federation Gateway with Apollo and come back here once it’s running.

By the end you will have: a subgraph serving _service and _entities, entity resolvers with batched lookups, a composed supergraph validated in CI, integration tests that run cross-subgraph queries, and dashboards that separate subgraph health from gateway health. Budget one to two weeks for a first onboarding; subsequent subgraphs go faster once the checklists and CI wiring exist.


1. Prerequisites

1.1 Before You Start

Complete every item before writing federation code. The most commonly skipped item is the last one: deciding exactly which types and fields this subgraph owns versus which ones it only references.

  • Service has a GraphQL schema (SDL or code-first)
  • Service exposes HTTP POST endpoint for GraphQL queries
  • Service deployed to staging environment
  • Team has access to the Apollo Studio / gateway repo
  • Team has reviewed the API design guidelines
  • Domain boundaries identified (what this subgraph owns)

1.2 Domain Ownership Declaration

Fill this declaration in and share it with the teams that own adjacent subgraphs before you start coding. Ownership disputes discovered at composition time are far more expensive than a thirty-minute conversation up front.

Service name: {service-name}
Team: {team-name}
Domain: {domain description}

Types owned by this subgraph:
  - {Type1}: full ownership
  - {Type2}: full ownership

Types extended from other subgraphs:
  - {Type3}: extends {other-service} with fields {field1}, {field2}

Entities (shared across subgraphs):
  - {Entity1}: @key(fields: "id")
  - {Entity2}: @key(fields: "id")

Run the finished declaration past the GraphQL Schema Review Checklist before implementation — it catches naming, nullability, and pagination problems while they’re still cheap to fix.

1.3 When NOT to Use This Template

This template covers joining an existing federation. Skip it when:

  • You’re creating your first graph. A single GraphQL server is simpler to run and iterate on; introduce federation only when several teams need to ship schema changes independently.
  • You’re decomposing a monolith. Extract the service first, stabilize its schema behind its own endpoint, then onboard it as a subgraph.
  • Your platform uses a managed router such as Apollo GraphOS or Apollo Router. The steps are the same in spirit, but serviceList configuration and rover supergraph compose are replaced by schema publication to the registry.
  • The service exposes a non-GraphQL API. Wrap it in a GraphQL layer first; a subgraph must speak GraphQL natively.

2. Subgraph Setup

2.1 Install Dependencies

# Using Apollo Server
npm install @apollo/server @apollo/subgraph graphql

# Using Mercurius (Fastify)
npm install mercurius mercurius-federation @mercurius/federation

2.2 Subgraph Schema Definition

# products-subgraph.graphqls

extend schema
  @link(url: "https://specs.apollo.dev/federation/v2.0",
        import: ["@key", "@external", "@extends", "@shareable"])

type Product @key(fields: "id") {
  id: ID!
  name: String!
  description: String!
  price: Float!
  currency: String!
  categoryId: ID!
  inStock: Boolean!
  createdAt: DateTime!
  updatedAt: DateTime!
}

type Category @key(fields: "id") {
  id: ID!
  name: String!
  productCount: Int! @shareable
}

type Query {
  product(id: ID!): Product
  products(first: Int = 20, after: String): ProductConnection!
  category(id: ID!): Category
}

type Mutation {
  createProduct(input: CreateProductInput!): CreateProductPayload!
  updateProduct(input: UpdateProductInput!): UpdateProductPayload!
}

type ProductConnection {
  edges: [ProductEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type ProductEdge {
  node: Product!
  cursor: String!
}

type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}

scalar DateTime

Two details matter here. extend schema @link(...) opts the file into Federation 2 and declares which directives the schema uses — list every directive you actually import, because composition validates against this list. And productCount: Int! @shareable marks a field that more than one subgraph may resolve; without @shareable, defining the same field in two subgraphs is a composition error. Reserve @shareable for fields that genuinely resolve identically everywhere — the GraphQL Federated Entity Pattern covers the ownership rules behind that decision.

2.3 Resolver Configuration

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { buildSubgraphSchema } from '@apollo/subgraph';

const typeDefs = `#graphql
  extend schema
    @link(url: "https://specs.apollo.dev/federation/v2.0",
          import: ["@key", "@external", "@extends"])

  type Product @key(fields: "id") {
    id: ID!
    name: String!
    price: Float!
  }

  type Query {
    product(id: ID!): Product
  }
`;

const resolvers = {
  Query: {
    product: (_, { id }, context) => {
      return context.dataSources.productDb.findById(id);
    },
  },
  // Entity resolver — called when gateway resolves a Product by key
  Product: {
    __resolveReference: (reference, context) => {
      return context.dataSources.productDb.findById(reference.id);
    },
  },
};

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

const { url } = await startStandaloneServer(server, {
  listen: { port: 4001 },
  context: async ({ req }) => ({
    dataSources: createDataSources(req),
    user: authenticateUser(req),
  }),
});

Note where __resolveReference lives: on the type, not on Query. The gateway calls it through the _entities field whenever another subgraph needs this object — for example when reviews returns a Product stub and the gateway has to fill in name and price. Context construction is the other half: authenticateUser runs per request inside the subgraph, so decide early whether auth is resolved at the gateway and forwarded, or verified locally in each subgraph.

2.4 Code-First and Alternative Servers

SDL-first isn’t the only option. GraphQL Yoga, Mercurius on Fastify, and code-first stacks like Pothos or TypeGraphQL all produce federation-compatible subgraphs, and buildSubgraphSchema accepts schemas assembled programmatically. What the gateway requires is uniform regardless of stack: an HTTP endpoint that serves _service and _entities correctly. If you run Apollo Router instead of @apollo/gateway, the subgraph code in this section stays identical — only the composition and deployment steps in section 4 change.

2.5 Local Development

You don’t need the production gateway to iterate. rover dev composes a local supergraph from your running subgraphs and watches them for schema changes:

# Terminal 1 — run your subgraph on port 4001
npm run dev

# Terminal 2 — local federated gateway on port 3000
rover dev --name products --url http://localhost:4001/graphql

Add more subgraphs to the same rover dev session with --name/--url pairs, or point it at supergraph.yaml to mirror the staging topology. Query http://localhost:3000 for a sandbox explorer that executes against the composed schema — this is the fastest way to check that an entity extension resolves before touching CI.


3. Entity Resolution

3.1 Entity Resolver Rules

  • Every type with @key must have __resolveReference
  • The resolver receives the key fields and returns the full entity
  • If the entity isn’t found, return null (not an error)
  • Cache entity lookups with DataLoader per request
  • Entity resolvers must be fast (< 50ms p95)
import DataLoader from 'dataloader';

const resolvers = {
  Product: {
    __resolveReference: (reference, context) => {
      // reference = { id: "123", __typename: "Product" }
      return context.loaders.productById.load(reference.id);
    },
  },
  Category: {
    __resolveReference: (reference, context) => {
      return context.loaders.categoryById.load(reference.id);
    },
  },
};

function createLoaders(db) {
  return {
    productById: new DataLoader(async (ids) => {
      const products = await db.products.findMany({ where: { id: { in: ids } } });
      return ids.map(id => products.find(p => p.id === id) || null);
    }),
    categoryById: new DataLoader(async (ids) => {
      const categories = await db.categories.findMany({ where: { id: { in: ids } } });
      return ids.map(id => categories.find(c => c.id === id) || null);
    }),
  };
}

The DataLoader wrapper matters more than it looks. A gateway query that lists fifty products with reviews issues fifty _entities representations in one request; without batching, that’s fifty separate database lookups inside a single client query.

3.2 Extending Entities from Other Subgraphs

# reviews-subgraph.graphqls
# Extends Product entity from Products subgraph

extend type Product @key(fields: "id") {
  id: ID! @external
  reviews: [Review!]!
  averageRating: Float!
  reviewCount: Int!
}

type Review @key(fields: "id") {
  id: ID!
  productId: ID!
  userId: ID!
  rating: Int!
  comment: String!
  createdAt: DateTime!
}

type Query {
  reviews(productId: ID!, first: Int = 10, after: String): ReviewConnection!
}
// Reviews subgraph resolvers
const resolvers = {
  Product: {
    // Resolve extended fields when Product is accessed via gateway
    reviews: (parent, _, context) => {
      return context.dataSources.reviewDb.findByProduct(parent.id);
    },
    averageRating: (parent, _, context) => {
      return context.dataSources.reviewDb.getAverageRating(parent.id);
    },
    reviewCount: (parent, _, context) => {
      return context.dataSources.reviewDb.getCount(parent.id);
    },
  },
};

The id: ID! @external marker tells composition: this subgraph references the key but doesn’t own it. reviews, averageRating, and reviewCount are the fields this subgraph contributes to Product. A useful mental model: the owning subgraph answers “what is this object”, the extending subgraph answers “what else is true about it”.

3.3 Computed Fields with @requires and @provides

When an extended field is derived from data owned by another subgraph, declare the dependency explicitly instead of re-fetching:

# shipping-subgraph.graphqls
extend type Product @key(fields: "id") {
  id: ID! @external
  weight: Float @external
  # shippingCost needs weight — resolved by products, required by shipping
  shippingCost: Float @requires(fields: "weight")
  estimatedDelivery: String
}

type Query {
  shippingEstimate(productId: ID!): Float
}
const resolvers = {
  Product: {
    // parent carries id + weight because @requires told the gateway to fetch both
    shippingCost: (parent) => {
      if (parent.weight == null) return null;
      return calculateShipping(parent.weight);
    },
    estimatedDelivery: (parent, _, context) => {
      return context.dataSources.shippingDb.estimate(parent.id);
    },
  },
};

The gateway reads @requires(fields: "weight") at composition time and adds weight to the representation it sends to shipping. If products stops resolving weight, composition fails — which is the correct outcome, because the field genuinely can’t be computed anymore.

The mirror directive is @provides: an extending subgraph that can already resolve fields of an entity (because it loaded them for its own purposes) may offer them to the gateway so no extra _entities call happens. Use it sparingly — it hides data flow that @requires makes explicit.

3.4 Common Composition Pitfalls

Most onboarding failures surface at rover supergraph compose, not at runtime. The recurring ones:

  • Extending an entity with no matching @key. extend type Product fails composition unless the owning subgraph declared @key on exactly the fields you reference.
  • @requires on fields the subgraph can’t see. A field computed from another subgraph’s data needs @external on the input plus @requires on the output; forgetting the pair leaves the field silently unresolvable instead of erroring loudly.
  • Two subgraphs defining the same field without @shareable. Composition rejects it. Decide which subgraph owns the field, or mark it shareable when both resolve it identically.
  • Inconsistent types for the key field. id: ID! in one subgraph and id: String! in another can compose but breaks reference resolution in confusing ways. Keep key types identical across the graph.
  • Orphan entities. Every @key type needs __resolveReference in its owning subgraph — without it the gateway returns ENTITY_RESOLUTION_FAILED the first time a query touches that type through another subgraph.

4. Gateway Integration

Once the subgraph serves _service and _entities, the gateway has to learn it exists. The request path looks like this:

flowchart diagram: C([Client

A client query touching Product.reviews is planned by the gateway, split across products and reviews, and merged back into one response.

4.1 Gateway Configuration

// gateway/index.js
import { ApolloGateway } from '@apollo/gateway';
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';

const gateway = new ApolloGateway({
  serviceList: [
    { name: 'products', url: 'https://products-service.internal/graphql' },
    { name: 'reviews', url: 'https://reviews-service.internal/graphql' },
    { name: 'users', url: 'https://users-service.internal/graphql' },
    { name: 'orders', url: 'https://orders-service.internal/graphql' },
  ],
  // Poll for schema changes every 10 seconds in staging
  debug: process.env.NODE_ENV !== 'production',
});

const server = new ApolloServer({
  gateway,
  // Disable subscriptions (not supported in federation)
  subscriptions: false,
});

const { url } = await startStandaloneServer(server, {
  listen: { port: 4000 },
  context: async ({ req }) => ({
    user: authenticateUser(req),
    correlationId: req.headers['x-correlation-id'],
  }),
});

serviceList works for small graphs and staging. In production, prefer managed composition: publish each subgraph schema to the registry with rover subgraph publish and let the gateway or router fetch the composed supergraph, so onboarding a subgraph never requires redeploying the gateway itself. The federation guide covers managed composition and production rollout in detail.

4.2 Supergraph Composition

# supergraph.yaml
federation_version: =2.0.0
subgraphs:
  products:
    routing_url: https://products-service.internal/graphql
    schema:
      file: ./subgraphs/products/products.graphqls
  reviews:
    routing_url: https://reviews-service.internal/graphql
    schema:
      file: ./subgraphs/reviews/reviews.graphqls
  users:
    routing_url: https://users-service.internal/graphql
    schema:
      file: ./subgraphs/users/users.graphqls
  orders:
    routing_url: https://orders-service.internal/graphql
    schema:
      file: ./subgraphs/orders/orders.graphqls
# Compose the supergraph schema
rover supergraph compose --config supergraph.yaml > supergraph-schema.graphql

# Validate composition
rover subgraph check products@production \
  --schema ./subgraphs/products/products.graphqls \
  --routing-url https://products-service.internal/graphql

Run rover subgraph check in CI on every pull request that touches the schema. It compares your proposal against the published supergraph and fails the build on breaking changes — long before those changes can break composition in production.

4.3 Propagating Context to Subgraphs

Subgraph requests don’t inherit the client’s headers. Whatever the subgraph needs — user identity, correlation ID, tenant — must be forwarded explicitly in the gateway’s data source:

import { ApolloGateway, RemoteGraphQLDataSource } from '@apollo/gateway';

class AuthenticatedDataSource extends RemoteGraphQLDataSource {
  willSendRequest({ request, context }) {
    request.http.headers.set('x-user-id', context.user?.id ?? '');
    request.http.headers.set('x-user-roles', (context.user?.roles ?? []).join(','));
    request.http.headers.set('x-correlation-id', context.correlationId ?? '');
  }
}

const gateway = new ApolloGateway({
  serviceList: [/* ... */],
  buildService({ url }) {
    return new AuthenticatedDataSource({ url });
  },
});

Keep the forwarded surface small. A subgraph that receives x-user-id and x-user-roles can do field-level authorization without re-validating the JWT; forwarding the raw Authorization header to every subgraph widens the token’s exposure to every service in the graph.


5. Testing

Test at two levels: the subgraph alone, and the composed graph. Subgraph tests answer “does my service resolve its own schema”; integration tests answer “does the gateway assemble a correct response from several subgraphs”. Both are necessary — a subgraph can pass every unit test and still break the graph through a @key mismatch or a missing __resolveReference.

5.1 Subgraph Tests

// Test entity resolution
describe('Product entity resolver', () => {
  it('resolves a product by ID', async () => {
    const result = await executeOperation({
      query: `{ product(id: "1") { id name price } }`,
    });
    expect(result.data.product).toEqual({
      id: '1',
      name: 'Widget',
      price: 9.99,
    });
  });

  it('returns null for non-existent product', async () => {
    const result = await executeOperation({
      query: `{ product(id: "999") { id name } }`,
    });
    expect(result.data.product).toBeNull();
  });
});

// Test __resolveReference directly
describe('Product __resolveReference', () => {
  it('resolves entity reference', async () => {
    const result = await resolvers.Product.__resolveReference(
      { id: '1', __typename: 'Product' },
      testContext
    );
    expect(result.id).toBe('1');
    expect(result.name).toBeDefined();
  });
});

5.2 Federation Integration Tests

// Test cross-subgraph queries
describe('Federated queries', () => {
  it('resolves product with reviews across subgraphs', async () => {
    const result = await gatewayExecute({
      query: `
        query {
          product(id: "1") {
            id
            name
            reviews {
              rating
              comment
            }
            averageRating
          }
        }
      `,
    });
    
    expect(result.data.product.id).toBe('1');
    expect(result.data.product.name).toBeDefined();
    expect(result.data.product.reviews).toBeInstanceOf(Array);
    expect(result.data.product.averageRating).toBeGreaterThan(0);
  });
});

5.3 Testing Checklist

  • Subgraph resolves all own types correctly
  • __resolveReference works for all entities
  • Extended fields resolve correctly
  • Cross-subgraph queries return correct data
  • Null handling: missing entity returns null, not error
  • Error handling: subgraph errors propagate to gateway
  • Authentication context passes through gateway
  • DataLoader batching works within subgraph

Treat rover subgraph check as a contract test and wire it into the subgraph’s CI pipeline: a schema change that breaks composition should fail the pull request, not the production gateway. Run the integration suite against the staging gateway after every subgraph deploy as well — composition success proves the schema fits together, not that the resolvers return sane data through the gateway path.


6. Deployment

6.1 Deployment Checklist

  • Subgraph deployed to staging
  • Schema composed with rover supergraph compose
  • Composition validated (no conflicts, no circular dependencies)
  • Gateway updated with new service URL
  • Integration tests pass in staging
  • Performance benchmarks run (p95 < 200ms for cross-subgraph queries)
  • Monitoring dashboards configured
  • Alerting rules set up
  • Rollback plan documented

6.2 Deployment Steps

The ordering below is deliberate: the subgraph is proven in staging, composition is proven against real SDL, and only then does production change. Reversing any two steps — registering before deploying, or deploying before composing — is how an unreachable or incompatible schema ends up inside a live supergraph.

1. Deploy subgraph service to staging
   - Verify health check passes
   - Verify GraphQL endpoint responds
   - Run subgraph test suite

2. Compose supergraph with new subgraph
   - rover supergraph compose --config supergraph.yaml
   - Verify no composition errors
   - Check for schema conflicts

3. Update gateway configuration
   - Add new service to serviceList
   - Deploy gateway to staging
   - Run integration tests

4. Verify in staging
   - Test cross-subgraph queries
   - Check gateway logs for errors
   - Monitor subgraph health

5. Deploy to production
   - Deploy subgraph service
   - Update gateway serviceList
   - Monitor error rates for 1 hour
   - Verify query success rate > 99.9%

6.3 Publishing to a Schema Registry

With managed composition, deployment is a publish step rather than a gateway redeploy:

# Publish the subgraph schema after a successful deploy
rover subgraph publish products@production \
  --schema ./subgraphs/products/products.graphqls \
  --name products \
  --routing-url https://products-service.internal/graphql

# Confirm the registry composed a new supergraph
rover supergraph fetch products@production > current-supergraph.graphql

Publish order matters when a change spans subgraphs: if reviews adds extend type Product @key(fields: "sku"), products must publish that @key first or composition fails for everyone. Sequence cross-subgraph changes the same way you would sequence database migrations — the additive half first, the dependent half second.

6.4 Rollback

A bad subgraph deploy should never require a gateway rollback when composition is managed: republish the previous subgraph schema (rover subgraph publish with the last known-good SDL) and the router picks up the prior supergraph. With a static serviceList gateway, keep the previous gateway configuration in version control so a revert is a redeploy, not a rebuild. The one rollback that doesn’t work is removing a subgraph that other subgraphs now extend — check extend type dependencies before pulling anything out of the graph.


7. Monitoring

7.1 Key Metrics

MetricSourceAlert Threshold
Subgraph request rateGatewaySudden drop vs. baseline
Subgraph error rateGateway> 1%
Subgraph latency p95Gateway> 200ms
Entity resolver latency p95Subgraph> 50ms
Gateway query latency p95Gateway> 500ms
Schema composition failuresCI/CDAny
Subgraph health check failuresGateway> 3 consecutive
Cross-subgraph query errorsGateway> 0.5%

The two metrics that catch onboarding problems earliest are entity resolver latency and cross-subgraph query errors. A new subgraph that resolves entities slowly degrades every query that touches its types, and that cost shows up as gateway latency, not subgraph errors.

7.2 Monitoring Setup

// Subgraph health check endpoint
app.get('/health', (req, res) => {
  res.json({
    status: 'healthy',
    subgraph: 'products',
    version: process.env.APP_VERSION,
    schemaHash: currentSchemaHash,
  });
});

// Apollo Studio integration for schema tracking
const server = new ApolloServer({
  schema: buildSubgraphSchema([{ typeDefs, resolvers }]),
  plugins: [
    process.env.NODE_ENV === 'production' && ApolloServerPluginInlineTrace(),
  ],
});

Instrument the subgraph before it joins the graph, not after. With ApolloServerPluginInlineTrace, each subgraph reports field-level timings that Apollo Studio aggregates into a federated trace — the difference between “the gateway is slow” and “products.__resolveReference is slow” is exactly the difference between guessing and fixing. If you send traces to your own APM instead, propagate x-correlation-id (section 4.3) so a slow client query can be followed across every subgraph it touched.

8. Security Considerations

  • Subgraph endpoints aren’t publicly reachable — only the gateway (or router) should be able to call them. Enforce this at the network layer, not by convention.
  • Query depth and complexity limits are set at the gateway, not per subgraph — one policy, one place to tune.
  • The gateway forwards only what subgraphs need (section 4.3). The raw Authorization header goes to the auth-owning subgraph or nowhere.
  • Introspection is disabled on subgraph endpoints in production; the gateway’s public introspection exposes the supergraph, which is the intended surface.
  • Error masking is on in production so subgraph internals (stack traces, table names) don’t leak through gateway responses.

9. Troubleshooting

Composition fails with “cannot extend type”

The subgraph you’re extending doesn’t declare the @key you referenced, or declares it on different fields. Check the owning schema first — the error almost never lives in your file.

Queries through the gateway return ENTITY_RESOLUTION_FAILED

__resolveReference is missing, throws instead of returning null, or returns the wrong shape. Reproduce with a direct _entities query against the subgraph before blaming the gateway:

query ($reps: [_Any!]!) {
  _entities(representations: $reps) {
    ... on Product { id name }
  }
}

Entity fields are null in the gateway but populated in the subgraph

The reference resolved, but the extension resolver reads a field the representation doesn’t carry — typically parent.productId when only parent.id is present. Log the representation object; it contains only the key fields plus __typename.

N+1 latency through the gateway

Every entity in a list triggers a separate __resolveReference unless you batch with DataLoader (section 3.1). If p95 jumps only when a query selects a list field, missing batching is the first suspect.

Auth context disappears inside subgraphs

The gateway context function doesn’t forward headers automatically. Propagate the user explicitly — commonly an x-user header set in RemoteGraphQLDataSource.willSendRequest — and confirm the subgraph context reads it.

Schema registry and running gateway disagree

A subgraph schema edited after the last publish leaves the router on an older supergraph. Diff rover subgraph fetch output against the file in the repo; drift here causes fields that exist locally to be invisible in production.

Composition succeeds locally but fails in CI

Almost always a federation version mismatch: supergraph.yaml pins federation_version: =2.0.0 while CI composes with a different Rover release or the registry defaults to another federation version. Pin the Rover version in CI (rover install with an explicit version) and keep federation_version identical across local, staging, and production configs.

See Also

Frequently Asked Questions

How do I share custom scalars across subgraphs?

Define custom scalars (DateTime, JSON, URL) in a shared npm package. Each subgraph imports the scalar definition and resolver. The gateway automatically merges scalar definitions during composition. If scalars are defined differently in two subgraphs, composition fails. Use a shared package like @company/graphql-scalars to ensure consistency.

What happens if one subgraph is down?

The gateway returns partial results for queries that can be resolved by available subgraphs. If a query requires data from the down subgraph, the gateway returns an error for that field while still resolving other fields. Use @requires directives carefully — if a required field can't be resolved, the entire entity resolution fails. Configure circuit breakers in the gateway to fail fast rather than waiting for timeouts.

How do I handle authentication in a federated graph?

Authenticate at the gateway level. Extract the JWT from the Authorization header in the gateway context. Pass the decoded user object to subgraphs via the x-user header or a custom context extension. Each subgraph receives the user in its context and performs field-level authorization. Don't authenticate in each subgraph independently — that causes redundant work and inconsistent behavior.

Can I use subscriptions with federation?

Standard Apollo Federation doesn't support subscriptions through the gateway. If you need real-time updates, run a separate subscription endpoint outside the gateway. Clients connect to the subscription endpoint directly and to the gateway for queries and mutations. Use a pub/sub system (Redis, NATS) to share events between subgraphs and the subscription endpoint. Apollo is working on native subscription support in future federation versions.

What is the difference between @key and @requires?

@key declares how an entity is identified across the graph — type Product @key(fields: "id") tells the gateway "to get this object's other fields, ask for it by id". @requires declares input data for a computed field — shippingCost: Float @requires(fields: "weight") tells the gateway "before calling the shipping subgraph, fetch weight from wherever it lives". In short: @key is identity, @requires is data dependency.

How do I roll out a new subgraph without downtime?

Deploy the subgraph and verify it healthy before registering it — nothing routes to it until composition succeeds. Publish the schema (or update serviceList) so composition happens while the service is already live and warm. Then shift traffic gradually at the client level: queries that never touched the new subgraph are unaffected by construction, and queries that do can be canary-tested against staging first. Keep the old monolith endpoints alive until the federated path has survived at least one full traffic cycle.

How do I debug a failing entity resolution?

Check three things: (1) Is __resolveReference implemented for the entity type? (2) Does the resolver return null when the entity isn't found? (3) Is the key field in the reference object spelled correctly? Enable query tracing in Apollo Studio to see which subgraph resolved which field. Check gateway logs for ENTITY_RESOLUTION_FAILED errors. Test the entity resolver in isolation with a direct subgraph query before testing through the gateway.