Federation

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 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.

Federated example: Users

First, install the optional dependency for federation:

  1. $ npm install --save @apollo/federation

Schema first

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.

  1. type User @key(fields: "id") {
  2. id: ID!
  3. name: String!
  4. }
  5. extend type Query {
  6. getUser(id: ID!): User
  7. }

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.

  1. import { Args, Query, Resolver, ResolveReference } from '@nestjs/graphql';
  2. import { UsersService } from './users.service';
  3. @Resolver('User')
  4. export class UsersResolvers {
  5. constructor(private usersService: UsersService) {}
  6. @Query()
  7. getUser(@Args('id') id: string) {
  8. return this.usersService.findById(id);
  9. }
  10. @ResolveReference()
  11. resolveReference(reference: { __typename: string; id: string }) {
  12. return this.usersService.findById(reference.id);
  13. }
  14. }

Finally, we hook everything up in a module together with a GraphQLFederationModule. This module accepts the same options as the regular GraphQLModule.

  1. import { Module } from '@nestjs/common';
  2. import { GraphQLFederationModule } from '@nestjs/graphql';
  3. import { UsersResolvers } from './users.resolvers';
  4. @Module({
  5. imports: [
  6. GraphQLFederationModule.forRoot({
  7. typePaths: ['**/*.graphql'],
  8. }),
  9. ],
  10. providers: [UsersResolvers],
  11. })
  12. export class AppModule {}

Code first

Code first federation is very similar to regular code first GraphQL. We simply add some extra decorators to the User entity.

  1. import { Directive, Field, ID, ObjectType } from '@nestjs/graphql';
  2. @ObjectType()
  3. @Directive('@key(fields: "id")')
  4. export class User {
  5. @Field((type) => ID)
  6. id: number;
  7. @Field()
  8. name: string;
  9. }

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.

  1. import { Args, Query, Resolver, ResolveReference } from '@nestjs/graphql';
  2. import { User } from './user.entity';
  3. import { UsersService } from './users.service';
  4. @Resolver((of) => User)
  5. export class UsersResolvers {
  6. constructor(private usersService: UsersService) {}
  7. @Query((returns) => User)
  8. getUser(@Args('id') id: number): User {
  9. return this.usersService.findById(id);
  10. }
  11. @ResolveReference()
  12. resolveReference(reference: { __typename: string; id: number }): User {
  13. return this.usersService.findById(reference.id);
  14. }
  15. }

Finally, we hook everything up in a module together with a GraphQLFederationModule. This module accepts the same options as the regular GraphQLModule.

  1. import { Module } from '@nestjs/common';
  2. import { GraphQLFederationModule } from '@nestjs/graphql';
  3. import { UsersResolvers } from './users.resolvers';
  4. import { UsersService } from './users.service'; // Not included in this example
  5. @Module({
  6. imports: [
  7. GraphQLFederationModule.forRoot({
  8. autoSchemaFile: true,
  9. }),
  10. ],
  11. providers: [UsersResolvers, UsersService],
  12. })
  13. export class AppModule {}

Federated example: Posts

Our Post service serves aggregated posts via a getPosts query, but also extends our User type with user.posts

Schema first

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.

  1. type Post @key(fields: "id") {
  2. id: ID!
  3. title: String!
  4. body: String!
  5. user: User
  6. }
  7. extend type User @key(fields: "id") {
  8. id: ID! @external
  9. posts: [Post]
  10. }
  11. extend type Query {
  12. getPosts: [Post]
  13. }

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.

  1. import { Query, Resolver, Parent, ResolveField } from '@nestjs/graphql';
  2. import { PostsService } from './posts.service';
  3. import { Post } from './posts.interfaces';
  4. @Resolver('Post')
  5. export class PostsResolvers {
  6. constructor(private postsService: PostsService) {}
  7. @Query('getPosts')
  8. getPosts() {
  9. return this.postsService.findAll();
  10. }
  11. @ResolveField('user')
  12. getUser(@Parent() post: Post) {
  13. return { __typename: 'User', id: post.userId };
  14. }
  15. }

The Posts service has virtually the same module, but is included below for the sake of completeness:

  1. import { Module } from '@nestjs/common';
  2. import { GraphQLFederationModule } from '@nestjs/graphql';
  3. import { PostsResolvers } from './posts.resolvers';
  4. @Module({
  5. imports: [
  6. GraphQLFederationModule.forRoot({
  7. typePaths: ['**/*.graphql'],
  8. }),
  9. ],
  10. providers: [PostsResolvers],
  11. })
  12. export class AppModule {}

Code first

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.

  1. import { Directive, ObjectType, Field, ID } from '@nestjs/graphql';
  2. import { Post } from './post.entity';
  3. @ObjectType()
  4. @Directive('@extends')
  5. @Directive('@key(fields: "id")')
  6. export class User {
  7. @Field((type) => ID)
  8. @Directive('@external')
  9. id: number;
  10. @Field((type) => [Post])
  11. posts?: Post[];
  12. }

We create the resolver for our extension on the User entity as follows:

  1. import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
  2. import { PostsService } from './posts.service';
  3. import { Post } from './post.entity';
  4. import { User } from './user.entity';
  5. @Resolver((of) => User)
  6. export class UsersResolvers {
  7. constructor(private readonly postsService: PostsService) {}
  8. @ResolveField((of) => [Post])
  9. public posts(@Parent() user: User): Post[] {
  10. return this.postsService.forAuthor(user.id);
  11. }
  12. }

We also need to create our Post entity:

  1. import { Directive, Field, ID, Int, ObjectType } from '@nestjs/graphql';
  2. import { User } from './user.entity';
  3. @ObjectType()
  4. @Directive('@key(fields: "id")')
  5. export class Post {
  6. @Field((type) => ID)
  7. id: number;
  8. @Field()
  9. title: string;
  10. @Field((type) => Int)
  11. authorId: number;
  12. @Field((type) => User)
  13. user?: User;
  14. }

And its resolver:

  1. import { Query, Args, ResolveField, Resolver, Parent } from '@nestjs/graphql';
  2. import { PostsService } from './posts.service';
  3. import { Post } from './post.entity';
  4. import { User } from './user.entity';
  5. @Resolver((of) => Post)
  6. export class PostsResolvers {
  7. constructor(private readonly postsService: PostsService) {}
  8. @Query((returns) => Post)
  9. findPost(@Args('id') id: number): Post {
  10. return this.postsService.findOne(id);
  11. }
  12. @Query((returns) => [Post])
  13. getPosts(): Post[] {
  14. return this.postsService.all();
  15. }
  16. @ResolveField((of) => User)
  17. user(@Parent() post: Post): any {
  18. return { __typename: 'User', id: post.authorId };
  19. }
  20. }

And finally, tie it together in a module. Note the schema build options, where we specify that User is an outside type.

  1. import { Module } from '@nestjs/common';
  2. import { GraphQLFederationModule } from '@nestjs/graphql';
  3. import { User } from './user.entity';
  4. import { PostsResolvers } from './posts.resolvers';
  5. import { UsersResolvers } from './users.resolvers';
  6. import { PostsService } from './posts.service'; // Not included in example
  7. @Module({
  8. imports: [
  9. GraphQLFederationModule.forRoot({
  10. autoSchemaFile: true,
  11. buildSchemaOptions: {
  12. orphanedTypes: [User],
  13. },
  14. }),
  15. ],
  16. providers: [PostsResolvers, UsersResolvers, PostsService],
  17. })
  18. export class AppModule {}

Federated example: Gateway

First, install the optional dependency for the gateway:

  1. $ npm install --save @apollo/gateway

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:

  1. import { Module } from '@nestjs/common';
  2. import { GraphQLGatewayModule } from '@nestjs/graphql';
  3. @Module({
  4. imports: [
  5. GraphQLGatewayModule.forRoot({
  6. server: {
  7. // ... Apollo server options
  8. cors: true,
  9. },
  10. gateway: {
  11. serviceList: [
  12. { name: 'users', url: 'http://user-service/graphql' },
  13. { name: 'posts', url: 'http://post-service/graphql' },
  14. ],
  15. },
  16. }),
  17. ],
  18. })
  19. export class AppModule {}

info Hint Apollo recommends that you don’t rely on the service discovery in a production environment but use their Graph Manager instead.

Sharing context

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.

  1. import { Module } from '@nestjs/common';
  2. import { GATEWAY_BUILD_SERVICE, GraphQLGatewayModule } from '@nestjs/graphql';
  3. import { RemoteGraphQLDataSource } from '@apollo/gateway';
  4. import { decode } from 'jsonwebtoken';
  5. class AuthenticatedDataSource extends RemoteGraphQLDataSource {
  6. async willSendRequest({ request, context }) {
  7. const { userId } = await decode(context.jwt);
  8. request.http.headers.set('x-user-id', userId);
  9. }
  10. }
  11. @Module({
  12. providers: [
  13. {
  14. provide: AuthenticatedDataSource,
  15. useValue: AuthenticatedDataSource,
  16. },
  17. {
  18. provide: GATEWAY_BUILD_SERVICE,
  19. useFactory: (AuthenticatedDataSource) => {
  20. return ({ name, url }) => new AuthenticatedDataSource({ url });
  21. },
  22. inject: [AuthenticatedDataSource],
  23. },
  24. ],
  25. exports: [GATEWAY_BUILD_SERVICE],
  26. })
  27. class BuildServiceModule {}
  28. @Module({
  29. imports: [
  30. GraphQLGatewayModule.forRootAsync({
  31. useFactory: async () => ({
  32. gateway: {
  33. serviceList: [
  34. /* services */
  35. ],
  36. },
  37. server: {
  38. context: ({ req }) => ({
  39. jwt: req.headers.authorization,
  40. }),
  41. },
  42. }),
  43. imports: [BuildServiceModule],
  44. inject: [GATEWAY_BUILD_SERVICE],
  45. }),
  46. ],
  47. })
  48. export class AppModule {}

Async configuration

Both the Federation and Gateway modules support asynchronous initialization using the same forRootAsync that’s documented in Quick start.