top of page

An Introduction Tutorial To Apollo GraphQL Federation

In this article, we will see what is Apollo Federation and what kind of problem that federation is trying to solve with a real-time example. Introduction to Apollo GraphQL Federation

Apollo Federation is an architecture of composing multiple GraphQL services into a single endpoint.

when you start to think about building a microservice, it would be difficult to divide the GraphQL layer for different services. For example, we are dividing it something like this –

This may seem to make sense at first. but, the problem is adding a new feature. Let’s say that we want to add top comments in Post. Post-service doesn’t know how to resolve a query for top comments because data about comment will be stored in the Comment Service.

On the other hand, Apollo Federation allows us to extend the Post type in Any Service, Here Comment service with a extend type functionality.

Therefore, this keeps all the code for a given feature in a single service and separated from unrelated concerns.

Federation Core Concepts

Mainly, let us see the core concept of apollo federation which compiles different services together to form a single graph

Entities and keys

Firstly, It is a type which is referenced by another service. it creates a connection between services and form a federated graph. entities have a primary key which identifies the specific instance of the type.

entities can be declared by using a keyword @key in the Type

type User @key(fields: "_id") {
   _id : ID
   name : String
   email : String

External Type Reference

Once, the entity is declared, other services can reference this type from their own types. Let’s see how the Comment Service refer the User Service in our example

type Comment {
   user: User

extend type User @key(fields : "_id") {
   _id : ID @external

Likewise, In this example, we have Comment type with a field called user that return the User type. Since User is an entity that lives in another service, we define that type in this service with just enough information to enable composition.

  • extend keyword declares the User is an entity defined elsewhere, here it is User Service

  • The @Key declares the ‘name’. We will use _id to refer to a particular user.

  • The _id field with an @external directive declares the type of _id field(ID ) that is implemented in another service.

On the other hand, To get all the values of Referenced User in Comment Type Definition. we need to write some logic in the Resolver.

Comment: {
    user(comment) {
        return { __typename: "User",_id : comment.userId 
{ __typename: "User",_id : comment.userId }

object is a representation of a User entity. Representations are how services reference each other’s types.

As a result, the gateway will use the representation as an input to the service that owns the referenced entity. So to allow the gateway to get all the values in the referenced service. we need to reference resolver back in the User service.

User: {
        async __resolveReference(object) {
            return await UserModel.getUserById(object._id);

Now, we could get user details in the Comment Type using the reference of it which is a UserID

Extending external types

However, Extending external types solves the problem of one to many relationship use-cases. For example, Post can have many comments and a comment belongs to a post. In the previous section, we just saw external type reference. Here we will see Extending external type

For example, we want to add comments field to Post type

extend type Post @key(fields: "_id"){
        _id : ID @external
        comments : [ Comment! ]}

we can extend the Post type in the Comment service and extend the type with comments which are the type of Comment

Since the Comment service already had a concept of the Post type from returning it, adding additional fields to the overall type can be done just like it was a normal type.

query plan will fetch the _id field for each Post from the Post service and pass those to the comment service, where you can then access these fields on the object passed into your comments


Post: {
    comments(post) {
        return CommentModel.getCommentByPost(post._id);

Building Microservice

Let us build a blog application using apollo federation. it contains three services and an API gateway

You can get the source code for each of the services below –

  • User Service

  • Post Service

  • Comment Service

API Gateway

Firstly, we will create a gateway which connects all the services with a single GraphQL endpoint.

Initialize the project and create a file called gateway.js

npm init --yes
npm install @apollo/gateway apollo-server graphql

touch gateway.js

After that, add the following code in gateway.js

const { ApolloServer } = require('apollo-server');

const { ApolloGateway } = require('@apollo/gateway');

const gateway = new ApolloGateway({
    serviceList: [
      { name: "users", url: "http://localhost:4001/graphql" },
      { name: "posts", url: "http://localhost:4002/graphql" },
      { name: "comments", url: "http://localhost:4003/graphql" },
      // { name: "inventory", url: "http://localhost:4004/graphql" }

(async () => { 
  const { schema, executor } = await gateway.load();
  const server = new ApolloServer({ schema, executor });
    server.listen().then(({ url }) => {
      console.log(` Server ready at ${url}`);

we provide serviceList configuration to the Apollo gateway which provides the name and endpoint for each federated services. name is used for error messages and logging.

API Gateway – Authentication Across services

In Microservice architecture, it is important to authenticate request across different services. This blog explains Microservices Authentication in detail. To achieve this, Apollo Gateway shares the context across services.

@apollo/gateway makes it easy to reuse the context feature of Apollo to customize what information is sent to underlying services.

const { ApolloServer } = require('apollo-server');
const { ApolloGateway, RemoteGraphQLDataSource } = require('@apollo/gateway');

const gateway = new ApolloGateway({
  serviceList: [
    { name: "users", url: "http://localhost:4001/graphql" },
    { name: "posts", url: "http://localhost:4002/graphql" },
    { name: "comments", url: "http://localhost:4003/graphql" },
    // other services

buildService({ name, url }) {
  return new RemoteGraphQLDataSource({
      willSendRequest({ request, context }) {
      // pass the user's id from the context to underlying services
      // as a header called `user-id`
      request.http.headers.set('x-user-id', context.userId);

const server = new ApolloServer({
  context: ({ req }) => {
    // get the user token from the headers
    const token = req.headers.authorization || '';
    // try to retrieve a user with the token
    const userId = getUserId(token);
    // add the user to the context
    return { userId };

server.listen().then(({ url }) => {
  console.log(` Server ready at ${url}`

In this example, buildService return a custom RemoteGraphQLDataSource which allow us to modify the outgoing request with information from the Apollo Service context .request from gateway send x-user-id in the request header across services.


To sum up, we can build a Microservices using apollo federation which solves the problem of stitching GraphQL to a single endpoint. Several teams can work in different services without any dependency between services.

Source: codewall

The Tech Platform



bottom of page