StackPractices
advanced By Mathias Paulenko

Set Up a GraphQL Federation Gateway with Apollo

Compose multiple GraphQL services into a single federated supergraph using Apollo Federation and a gateway that routes queries across subgraphs.

Apollo Federation splits a monolithic GraphQL API into independently deployable subgraphs. A gateway composes them into one supergraph and routes each part of a query to the service that owns it. Entities like User can be defined in one subgraph and extended in others, so teams own their domains without a shared schema file. This recipe builds a working two-subgraph setup with Apollo Server 4. The entity mechanics are covered in depth by the federated entity pattern.

When to Use This

  • Several teams need to own different slices of one GraphQL API
  • A monolithic GraphQL server has grown too large to ship as one codebase
  • You need independent deployment and scaling per API domain

Skip this for a single-team API: federation adds a composition step, a new network hop, and operational overhead that a modular monolith avoids. For production concerns beyond this setup (router HA, persisted queries, CI checks), see the production sections of the Complete Guide to GraphQL Federation.

Prerequisites

  • Two or more GraphQL services you can deploy separately
  • @apollo/server, @apollo/subgraph, @apollo/gateway, graphql, graphql-tag

Solution

1. Install Dependencies

# In each subgraph
npm install @apollo/server @apollo/subgraph graphql graphql-tag

# In the gateway
npm install @apollo/server @apollo/gateway graphql

2. Define the Users Subgraph

// users-service/index.ts
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { buildSubgraphSchema } from '@apollo/subgraph';
import { gql } from 'graphql-tag';

const typeDefs = gql`
  type User @key(fields: "id") {
    id: ID!
    name: String!
    email: String!
  }

  type Query {
    user(id: ID!): User
    users: [User!]!
  }
`;

const users = [
  { id: '1', name: 'Alice', email: 'alice@example.com' },
  { id: '2', name: 'Bob', email: 'bob@example.com' },
];

const resolvers = {
  Query: {
    user: (_: unknown, { id }: { id: string }) => users.find((u) => u.id === id),
    users: () => users,
  },
  // Called by the gateway whenever another subgraph references a User by key.
  User: {
    __resolveReference: (ref: { id: string }) => users.find((u) => u.id === ref.id),
  },
};

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

startStandaloneServer(server, { listen: { port: 4001 } });

3. Define the Posts Subgraph

// posts-service/index.ts
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { buildSubgraphSchema } from '@apollo/subgraph';
import { gql } from 'graphql-tag';

const typeDefs = gql`
  type Post @key(fields: "id") {
    id: ID!
    title: String!
    content: String!
    author: User
  }

  type User @key(fields: "id") @extends {
    id: ID! @external
    posts: [Post!]!
  }

  type Query {
    posts: [Post!]!
    post(id: ID!): Post
  }
`;

const posts = [
  { id: '101', title: 'Hello', content: 'World', authorId: '1' },
  { id: '102', title: 'Federation', content: 'Guide', authorId: '2' },
];

const resolvers = {
  Query: {
    posts: () => posts,
    post: (_: unknown, { id }: { id: string }) => posts.find((p) => p.id === id),
  },
  // Returns a reference; the gateway fetches User fields from the users subgraph.
  Post: {
    author: (post: { authorId: string }) => ({ __typename: 'User', id: post.authorId }),
  },
  User: {
    posts: (user: { id: string }) => posts.filter((p) => p.authorId === user.id),
  },
};

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

startStandaloneServer(server, { listen: { port: 4002 } });

Note what the posts schema does not declare: User.name. A previous version of this example carried author: User @provides(fields: "name"), which told the gateway that posts could resolve name itself; it couldn’t, so name came back null. Only mark a field @provides when the returning subgraph actually resolves it.

4. Create the Gateway

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

const gateway = new ApolloGateway({
  supergraphSdl: new IntrospectAndCompose({
    subgraphs: [
      { name: 'users', url: 'http://localhost:4001/graphql' },
      { name: 'posts', url: 'http://localhost:4002/graphql' },
    ],
    // Poll for schema updates; remove for a static local setup.
    pollIntervalInMs: 10_000,
  }),
});

interface GatewayContext {
  user: { id: string; role: string } | null;
}

// Stand-in for your real token verification.
async function verifyToken(token: string): Promise<GatewayContext['user']> {
  if (token === 'alice-token') return { id: '1', role: 'user' };
  if (token === 'admin-token') return { id: '9', role: 'admin' };
  return null;
}

const server = new ApolloServer<GatewayContext>({ gateway });

const { url } = await startStandaloneServer(server, {
  listen: { port: 4000 },
  context: async ({ req }) => {
    const token = req.headers.authorization?.replace('Bearer ', '');
    return { user: token ? await verifyToken(token) : null };
  },
});

console.log(`Gateway ready at ${url}`);

IntrospectAndCompose is the explicit form of what serviceList did implicitly: the gateway introspects each subgraph at startup, composes the supergraph, and re-polls on an interval — the Apollo gateway docs cover the full configuration surface. In production you would replace this with a published supergraph from Apollo Studio (see Variants).

5. Query Across Subgraphs

query {
  posts {
    id
    title
    author {
      id
      name
      posts {
        id
        title
      }
    }
  }
}

The gateway fetches posts from the posts subgraph, resolves author.name through an _entities call to the users subgraph, then resolves author.posts back in the posts subgraph, all inside one client request.

How It Works

  1. @key declares an entity’s primary key. The gateway uses it to fetch the same entity from whichever subgraph owns the requested fields.
  2. @extends + @external let the posts subgraph add User.posts without owning User: @external fields are resolved elsewhere and can only be referenced, never returned by this subgraph.
  3. __resolveReference is the entity resolver. The gateway calls it through the _entities root field with { __typename, id } and expects the full object back — the federation spec’s entity resolution section details the exact contract.
  4. Composition happens at gateway startup: IntrospectAndCompose pulls each subgraph’s schema, validates that fields have a single owner, and builds a query plan table.
  5. Query planning splits the incoming operation by field owner. The gateway executes subgraph fetches in dependency order and stitches the results. That round-trip order is what makes N+1 worth watching, so keep DataLoader batching in mind once entities fan out.
flowchart diagram: Client

Variants

Managed Federation with Rover and Apollo Studio

Publish subgraph schemas to Apollo Studio instead of composing from introspection:

rover subgraph publish my-graph@current \
  --name users \
  --routing-url http://localhost:4001/graphql \
  --schema ./users-schema.graphql

The gateway then polls the published supergraph:

const gateway = new ApolloGateway(); // reads APOLLO_KEY and APOLLO_GRAPH_REF

Managed mode gives you composition checks in CI, schema change validation, and instant rollback; see the federation guide for the full production setup.

Forwarding Auth to Subgraphs

The gateway context isn’t automatically forwarded: subgraphs only see what buildService puts on the wire. Attach user claims as headers:

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

const gateway = new ApolloGateway({
  supergraphSdl: new IntrospectAndCompose({
    subgraphs: [
      { name: 'users', url: 'http://localhost:4001/graphql' },
      { name: 'posts', url: 'http://localhost:4002/graphql' },
    ],
  }),
  buildService({ url }) {
    return new RemoteGraphQLDataSource({
      url,
      willSendRequest({ request, context }) {
        if (context.user) {
          request.http?.headers.set('x-user-id', context.user.id);
          request.http?.headers.set('x-user-role', context.user.role);
        }
      },
    });
  },
});

Subgraphs read x-user-id/x-user-role in their own context function and apply authorization there. For identity propagation patterns across services, see the federated identity pattern.

Health Checks and Startup Ordering

If the gateway starts before a subgraph, composition fails and the gateway refuses to serve. In containers, gate startup on subgraph health:

# docker-compose.yaml (excerpt)
gateway:
  depends_on:
    users:
      condition: service_healthy
    posts:
      condition: service_healthy

Each subgraph exposes Apollo Server’s built-in health endpoint at /.well-known/apollo/server-health, which returns {"status":"pass"} once the schema is ready.

Best Practices

  • Use managed federation in production. Studio handles composition, schema checks, and rollback; IntrospectAndCompose is for local development.
  • Keep subgraphs domain-focused. One team, one subgraph, one bounded context.
  • Forward identity as headers. The gateway authenticates; subgraphs authorize.
  • Watch query plans. Studio shows how each operation splits across subgraphs; chatty plans mean reshaping the schema, not the resolvers.
  • Deploy several gateway replicas. The gateway is a single point of failure; put it behind a load balancer.

Common Mistakes

  • @provides on fields the subgraph can’t resolve. The gateway will route the field to that subgraph and get null. Only provide what you actually return.
  • Defining the same field in two subgraphs. Every field needs exactly one owner; composition fails otherwise (unless it’s @shareable).
  • Forgetting __resolveReference. Any entity referenced by key needs it, or _entities calls return null.
  • Using @external on owned fields. @external means “resolved elsewhere”. Marking an owned field external makes it unresolvable.
  • Composition errors only visible in logs. The gateway fails to serve when composition breaks; watch startup logs and health endpoints in CI.
  • Entity fan-out N+1. Resolving a list of references one subgraph call at a time; batch _entities usage is automatic, but entity-heavy plans still deserve a look.

Frequently Asked Questions

What is the difference between Federation 1 and Federation 2?

Federation 2 removes most boilerplate: @extends is no longer required to reference an entity, value types can be shared, and @shareable, @inaccessible, @override, and @tag give finer control over composition. Subgraphs composed with @apollo/subgraph v2+ produce Federation 2 SDL; migration from Fed 1 is incremental, so you don't have to rewrite schemas at once.

How does the gateway handle a subgraph outage?

Queries needing the down subgraph fail; queries touching only healthy subgraphs keep working. Composition failures at startup are harder: with IntrospectAndCompose the gateway can't build a supergraph and refuses to start, so publish the supergraph in production so the gateway can boot from the last known SDL.

Can I add a non-federated GraphQL service to the gateway?

No. Every service must expose a subgraph schema via buildSubgraphSchema (it adds _service and _entities). For legacy or third-party GraphQL APIs, use schema stitching or wrap them behind a small federated facade.

Do subgraphs ever talk to each other?

Never. Subgraphs know nothing about the gateway's other services; every cross-subgraph resolution goes through the gateway's query plan and _entities calls. If two domains need each other's data, model the dependency as entity references.

How do I debug composition errors locally?

Start each subgraph alone and query its _service { sdl } field. That SDL is what the gateway composes. rover subgraph check validates a schema against the published graph before deploying, and rover supergraph compose reproduces composition offline so you can see the exact error.

Should the gateway enforce authorization?

Authenticate at the gateway (verify the token once), authorize in subgraphs (they own the domain rules). Forward identity via buildService headers; field-level rules belong next to the resolvers that know the data.