GraphQL has become a popular choice for building APIs due to its flexibility and efficiency in data fetching. But as projects grow in size and complexity, managing a monolithic GraphQL schema can quickly become overwhelming. Adopting a microservices architecture helps decentralize and handle complexity through modularization. However, ensuring efficient communication and coordination between services remains challenging. This is where federation comes into play.
Federation allows you to divide your schema into smaller, interconnected services, making it easier to develop, deploy, and scale your GraphQL architecture.
In this article, you will learn about three popular federation approaches: GraphQL Mesh, Apollo Federation, and Content Federation. You will learn their core concepts, benefits, and code implementations. By the end of this read, you'll have a crystal-clear understanding of each approach to select the perfect federation strategy for your project's success.
#What is GraphQL Mesh?
The GraphQL Mesh framework is used to shape and build an executable GraphQL schema from multiple data sources. In combination with Hive Gateway iIt allows you to use GraphQL query language to access data in remote APIs that don't run GraphQL (and those that run GraphQL).
The key benefit of using GraphQL Mesh is the ability to aggregate data from multiple sources seamlessly. Whether you need to merge data from OpenAPI/Swagger, gRPC, REST APIs, databases, or other GraphQL services, GraphQL Mesh allows you to create a cohesive schema without tightly coupling your services. This modularity enhances maintainability and enables you to introduce new data sources effortlessly.
GraphQL Mesh also provides flexibility and customization options. You can modify and extend the merged schema using resolvers, transformations, and directives. This allows you to tailor the schema to your needs, implement business logic, and transform data as it flows through the federation.
Implementation of GraphQL Mesh
To get started with GraphQL Mesh, you'll need to set up a project and then install the necessary dependencies (including Hive Gateway to serve data):
npm i graphql @graphql-hive/gateway @graphql-mesh/compose-cli @omnigraph/openapi
In the project root directory, create a file named mesh.config.ts, which will serve as the configuration file for GraphQL Mesh. Open the file in your text editor and define the data sources you want to federate.
Here's an example of the mesh.config.ts configuration file that includes a REST API and a GraphQL endpoint:
import {defineConfig,loadGraphQLHTTPSubgraph,} from "@graphql-mesh/compose-cli";import { loadOpenAPISubgraph } from "@omnigraph/openapi";export const composeConfig = defineConfig({subgraphs: [{sourceHandler: loadOpenAPISubgraph("my-rest-api", {source: "https://api.example.com/rest/swagger.json",}),},{sourceHandler: loadGraphQLHTTPSubgraph("my-graphql-api", {endpoint: "https://api.example.com/graphql",}),},],});
You can then add a run script to your package.json file:
"scripts": {"dev": "mesh-compose > supergraph.graphql && hive-gateway supergraph"
When you run npm run dev
, GraphQL Mesh will compose a supergraph and start Hive Gateway, where you can query all federated APIs. You can also leverage various GraphQL Mesh and Hive Gateway plugins to add custom resolvers, transformations, and other features to your schema. Both GraphQL Mesh and Hive Gateway provide full support for Apollo Federation, allowing you to work with federated schemas while leveraging their respective features.
#What is Apollo Federation?
Apollo Federation is a framework that enables you to compose a federated schema by combining independent, self-contained GraphQL services (subgraphs). It follows a decentralized architecture, where each service has its schema and can be developed and deployed independently.
In a federated architecture, your individual GraphQL APIs are called subgraphs, and they're composed into a supergraph. Clients can fetch data from all your subgraphs with a single request by querying your supergraph's router.
One major advantage of Apollo Federation is that you can develop and scale services independently. This decentralized approach fosters team autonomy and accelerates development cycles. Each service can focus on its specific domain, and changes can be made without impacting other services.
Implementation of Apollo Federation
To demonstrate how Apollo Federation works, let's consider an example where you have two services: products and reviews. The products service provides information about products, and the reviews service manages customer reviews for those products. You'll create a federated graph that combines these services.
First, set up the product's service. Create a new file called products.js and add the following code:
const { ApolloServer, gql } = require('apollo-server');const { buildSubgraphSchema } = require('@apollo/subgraph');const typeDefs = gql`type Product @key(fields: "id") {id: ID!name: String!}extend type Query {products: [Product]}`;const products = [{ id: '1', name: 'Product 1' },{ id: '2', name: 'Product 2' },];const resolvers = {Query: {products: () => products,},};const server = new ApolloServer({schema: buildSubgraphSchema([{ typeDefs, resolvers }]),});server.listen(4001).then(({ url }) => {console.log(`Products service running at ${url}`);});
This code defines a GraphQL type Product
with an id
and name
field. You also extend the Query
type to include a products
field that returns an array of Product
objects.
Next, set up the reviews service. Create a new file called reviews.js and add the following code:
const { ApolloServer, gql } = require('apollo-server');const { buildSubgraphSchema } = require('@apollo/subgraph');const typeDefs = gql`type Review @key(fields: "id") {id: ID!productId: ID!rating: Int!comment: String!}extend type Product @key(fields: "id") {id: ID! @externalreviews: [Review]}extend type Query {reviews: [Review]}`;const reviews = [{ id: '1', productId: '1', rating: 5, comment: 'Great product!' },{ id: '2', productId: '2', rating: 4, comment: 'Nice product.' },];const resolvers = {Product: {reviews: (parent) =>reviews.filter((review) => review.productId === parent.id),},Query: {reviews: () => reviews,},};const server = new ApolloServer({schema: buildSubgraphSchema([{ typeDefs, resolvers }]),});server.listen(4002).then(({ url }) => {console.log(`Reviews service running at ${url}`);});
This code defines a GraphQL type Review
with fields id
, productId
, rating
, and comment
. You also extend the Product
type to include a reviews
field, representing the reviews associated with a particular product. The @external
directive indicates that the id
field is defined in another service. You also extend the Query
type to include a reviews
field that returns all reviews.
You need to create a gateway combining these services into a federated graph. Create an index.js file and add the following code:
const { ApolloServer } = require('apollo-server');const { ApolloGateway, IntrospectAndCompose } = require('@apollo/gateway');const gateway = new ApolloGateway({supergraphSdl: new IntrospectAndCompose({subgraphs: [{ name: 'products', url: 'http://localhost:4001' },{ name: 'reviews', url: 'http://localhost:4002' },],}),});const server = new ApolloServer({gateway,});server.listen(4000).then(({ url }) => {console.log(`Server ready at ${url}`);});
This code sets up an Apollo gateway using the ApolloGateway
class from the @apollo/gateway
package. We define the subgraphs
and supergraphSdl
. Each service entry includes a name
and a url
indicating the location of the respective service.
To run the example, you add commands for each subgraph and the gateway in your package.json file:
"scripts": {"server:products": "nodemon products.js","server:reviews": "nodemon reviews.js","server:graphql": "nodemon index.js"},
When you run npm run server
, the Apollo sandbox will open for you to test the federated GraphQL schemas.
#What is Content Federation?
Content Federation is the ability to bring data together from multiple sources and backends via API into a centralized data structure or API without migrating the data or having multiple versions of it. This allows for a single view (centralized) of the data.
Content Federation is especially useful when you have multiple data sources and want to merge them and allow content editors to utilize and enrich data and content without developer involvement. It allows you to aggregate content from diverse systems, apply transformations, and enrich it with additional data. This approach enables you to create powerful and tailored content APIs that client applications can easily consume.
One major player in the world of content federation is Hygraph — a federated content management platform.
Implementation of Content Federation with Hygraph
Hygraph is a federated content management platform that enables teams to provide content to any channel. If this is your first time exploring Hygraph, create a free-forever developer account via either GitHub or Mail.
Here are the steps you will follow to implement federation with Hygraph:
Define the federated schema: To define the Federated Schema with Hygraph, you must create multiple smaller schemas for each service.
Configure the services: Configure each service with its own schema, data types, and resolvers. With Hygraph, you can create custom content types, fields, and relationships for each service.
Create a gateway: Create a Gateway to route queries to the appropriate services and aggregate the results into a single response. Hygraph provides a built-in Gateway that you can use to route queries to your services.
Once you have done this, you can send queries to your Gateway and receive responses. For this article, let’s combine the Cocktail API (an external API) into an Hygraph project and query for data with a single GraphQL query.
Step 1: Add a remote source
The first step is to add a remote source, specify the type of the API, name and paste the API address:
Step 2: Create a GraphQL remote field
Create a field for the data you will use to query for a particular cocktail. For this, I will create two fields, the "Best cocktail" field for you to submit the best cocktail of the author, and a slug field (Cocktail Slug) that will automatically convert the "Best cocktail" data to slug.
You can now create the GraphQL remote field to query for a particular cocktail with the slug value.
Step 3: Test the remote source
You have created a GraphQL remote field for the cocktail Info. Test it by adding the author's best cocktail, which would generate a slug value, and then you can use it to get the particular cocktail information.
At this point, you have successfully added and combined multiple remote sources into your Hygraph project. Create a GraphQL query to fetch the author's data, including the author's best cocktail, ingredients, and instructions for making it.
query AuthorsInfo {authors {firstNamelastNamebiobestCocktailcocktailInfo {infoingredientsinstructions}}}
This will return all the various values, including the ones from the remote sources, directly into this GraphQL query:
{"data": {"authors": [{"firstName": "John ","lastName": "Doe","bio": null,"bestCocktail": "paloma","cocktailInfo": {"info": "Alcoholic","ingredients": "Grape Soda Tequila","instructions": "Stir Together And Serve Over Ice."}}]}}
You can explore more by reading the remote sources documentation and this article on How to run multiple GraphQL queries and combine multiple sources.
#GraphQL Mesh vs. Apollo Federation vs. Content Federation: comparison and considerations
After exploring GraphQL Mesh, Apollo Federation, and Content Federation, it's important to compare their differences and consider the factors that impact your project.
Factors | GraphQL Mesh | Apollo Federation | Content Federation |
---|---|---|---|
Architecture | Combines multiple schemas into a federated schema | Composes independent services into a federated schema | Composes independent services into a federated schema accessible to developers and editors |
Data Sources | Supports various data sources and APIs | Supports GraphQL APIs | Supports various data sources and APIs |
Flexibility | Allows customization using resolvers, transformations, and plugins | Offers flexibility in service development and deployment | Offers flexibility in remote sources development and deployment |
Independence | Can operate without the need for a centralized gateway | Services can be developed and deployed independently | Remote sources can be developed and deployed independently |
Gateway | Not required | Requires a centralized gateway | Hygraph is the gateway |
Scalability | Can handle scalability and performance considerations | Provides scalability through independent services | Provides scalability through independent sources |
Learning Curve | Moderate | Moderate to high | Moderate |
#Conclusion
Choosing the right federation approach for your GraphQL architecture significantly impacts your system's scalability, flexibility, and maintainability. In this article, we explored GraphQL Mesh, Apollo Federation, and Content Federation, three popular federation approaches, and discussed their core concepts, benefits, and code implementations.
Before choosing the best approach for your project, consider the specific requirements and constraints, along with factors like data sources, scalability, and extensibility; then, you’ll be able to make a perfect decision.
By leveraging the power of federation, you can build robust and scalable GraphQL architectures that meet the evolving needs of your application.
The GraphQL Report 2024
Statistics and best practices from prominent GraphQL users.
Check out the report