I’ve been thinking about how modern applications need to scale without becoming monolithic nightmares. Recently, I faced this challenge when our e-commerce platform started straining under rapid growth. That’s when GraphQL Federation caught my attention - a way to split our API while keeping it unified for clients. Let me share what I’ve learned about building a high-performance federated gateway.
Getting started requires a solid foundation. We begin by setting up our workspace with a clear structure. Using TypeScript ensures type safety across our services. Here’s how I organize my projects:
# Create project structure
mkdir -p gateway users products reviews shared
# Initialize each service
for service in gateway users products reviews; do
cd $service && npm init -y && npm install @apollo/server graphql typescript
done
# Install gateway dependencies
cd gateway && npm install @apollo/gateway
For the Users service, we define entities that can be extended by other services. Notice how we use Apollo’s federation directives:
// users-service/src/schema.ts
import gql from 'graphql-tag';
export const typeDefs = gql`
extend schema @link(url: "https://specs.apollo.dev/federation/v2.3",
import: ["@key", "@shareable"])
type User @key(fields: "id") {
id: ID!
email: String!
username: String!
}
type Query {
getUser(id: ID!): User
}
`;
The Products service demonstrates how to extend types from other services. Ever wondered how services reference each other’s data?
// products-service/src/schema.ts
import gql from 'graphql-tag';
export const typeDefs = gql`
extend schema @link(url: "https://specs.apollo.dev/federation/v2.3",
import: ["@key", "@extends", "@external"])
type Product @key(fields: "id") {
id: ID!
name: String!
owner: User!
}
extend type User @key(fields: "id") {
id: ID! @external
products: [Product]
}
`;
The gateway acts as the unified entry point. Here’s how I configure it to compose our schemas:
// gateway/src/index.ts
import { ApolloGateway } from '@apollo/gateway';
import { ApolloServer } from '@apollo/server';
const gateway = new ApolloGateway({
serviceList: [
{ name: 'users', url: 'http://localhost:4001/graphql' },
{ name: 'products', url: 'http://localhost:4002/graphql' }
]
});
const server = new ApolloServer({ gateway });
server.listen().then(({ url }) => {
console.log(`Gateway ready at ${url}`);
});
Resolving relationships across services requires reference resolvers. In the Products service, we resolve user relationships like this:
// products-service/src/resolvers.ts
const resolvers = {
User: {
products: (user) => {
return getProductsByOwner(user.id);
}
},
Product: {
owner: (product) => {
return { __typename: "User", id: product.ownerId };
}
}
};
For authentication, I pass JWT tokens through context to all services. How do we ensure consistent auth without coupling services?
// gateway/src/context.ts
const gateway = new ApolloGateway({
// ...serviceList,
buildService({ url }) {
return new RemoteGraphQLDataSource({
url,
willSendRequest({ request, context }) {
request.http.headers.set(
'authorization',
context.authToken
);
}
});
}
});
Performance optimization is crucial. We implement Redis caching at the gateway level:
// gateway/src/cache.ts
import { RedisCache } from 'apollo-server-cache-redis';
const server = new ApolloServer({
gateway,
cache: new RedisCache({
host: 'redis-server',
port: 6379
}),
persistedQueries: {
cache: new RedisCache()
}
});
Error handling requires a unified approach. I create custom error classes that propagate across services:
// shared/src/errors.ts
export class FederationError extends Error {
extensions: Record<string, any>;
constructor(message: string, code: string) {
super(message);
this.extensions = { code, service: 'gateway' };
}
}
For deployment, Docker containers and Kubernetes work well. Here’s a sample Dockerfile for our gateway:
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
EXPOSE 4000
CMD ["npm", "start"]
Monitoring federated services requires distributed tracing. I integrate Apollo Studio with this configuration:
// gateway/src/monitoring.ts
import { ApolloServerPluginUsageReporting } from '@apollo/server/plugin/usageReporting';
const server = new ApolloServer({
gateway,
plugins: [
ApolloServerPluginUsageReporting({
endpointUrl: 'https://metrics.apollographql.com/api/ingress',
sendVariableValues: { all: true }
})
]
});
Throughout this process, I’ve found that federation shines when services need autonomy but clients demand simplicity. The real magic happens when changes to one service don’t require redeploying everything. What challenges might you face when transitioning from a monolith?
Remember to test your query plans before deployment. The gateway’s query planner handles complex requests across services, but you should verify performance under load. I simulate production traffic using Artillery.io to spot bottlenecks.
If you found this useful, share it with your team! Have questions about specific implementation details? Leave a comment below - I’ll respond to every query. Your experiences with federated architectures could help others too.