Apollo Federation offers a means of splitting your monolithic GraphQL server into independent microservices. It consists of two components: a gateway and one or more federated microservices. Each microservice holds part of the schema and the gateway merges the schemas into a single schema that can be consumed by the client.
To quote the Apollo docs, Federation is designed with these core principles:
Building a graph should be declarative. With federation, you compose a graph declaratively from within your schema instead of writing imperative schema stitching code.
Code should be separated by concern , not by types. Often no single team controls every aspect of an important type like a User or Product, so the definition of these types should be distributed across teams and codebases, rather than centralized.
The graph should be simple for clients to consume. Together, federated services can form a complete, product-focused graph that accurately reflects how it’s being consumed on the client.
It’s just GraphQL , using only spec-compliant features of the language. Any language, not just JavaScript, can implement federation.
Warning
Apollo Federation currently does not support subscriptions.
In the next example, we'll set up a demo application with a gateway and two federated endpoints: a Users service and a Posts service.
The User service has a simple schema. Note the @key directive: it tells the Apollo query planner that a particular instance of User can be fetched if you have its id. Also, note that we extend the Query type.
type User @key(fields: "id") {
id: ID!
name: String!
}
extend type Query {
getUser(id: ID!): User
}
Our resolver has one extra method: resolveReference(). It's called by the Apollo Gateway whenever a related resource requires a User instance. We'll see an example of this in the Posts service later on. Please note the @ResolveReference() decorator.
Our resolver has one extra method: resolveReference(). It's called by the Apollo Gateway whenever a related resource requires a User instance. We'll see an example of this in the Posts service later on. Please note the @ResolveReference() decorator.
import{Module}from'@nestjs/common';import{GraphQLFederationModule}from'@nestjs/graphql';import{UsersResolvers}from'./users.resolvers';import{UsersService}from'./users.service';// Not included in this example@Module({imports:[GraphQLFederationModule.forRoot({autoSchemaFile:true,}),],providers:[UsersResolvers,UsersService],})exportclassAppModule{}
The Posts service references the User type in its schema by marking it with the extend keyword. It also adds one property to the User type. Note the @key directive used for matching instances of User, and the @external directive indicating that the id field is managed elsewhere.
type Post @key(fields: "id") {
id: ID!
title: String!
body: String!
user: User
}
extend type User @key(fields: "id") {
id: ID! @external
posts: [Post]
}
extend type Query {
getPosts: [Post]
}
Our resolver has one method of interest here: getUser(). It returns a reference containing __typename and any additional properties your application needs to resolve the reference, in this case only an id. The __typename is used by the GraphQL Gateway to pinpoint the microservice responsible for the User type and request the instance. The Users service discussed above will be called on the resolveReference() method.
We will need to create a class representing our User entity. Even though it lives in another service, we will be using and extending it. Note the @extends and @external directives.
import{Module}from'@nestjs/common';import{GraphQLFederationModule}from'@nestjs/graphql';import{User}from'./user.entity';import{PostsResolvers}from'./posts.resolvers';import{UsersResolvers}from'./users.resolvers';import{PostsService}from'./posts.service';// Not included in example@Module({imports:[GraphQLFederationModule.forRoot({autoSchemaFile:true,buildSchemaOptions:{orphanedTypes:[User],},}),],providers:[PostsResolvers,UsersResolvers,PostsService],})exportclassAppModule{}
Our gateway only needs a list of endpoints and will auto-discover the schemas from there. Therefore it is the same for code and schema first, and the code for our gateway is very short:
import{Module}from'@nestjs/common';import{GraphQLGatewayModule}from'@nestjs/graphql';@Module({imports:[GraphQLGatewayModule.forRoot({server:{// ... Apollo server optionscors:true,},gateway:{serviceList:[{name:'users',url:'http://user-service/graphql'},{name:'posts',url:'http://post-service/graphql'},],},}),],})exportclassAppModule{}
Hint
Apollo recommends that you don't rely on the service discovery in a production environment but use their Graph Manager instead.
You can customize the requests between the gateway and federated services using a build service. This allows you to share context about the request. You can easily extend the default RemoteGraphQLDataSource and implement one of the hooks. Please refer to Apollo Docs on RemoteGraphQLDataSource for more information about the possibilities.