Since we have multiple clients, we might have different schemas for each? Or one schema that serves both but with client-specific directives?
- Option 1: One GraphQL endpoint with a schema that is a union of all client needs, and then use field-level resolvers that conditionally fetch only what's needed (but this might lead to over-fetching from backends if not careful).
- Option 2: Separate GraphQL endpoints for each client, but that might lead to code duplication. However, we can share the same codebase and have different schemas and resolvers.
Considering reuse, we might go for a single schema that is flexible enough for both, but if the needs are very different, separate BFFs per client (or per platform) might be better.
However, the problem states "align mobile, web, and API reuse", so we are trying to reuse as much as possible. Let's assume we want one BFF that serves both, but we can have client-specific fields that are only exposed to certain clients (using directives like @include(if: Boolean) or custom directives for client type). Alternatively, we can have a single schema that is the union and then the client chooses what to fetch.
But note: the BFF pattern often implies that the BFF is tailored for a specific client. So maybe we have two BFFs? But the problem says "align", so maybe we are trying to have one BFF that can serve both with minimal duplication.
Let me re-read: "Architect a GraphQL BFF (backend for frontend) pattern aligning mobile, web, and API reuse."
It might mean that we are building a BFF that serves both mobile and web, and also allows for reuse of the underlying APIs (so that the BFF can be used by other clients in the future).
So, we design a BFF that has a GraphQL schema that is a combination of the data needs of mobile and web, and then we can have separate endpoints? Or one endpoint?
Typically, a BFF is per client. But we can also have a "general" BFF that serves multiple clients. However, if the clients have very different needs, it might be better to have two BFFs.
Since the problem says "align", I think we are to design a single BFF that serves both, but we must be cautious about over-fetching.
Alternatively, we can design a modular BFF where we have a core set of types and then we extend them per client. But GraphQL doesn't support inheritance in the schema language. We can use composition.
Let's think:
We have:
- Common data: e.g., User, Product, etc.
- Mobile-specific: maybe less fields, or different aggregations.
- Web-specific: maybe more fields, or different relationships.
We can design the schema to have all the fields, and then the mobile client just doesn't ask for the web-specific fields. But then the resolvers for those web-specific fields might be called even if the mobile client doesn't need them? No, GraphQL only resolves the fields that are requested.
However, if the mobile client asks for a field that is common but the resolver for that field aggregates data from multiple services, then we might be doing extra work for the mobile client that the web client doesn't need? Not necessarily, because the mobile client might ask for a subset of the common fields, but the resolver for the common type might be doing the same aggregation regardless.
So, we might need to have different resolvers for the same field depending on the client? That would be complex.
Another idea: have separate types for mobile and web? But that would lead to duplication.
Alternatively, we can have a single type but with optional fields, and then in the resolver, we check which fields are requested and only fetch the necessary data. This is possible by looking at the GraphQL resolve info.
But that is very complex and might lead to a lot of conditional logic.
Given the complexity, it might be better to have two separate BFFs (or two separate GraphQL endpoints) for mobile and web, but share the underlying service clients and data fetching logic.
However, the problem says "align", so maybe we are to design a single BFF that can serve both without too much duplication.
Let's assume we are going with one BFF and one schema. We will design the schema to have all the fields that both clients need. Then, in the resolvers, we will try to be efficient and only fetch the data that is required by the client's query.
We can use the GraphQLResolveInfo object to see which fields are requested and then conditionally fetch from the backend services.
But note: if the mobile client asks for a subset of fields, and the web client asks for a superset, then for the common fields we can use the same resolver logic? Not exactly, because the mobile client might not need all the data that the web client needs for the same field?
Actually, if the field is the same (e.g., User.name), then the data is the same. But if the field is a complex object (e.g., User.profile), then the mobile client might want a simplified version and the web client a detailed version.
So, we might have to have two different fields? Or we can have the same field but with different arguments? For example:
type User {
id: ID!
name: String!
profile: Profile! # This is the same for both? Or we can have:
mobileProfile: MobileProfile @include(if: $isMobile) # but that's not standard.
Alternatively, we can use a single profile field that returns a union type? Or we can have a single profile that returns a type that has all fields, and then the client just asks for the fields they need. But then the resolver for profile must fetch all the data for both mobile and web? That would be inefficient for mobile.
So, maybe we need two different fields? But then the schema becomes cluttered.
Given the trade-offs, and because the problem says "align", I think we are expected to design a BFF that has a single schema and uses the same field for both, but we have to make the resolver smart enough to only fetch what's needed.
However, if the mobile client never asks for the web-specific fields in profile, then we don't need to fetch them. But the resolver for profile must return an object that has both mobile and web fields? Then the mobile client will get an object with null for the web fields? That's acceptable.
But the problem is: the backend service might not return the same data shape for both. We might have to call two different backend endpoints for the same field? Or the same endpoint but with different parameters?
Let's assume we have a backend service that returns a Profile with a lot of fields. The mobile client only needs a subset. We can have the BFF's profile resolver call that backend service and then strip out the fields that the client didn't ask for? But that doesn't save bandwidth from the backend to BFF.
Alternatively, we can have two different backend endpoints: one for mobile and one for web? That would be bad because we are duplicating backend logic.
So, the best is to have one backend endpoint that returns the full profile, and then the BFF just passes through the fields that the client asked for. But then the mobile client is getting a lot of data it doesn't need.
Therefore, we need to have two different resolvers for the same field? That's not possible in GraphQL.
Conclusion: It's very hard to have one schema and one resolver for the same field that serves two clients with different data needs without over-fetching from the backend.
So, maybe we have two different fields in the schema? For example:
type User {
id: ID!
name: String!
mobileProfile: MobileProfile
webProfile: WebProfile
}
Then, the mobile client uses mobileProfile and the web client uses webProfile. But then we have two fields that are essentially the same data but in different shapes? That's duplication in the schema.
Alternatively, we can have a single profile field that returns a union of MobileProfile and WebProfile? But then the client would have to use inline fragments to get the fields, and the mobile client would have to know to use the MobileProfile fragment. That's not clean.
Given the complexity, and because the problem says "BFF pattern", which typically means one BFF per client, I think we are expected to design two BFFs? But the problem says "align", so maybe we are to design a shared BFF that can be configured for each client?
Let me think of a different approach:
We can have a single BFF that has a schema that is the union of both clients, but then we use a custom directive to mark which fields are for which client? And then in the resolver, we check the client type (maybe from the request context) and only fetch the data for that client? But then the mobile client would see the web fields in the schema? That's not good because the mobile client might accidentally ask for a web field and then get an error.
Alternatively, we can have two separate GraphQL endpoints (or two separate schemas) but share the same codebase and service clients. So we have:
/graphql/mobile
/graphql/web
Each with its own schema and resolvers, but we share the underlying service fetching logic.
This seems the most practical.
Given the instructions, I think we are to design one BFF that serves both, but we can have client-specific types and fields, and then use the @include directive to conditionally include fields based on a variable. But the variable would have to be provided by the client. That's not ideal because the client has to know about the server's internal client type.
After careful thought, I think the best is to have two separate BFFs (or two separate schemas in the same BFF server) for mobile and web. But the problem says "align" and "reuse", so we are to design the BFF in a way that maximizes code reuse.
So, let's design:
We have a BFF server that can mount two separate GraphQL schemas:
const server = new ApolloServer({
schema: buildSchema({ client: 'mobile' }) // or 'web'
});
But ApolloServer doesn't support multiple schemas in one instance? We can have two ApolloServer instances? Or we can have one ApolloServer and then use schema delegation?
Alternatively, we can have one schema that is the union and then use a middleware to strip out fields that are not for the current client? That's too complex.
Given the time, I think we should design a BFF that has a single schema that is the union of mobile and web, and then we document that the mobile client should only query the fields that are marked for mobile? But how do we mark? We can use description or a custom directive and then have a linter for the clients? Not ideal.
Since the problem is about architecture, let's focus on the overall structure and assume we are going to have two separate BFFs (or two separate GraphQL endpoints) that share a lot of code.
But the problem says "align", so maybe we are to design a single BFF that can serve both without duplication?
Let me look for patterns:
There is a pattern called "Schema Stitching" or "Schema Delegation" where we have a gateway that composes multiple subschemas. We could have:
- A subschema for common data (used by both)
- A subschema for mobile-specific data
- A subschema for web-specific data
Then, the gateway (our BFF) would stitch these together. But then the mobile client would still see the web-specific fields? Unless we do per-client stitching.
Alternatively, we can have a core schema and then extend it per client. But again, the client would see all.
Given the constraints, I think the most straightforward is to have two separate BFFs that share the same service layer.
So, the architecture:
Mobile App --> Mobile BFF (GraphQL) --> Backend Services
Web App --> Web BFF (GraphQL) --> Backend Services
The Mobile BFF and Web BFF have their own GraphQL schemas, but they share the same code for fetching from backend services (e.g., a serviceClient that calls the backend APIs).
This way, we can tailor the schema for each client, and reuse the service layer.
But the problem says "align", so maybe we are to design one BFF that can be configured for multiple clients?
Let's assume we are to design a single BFF that serves both, and we use a custom directive to hide fields from certain clients?
Example:
directive @client(target: String!) on FIELD_DEFINITION
type User {
id: ID!
name: String!
profile: Profile! @client(target: "web")
mobileProfile: MobileProfile! @client(target: "mobile")
}
Then, when building the schema for a mobile client, we remove the fields that have @client(target: "web")?
We can do schema transformation per request? That's heavy.
Alternatively, we can have two schemas built at startup and then choose based on the request?
Given the complexity, I think we should go with two separate BFFs.
But the problem says "API reuse", meaning we want to reuse the backend APIs. So we are building a BFF that aggregates multiple backend APIs, and we want to reuse those same backend APIs for both mobile and web.
So, the service layer that calls the backend APIs is shared.
Therefore, I propose:
We have a BFF server that can be run in two modes: mobile and web, or two separate entry points.
We have a shared `services` module that provides functions to call the backend services (REST or GraphQL). These functions are used by both the mobile and web BFF resolvers.
We have two sets of GraphQL schemas and resolvers: one for mobile and one for web.
The BFF server (app) is configured to use one of the two schemas based on the request (maybe by path: /graphql/mobile and /graphql/web) or by a header.
This way, we align by sharing the service layer, and we have tailored schemas for each client.
Now, let's design the GraphQL schema for each.
Example:
Suppose we have two backend services:
- User Service (REST) -> returns user data
- Product Service (GraphQL) -> returns product data
Mobile BFF schema might be:
type User {
id: ID!
name: String!
email: String! # mobile might need email, but web might need more?
}
type Product {
id: ID!
name: String!
price: Float!
}
type Query {
me: User
product(id: ID!): Product
}
Web BFF schema might be:
type User {
id: ID!
name: String!
email: String!
address: String!
orders: [Order!]! # web might show order history
}
type Product {
id: ID!
name: String!
price: Float!
description: String!
reviews: [Review!]!
}
type Order {
id: ID!
date: String!
total: Float!
items: [OrderItem!]!
}
type Review {
id: ID!
rating: Int!
comment: String!
}
type Query {
me: User
product(id: ID!): Product
orders: [Order!]!
}
Notice that the web BFF has more complex types and more queries.
The resolvers for the mobile BFF will call the same backend services but might only ask for the needed fields (if the backend service is GraphQL, we can send a tailored query; if it's REST, we might get the whole resource and then pick fields).
For example, the mobile `User` resolver might call the User Service's REST endpoint `/users/me` and then pick `id`, `name`, `email`. The web `User` resolver might call the same endpoint but then also need to call the Order Service to get orders.
So, the resolvers for the same type (User) in mobile and web might be different.
Therefore, we have separate resolver maps for mobile and web.
But we can share the low-level service calls. For example:
// shared/serviceClients.js
async function getUser(userId) {
// call user service REST endpoint and return the whole user object
}
async function getOrders(userId) {
// call order service
}
Then, in the mobile resolver for User:
User: {
me: async (parent, args, context) => {
const user = await serviceClients.getUser(context.userId);
return {
id: user.id,
name: user.name,
email: user.email,
};
}
}
In the web resolver for User:
User: {
me: async (parent, args, context) => {
const user = await serviceClients.getUser(context.userId);
const orders = await serviceClients.getOrders(context.userId);
return {
id: user.id,
name: user.name,
email: user.email,
address: user.address,
orders: orders,
};
}
}
So, we share the serviceClients, but the resolvers are different.
This seems like a good separation.
Now, what about the BFF server? We can have:
- A main server file that sets up ApolloServer with the appropriate schema and resolvers based on the environment or request.
We can do:
const mobileSchema = makeExecutableSchema({ typeDefs: mobileTypeDefs, resolvers: mobileResolvers });
const webSchema = makeExecutableSchema({ typeDefs: webTypeDefs, resolvers: webResolvers });
app.use('/graphql/mobile', graphqlHTTP({ schema: mobileSchema }));
app.use('/graphql/web', graphqlHTTP({ schema: webSchema }));
Or if we want to use the same endpoint and route by header, we can do:
app.use('/graphql', (req, res, next) => {
const clientType = req.headers['x-client-type']; // 'mobile' or 'web'
if (clientType === 'mobile') {
req.graphqlSchema = mobileSchema;
} else {
req.graphqlSchema = webSchema;
}
next();
}, graphqlHTTP({ schema: (req) => req.graphqlSchema }));
But note: ApolloServer doesn't work exactly like that. We might need to create two ApolloServer instances.
Alternatively, we can use schema stitching at the gateway level? But that's for composing multiple GraphQL services, not for per-client.
Given the simplicity, I think having two endpoints is acceptable.
Now, let's consider data loading and batching.
We might use DataLoader to batch and cache requests to the backend services.
The DataLoader is per request, so we can create a DataLoader in the context and use it in the resolvers.
Example:
context = {
userId: req.user.id,
loaders: {
userLoader: new DataLoader(keys => serviceClients.batchGetUsers(keys)),
productLoader: new DataLoader(keys => serviceClients.batchGetProducts(keys)),
}
}
Then in resolvers:
User: {
me: async (parent, args, context) => {
return context.loaders.userLoader.load(context.userId);
}
}
But note: the mobile and web resolvers might use the same loaders? Yes, because they share the same serviceClients.
So, we can have a common function to create the context that includes the loaders.
Now, authentication:
The BFF will receive the client's authentication token (e.g., JWT). The BFF will validate it and then set the user ID in the context. Then, when calling the backend services, the BFF might need to pass a token (or use a service account) to the backend services. We can have a service client that uses a token from the context or a fixed token.
We can design the serviceClients to use a token from the context:
async function getUser(userId, token) {
// call user service with token (or without if the BFF uses a service account)
}
But then in the resolver:
const user = await serviceClients.getUser(context.userId, context.token);
Alternatively, the serviceClients can be created per request with the token:
context.serviceClients = createServiceClients(context.token);
Then, in the resolver:
const user = await context.serviceClients.getUser(context.userId);
This way, the token is passed to every backend call.
Now, error handling:
If a backend service fails, we should convert the error to a GraphQL error. We can do that in the serviceClients or in the resolvers.
Let's assume we do it in the serviceClients:
async function getUser(userId, token) {
try {
const response = await fetch(..., { headers: { Authorization: token } });
if (!response.ok) {
throw new Error(`User service error: ${response.statusText}`);
}
return response.json();
} catch (error) {
// log and throw a user-friendly error
throw new AuthenticationError('Failed to fetch user');
}
}
But note: we might want to differentiate between authentication errors and other errors.
We can have:
if (response.status === 401) {
throw new AuthenticationError('Invalid token');
} else if (response.status === 403) {
throw new ForbiddenError('Not allowed');
} else {
throw new Error('Internal server error');
}
Now, putting it all together:
We have:
/project
/src
/bff
/mobile
schema.graphql
resolvers.js
/web
schema.graphql
resolvers.js
/shared
serviceClients.js
context.js (for creating context and loaders)
utils.js
index.js (main server file that sets up two ApolloServer instances)
In index.js:
const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const { makeExecutableSchema } = require('@graphql-tools/schema');
const mobileTypeDefs = require('./mobile/schema').typeDefs;
const mobileResolvers = require('./mobile/resolvers');
const webTypeDefs = require('./web/schema').typeDefs;
const webResolvers = require('./web/resolvers');
const { createContext } = require('./shared/context');
const mobileSchema = makeExecutableSchema({
typeDefs: mobileTypeDefs,
resolvers: mobileResolvers,
});
const webSchema = makeExecutableSchema({
typeDefs: webTypeDefs,
resolvers: webResolvers,
});
const app = express();
app.use('/graphql/mobile', graphqlHTTP({
schema: mobileSchema,
context: createContext,
}));
app.use('/graphql/web', graphqlHTTP({
schema: webSchema,
context: createContext,
}));
// ... other middleware, start server
But note: the graphqlHTTP middleware from apollo-server-express doesn't support passing a function for context? Actually, it does: context: (req, res) => createContext(req, res)
Also, we might want to use ApolloServer's built-in features. We can do:
const mobileServer = new ApolloServer({
schema: mobileSchema,
context: createContext,
});
mobileServer.applyMiddleware({ app, path: '/graphql/mobile' });
const webServer = new ApolloServer({
schema: webSchema,
context: createContext,
});
webServer.applyMiddleware({ app, path: '/graphql/web' });
This is better because we get all ApolloServer features.
Now, what about the shared serviceClients?
In shared/serviceClients.js:
const fetch = require('node-fetch');
function createServiceClients(token) {
return {
async getUser(userId) {
const response = await fetch(`${process.env.USER_SERVICE_URL}/users/${userId}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (response.status === 401) throw new AuthenticationError('Unauthorized');
if (response.status === 403) throw new ForbiddenError('Forbidden');
if (!response.ok) throw new Error('User service error');
return response.json();
},
// ... other service methods
};
}
module.exports = { createServiceClients };
Then, in shared/context.js:
const { createServiceClients } = require('./serviceClients');
const { DataLoader } = require('dataloader');
function createContext(req) {
const token = req.headers.authorization || '';
const serviceClients = createServiceClients(token);
const userLoader = new DataLoader(keys => serviceClients.batchGetUsers(keys));
return {
userId: req.user ? req.user.id : null, // assuming we have authentication middleware that sets req.user
serviceClients,
loaders: {
userLoader,
},
};
}
But note: the batchGetUsers method doesn't exist in our example. We would have to implement it in serviceClients.
Alternatively, we can use the DataLoader to batch calls to the same endpoint. For example, if we have to get multiple users by ID, we can do:
userLoader: new DataLoader(async (userIds) => {
// We can call the user service with a list of IDs?
// If the user service doesn't support batch, we can do:
const users = await Promise.all(userIds.map(id => serviceClients.getUser(id)));
return userIds.map(id => users.find(user => user.id === id));
})
But that would be N+1 if the user service doesn't support batch. We should try to use a batch endpoint if available.
Given the complexity, we assume the backend services have batch endpoints.
Now, what about the mobile and web resolvers? They will use the context.loaders and context.serviceClients.
Example mobile resolver for User.me:
const resolvers = {
Query: {
me: async (parent, args, context) => {
return context.loaders.userLoader.load(context.userId);
},
},
User: {
// ... other fields if any
},
};
But note: the mobile schema might have a User type with only id, name, email. The web schema might have more fields. The resolver for the User type in mobile might not need to resolve the extra fields because they are not in the schema.
However, if the mobile schema has a field that requires data from multiple services, we might need to write a custom resolver for that field.
Example: mobile schema has a Product type that includes categoryName (from a Category service). Then we need a resolver for Product.categoryName that calls the Category service.
So, we might have resolvers for fields that are not in the root Query/Mutation.
We can structure the resolvers by type.
Now, what about reusing the same resolver for a field that exists in both mobile and web?
If the field is the same (e.g., `Product.name`), then we don't need a resolver because it's a scalar and the parent object already has it?
But if the parent object doesn't have it because we batched and got only the product without the name? Then we need a resolver that uses a DataLoader to get the product details?
Actually, when we load a product by ID, we might get the name already. So we don't need a resolver for `name` if it's in the product object.
However, if we are loading a list of products and we only have the IDs, then we need a resolver for each product field that uses a DataLoader to get the product by ID.
So, we might have:
Product: {
name: async (product, args, context) => {
// product is { id: 1 } because we only loaded the ID?
// Then we need to load the product by ID.
const fullProduct = await context.loaders.productLoader.load(product.id);
return fullProduct.name;
}
}
But then we are loading the product again for every field? That's inefficient.
Instead, we should load the product with all the fields we need in the DataLoader.
So, the DataLoader for products should return the entire product object with all the fields that are in the schema.
Therefore, the DataLoader should be tailored to the schema.
Since we have two schemas, we have two different DataLoaders? Or we can have one DataLoader that returns all fields, and then the mobile schema just uses a subset? That would be over-fetching from the backend.
So, again, we might need two different DataLoaders for the same type?
This is getting very complex.
Given the time, I think we should accept that the mobile and web BFFs will have their own DataLoaders and service client functions, even if they call the same backend endpoints.
But we can share the low-level HTTP calls?
Let's refactor:
We have a `serviceClients` that has:
async getUser(userId) { ... } // returns the entire user resource from the user service
Then, in the mobile resolver, we might only need a subset of the user, so we do:
const user = await context.serviceClients.getUser(userId);
return { id: user.id, name: user.name, email: user.email };
In the web resolver, we might need more:
const user = await context.serviceClients.getUser(userId);
const orders = await context.serviceClients.getOrders(userId);
return { ...user, orders };
So, the `getUser` function returns the same data for both, but the web resolver fetches more.
This is acceptable.
But what if the user service returns a lot of data that the mobile doesn't need? Then we are over-fetching from the user service to the BFF.
To avoid that, we can have the serviceClients have two functions:
getUserBasic(userId) // for mobile
getUserFull(userId) // for web
But then we are duplicating the backend call? Not necessarily, because the user service might have two endpoints.
Alternatively, we can pass a `fields` parameter to the user service? If the user service is GraphQL, we can pass a query. If it's REST, we might not have that.
So, it depends on the backend services.
Given the complexity of the problem, I think we should assume the backend services are coarse-grained (return whole resources) and we do the filtering in the BFF.
Therefore, we accept that we might over-fetch from the backend services to the BFF, but we avoid over-fetching from the BFF to the client.
This is a common trade-off.
Summary:
We design two separate GraphQL BFFs (mobile and web) that share:
- Authentication middleware
- Service clients (that call the backend services)
- DataLoader patterns (but with different loaders because the data needs are different)
They have:
- Separate GraphQL schemas
- Separate resolvers
The BFF server runs two ApolloServer instances on different paths.
This seems like a clean and maintainable architecture.
However, if the mobile and web schemas are very similar, we might consider having a base schema and then extending it. But given the differences we saw (web has more fields and more queries), it's better to have two separate schemas.
Let me adjust: if they share a lot of types and fields, we can have a common typeDefs and then extend for each client.
commonTypeDefs = `
type User {
id: ID!
name: String!
}
type Product {
id: ID!
name: String!
}
type Query {
me: User
product(id: ID!): Product
}
`
mobileTypeDefs = commonTypeDefs + `
extend type User {
email: String!
}
`
But note: the mobile User has an extra field. The web User might have even more. We can extend the common User.
Then, we have a common resolver for the common fields, and then mobile and web resolvers for the extended fields.
Example:
commonResolvers = {
User: {
id: (user) => user.id,
name: (user) => user.name,
},
Query: {
me: (parent, args, context) => { ... },
product: (parent, args, context) => { ... },
}
}
mobileResolvers = {
User: {
email: (user, args, context) => { ... },
}
}
Then, we merge the resolvers:
const mobileMergedResolvers = mergeResolvers([commonResolvers, mobileResolvers]);
This way, we share the common resolvers.
But note: the resolver for `me` in commonResolvers returns a User object that must have `id` and `name`. The mobile resolver for `email` expects the user object to have an `email` field? Or it will fetch it?
We can have the `me` resolver in commonResolvers return an object with only `id` and `name`, and then the mobile resolver for `email` will fetch the email separately? That would be inefficient.
Alternatively, the `me` resolver in commonResolvers can return the full user object (from the service) and then the mobile resolver for `email` just picks the email from the parent. But then the `me` resolver is the same for both?
We can have:
commonResolvers.Query.me = async (parent, args, context) => {
const user = await context.serviceClients.getUser(context.userId);
return user;
}
Then, the mobile resolver for `User.email` is:
(user) => user.email
And the web resolver for `User.address` is:
(user) => user.address
But then the `getUser` function must return all fields? That's over-fetching for mobile.
So, we are back to the same problem.
Therefore, even with shared common resolvers, we might have to have different implementations for the root fields if the data needs are different.
Given the complexity, I think it's acceptable to have two separate sets of resolvers, even if they share some code.
Final proposal:
We have two BFFs (mobile and web) that share:
- The same serviceClients (which call the backend services and return the full resources as provided by the backend)
- The same context creation (with DataLoaders, but note: the DataLoaders might be different because the mobile and web load different data? We can share the same DataLoader for the same backend service? But if the mobile and web need different fields, the DataLoader might load the full resource anyway? So we can share the DataLoader?
Example:
We have a `userLoader` that loads a user by ID and returns the full user object (as returned by the user service). Then, in the mobile resolver, we pick the fields we need. In the web resolver, we pick more. So the same DataLoader can be used.
But wait: if the user service returns a user with 100 fields and the mobile only needs 3, we are still loading 100 fields. That might be acceptable if the user service doesn't have a way to return fewer fields.
So, we can share the DataLoaders.
Then, the only difference between mobile and web is the GraphQL schema and the resolvers that pick the fields from the loaded objects.
But then, what about fields that require additional backend calls? For example, the web User.orders field. That would require a call to the order service. The mobile doesn't have that field, so we don't need the order service in mobile.
So, we might have:
In mobile:
User: {
email: (user) => user.email, // user is the object from userLoader
}
In web:
User: {
orders: (user, args, context) => {
return context.loaders.orderLoader.loadMany(user.orderIds);
}
}
So, the mobile doesn't need the orderLoader.
Therefore, the context for mobile and web might have different loaders.
We can create the context with all loaders, but then the mobile resolver for orders doesn't exist, so it's not used. But we are creating an orderLoader that might not be used. That's acceptable.
Alternatively, we can have different context creation functions? But that would be duplication.
We can have one context function that creates all loaders, and then in the mobile server, we don't use the orderLoader. That's fine.
So, we can share the context creation.
Then, the only difference is the schema and the resolvers.
We can even share the root resolvers (Query, Mutation) if they are the same? But the web has an `orders` query that mobile doesn't. So we have to have different root resolvers.
Therefore, we have two sets of resolvers, but we can share the helper functions and the DataLoaders.
Conclusion:
We design two GraphQL BFFs (mobile and web) that share:
- A common serviceClients module that calls the backend services (returns the full resources as provided by the backend)
- A common context module that creates a context with all necessary DataLoaders (even if some are not used by one of the BFFs)
- Common utility functions
And we have:
- Two GraphQL schemas (mobile and web) that define the fields for each client.
- Two resolver maps that use the shared context and serviceClients to fetch data, and then shape the data according to the schema.
The BFF server runs two ApolloServer instances on different paths (or one with two schemas, but that's more complex).
This architecture allows for:
- Code reuse of the service layer and context.
- Tailored GraphQL APIs for each client.
- Independent evolution of the mobile and web schemas.
However, if the mobile and web schemas are very similar, we might consider having one schema and then using field-level directives to hide fields from certain clients? But as discussed, that's complex.
Given the problem, I think this is a reasonable solution.
Let me write a sample code structure:
project/
src/
bff/
shared/
serviceClients.js
context.js
loaders.js (if we want to separate the DataLoader creation)
mobile/
schema.graphql
resolvers.js
web/
schema.graphql
resolvers.js
index.js (main server file)
In index.js:
const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const { readFileSync } = require('fs');
const path = require('path');
const mobileTypeDefs = readFileSync(path.join(__dirname, 'mobile/schema.graphql'), 'utf8');
const mobileResolvers = require('./mobile/resolvers');
const webTypeDefs = readFileSync(path.join(__dirname, 'web/schema.graphql'), 'utf8');
const webResolvers = require('./web/resolvers');
const { createContext } = require('./shared/context');
const mobileServer = new ApolloServer({
typeDefs: mobileTypeDefs,
resolvers: mobileResolvers,
context: createContext,
});
const webServer = new ApolloServer({
typeDefs: webTypeDefs,
resolvers: webResolvers,
context: createContext,
});
const app = express();
mobileServer.applyMiddleware({ app, path: '/graphql/mobile' });
webServer.applyMiddleware({ app, path: '/graphql/web' });
app.listen({ port: 4000 }, () => {
console.log(`🚀 Server ready at http://localhost:4000/graphql/mobile and http://localhost:4000/graphql/web`);
});
This is a simple setup.
We can also use schema stitching if we have common subschemas, but given the differences, I think separate schemas are simpler.
Now, what about the serviceClients? They are shared and used by both mobile and web resolvers.
Example serviceClients.js:
const fetch = require('node-fetch');
async function getUser(userId, token) {
const response = await fetch(`${process.env.USER_SERVICE_URL}/users/${userId}`, {
headers: { 'Authorization': `Bearer ${token}` },
});
if (response.status === 401) throw new AuthenticationError('Unauthorized');
if (response.status === 403) throw new ForbiddenError('Forbidden');
if (!response.ok) throw new Error('User service error');
return response.json();
}
async function getProduct(productId, token) {
// similar
}
async function getOrders(userId, token) {
// ...
}
// Batch versions if the backend supports it, otherwise we use DataLoader to batch individual calls.
async function batchGetUsers(userIds, token) {
// if the user service supports batch, we can do:
// POST /users/batch with { userIds } and return an array of users.
// Otherwise, we do:
return Promise.all(userIds.map(id => getUser(id, token)));
}
module.exports = {
getUser,
getProduct,
getOrders,
batchGetUsers,
// ... other service methods
};
Then, in context.js:
const { DataLoader } = require('dataloader');
const { createServiceClients } = require('./serviceClients');
function createContext(req) {
const token = req.headers.authorization || '';
const serviceClients = createServiceClients(token);
const userLoader = new DataLoader(keys => serviceClients.batchGetUsers(keys, token));
const productLoader = new DataLoader(keys => serviceClients.batchGetProducts(keys, token));
const orderLoader = new DataLoader(keys => serviceClients.batchGetOrders(keys, token));
return {
userId: req.user ? req.user.id : null,
serviceClients,
loaders: {
userLoader,
productLoader,
orderLoader,
},
};
}
module.exports = { createContext };
Then, in mobile resolvers:
const resolvers = {
Query: {
me: async (parent, args, context) => {
if (!context.userId) throw new AuthenticationError('Not authenticated');
return context.loaders.userLoader.load(context.userId);
},
product: async (parent, { id }, context) => {
return context.loaders.productLoader.load(id);
},
},
User: {
email: (user) => user.email, // assuming the user object from userLoader has email
},
Product: {
name: (product) => product.name,
price: (product) => product.price,
},
};
module.exports = resolvers;
In web resolvers:
const resolvers = {
Query: {
me: async (parent, args, context) => {
if (!context.userId) throw new AuthenticationError('Not authenticated');
return context.loaders.userLoader.load(context.userId);
},
product: async (parent, { id }, context) => {
return context.loaders.productLoader.load(id);
},
orders: async (parent, args, context) => {
if (!context.userId) throw new AuthenticationError('Not authenticated');
return context.loaders.orderLoader.load(context.userId);
},
},
User: {
email: (user) => user.email,
address: (user) => user.address,
orders: (user) => user.orders, // but wait, the user object from userLoader might not have orders.
},
// ... other fields
};
However, note: the user object from userLoader does not have orders. So we cannot do `user.orders`. We have to fetch orders separately.
So, in the web User.orders resolver:
orders: (user, args, context) => {
return context.loaders.orderLoader.loadMany(user.orderIds);
}
But then we need the user to have orderIds. How do we get orderIds?
We can change the userLoader to return a user with orderIds? But the user service might not return orderIds.
Alternatively, we can fetch orders by userId. So:
orders: (user, args, context) => {
return context.loaders.orderLoader.load(context.userId);
}
But then we are ignoring the `user` argument. That's acceptable because we know the orders for the current user.
But what if we want to get orders for another user? Then we need the user to have an id.
So:
orders: (user, args, context) => {
return context.loaders.orderLoader.load(user.id);
}
Then, the user object must have an id. That's fine.
So, we need to adjust the userLoader to return the user with at least the id.
Since we are loading the user by id, the user object will have an id.
So, the web User.orders resolver works.
This is a basic example.
Note: the above example assumes that the user service returns a user object with id, email, address, etc. and the order service returns orders for a userId.
But wait: the userLoader loads a user by userId, and then the orders field uses the user's id to load orders. That's a separate call.
We can also batch these if we have multiple users? But in the me query, we only load one user, so it's one call to user service and then one call to order service for that user's orders.
We can improve by using DataLoader for orders by userId, and then in the User.orders resolver, we load by user.id.
This is acceptable.
Now, what about the web Product type that has reviews? We would need a reviewLoader and a resolver that loads reviews by productId.
So, the pattern is:
- For each type that has a relationship to another type (like User to Orders, Product to Reviews), we have a DataLoader for the child type by parent id.
- The parent type's field resolver uses the parent's id to load the children.
This is a common pattern.
Finally, we have to consider that the BFF might need to call multiple backend services for a single field. For example, a User might have a recommendedProducts field that calls both the product service and a recommendation service.
Then, we would have a resolver that does:
recommendedProducts: async (user, args, context) => {
const products = await context.serviceClients.getRecommendedProducts(user.id);
return products;
}
And we might not use a DataLoader for that because it's a one-off call.
But if we have multiple users and each has recommendedProducts, then we might want to batch the calls to the recommendation service. So we would create a DataLoader for recommendedProducts by userId.
So, we should try to use DataLoaders for any field that might cause N+1.
Given the complexity, we have to design DataLoaders for every field that requires a backend call and might be requested in a list.
But note: if the field is on a type that is loaded by a DataLoader that already fetched the necessary data, we don't need an additional DataLoader.
Example: if the userLoader already returns the user with orders (because we changed the user service to include orders), then we don't need a separate orderLoader.
It depends on the backend services.
Given the time, I think we have covered the main points.
Let me summarize the architecture:
Two GraphQL BFFs (mobile and web) with separate schemas and resolvers, sharing:
- Service clients (that call backend services)
- Context creation (with DataLoaders for each backend service that might be called in a list)
- Authentication and error handling
The BFF server is an Express server with two ApolloServer instances on different paths.
This architecture aligns with the requirement of serving mobile and web with tailored APIs while reusing the backend service calls.
If in the future we need to add another client (e.g., smart TV), we can create a new BFF for that client and reuse the serviceClients and context.
We can also extract common types and resolvers into a common module if needed, but given the differences, it might be minimal.
I think this is a solid architecture.
Now, let's write a sample code for the mobile and web schemas and resolvers to illustrate.
Since we don't have actual backend services, we'll keep it simple.
Mobile schema (mobile/schema.graphql):
type User {
id: ID!
name: String!
email: String!
}
type Product {
id: ID!
name: String!
price: Float!
}
type Query {
me: User
product(id: ID!): Product
}
Mobile resolvers (mobile/resolvers.js):
const { AuthenticationError } = require('apollo-server-express');
const resolvers = {
Query: {
me: async (parent, args, context) => {
if (!context.userId) throw new AuthenticationError('Not authenticated');
return context.loaders.userLoader.load(context.userId);
},
product: async (parent, { id }, context) => {
return context.loaders.productLoader.load(id);
},
},
User: {
// The user object from userLoader already has id, name, email, so we don't need resolvers for these.
// But if we want to transform, we can.
},
Product: {
// same
},
};
module.exports = resolvers;
Web schema (web/schema.graphql):
type User {
id: ID!
name: String!
email: String!
address: String!
orders: [Order!]!
}
type Order {
id: ID!
date: String!
total: Float!
items: [OrderItem!]!
}
type OrderItem {
id: ID!
productId: ID!
quantity: Int!
price: Float!
}
type Product {
id: ID!
name: String!
price: Float!
description: String!
reviews: [Review!]!
}
type Review {
id: ID!
rating: Int!
comment: String!
}
type Query {
me: User
product(id: ID!): Product
orders: [Order!]!
}
Web resolvers (web/resolvers.js):
const resolvers = {
Query: {
me: async (parent, args, context) => {
if (!context.userId) throw new AuthenticationError('Not authenticated');
return context.loaders.userLoader.load(context.userId);
},
product: async (parent, { id }, context) => {
return context.loaders.productLoader.load(id);
},
orders: async (parent, args, context) => {
if (!context.userId) throw new AuthenticationError('Not authenticated');
return context.loaders.orderLoader.load(context.userId);
},
},
User: {
address: (user) => user.address,
orders: (user, args, context) => {
return context.loaders.orderLoader.loadMany(user.orderIds);
// But note: the user object from userLoader might not have orderIds.
// Alternatively, we can load orders by userId:
// return context.loaders.orderLoader.load(user.id);
// But then we are loading the same orders multiple times if we have multiple users?
// In the `me` query, we only have one user, so it's okay.
// But if we have a query that returns multiple users, then we want to batch the order loads by userId.
// So we do:
return context.loaders.orderLoader.load(user.id);
},
},
Product: {
description: (product) => product.description,
reviews: (product, args, context) => {
return context.loaders.reviewLoader.loadMany(product.reviewIds);
// or by productId:
// return context.loaders.reviewLoader.load(product.id);
},
},
Order: {
date: (order) => order.date,
total: (order) => order.total,
items: (order, args, context) => {
return context.loaders.orderItemLoader.loadMany(order.itemIds);
// or by orderId:
// return context.loaders.orderItemLoader.load(order.id);
},
},
OrderItem: {
productId: (item) => item.productId,
quantity: (item) => item.quantity,
price: (item) => item.price,
},
Review: {
rating: (review) => review.rating,
comment: (review) => review.comment,
},
};
module.exports = resolvers;
Note: the above web resolvers assume that the objects returned by the loaders have the necessary fields (like orderIds, reviewIds, itemIds) or we can load by the parent's id.
We have to design the loaders accordingly.
In the context, we create loaders for:
userLoader: by userId -> returns full user (with id, name, email, address, etc.)
productLoader: by productId -> returns full product (with id, name, price, description, etc.)
orderLoader: by userId -> returns orders for that user? Or by orderId?
Actually, in the web User.orders resolver, we are loading orders by user.id. So the orderLoader should be by userId? But then in the Order type, we have an items field that loads order items by order.id. So we need an orderItemLoader by orderId.
So we have:
orderLoader: new DataLoader(keys => serviceClients.batchGetOrdersByUserId(keys)) // keys are userIds
orderItemLoader: new DataLoader(keys => serviceClients.batchGetOrderItemsByOrderId(keys)) // keys are orderIds
And then in the Order.items resolver, we do:
items: (order, args, context) => {
return context.loaders.orderItemLoader.load(order.id);
}
But wait: the order object from orderLoader (which is by userId) might not have an id? It should have an id.
So, the orderLoader returns an array of orders for each userId. But note: the DataLoader for orderLoader is keyed by userId, and returns an array of orders? Or one order per userId?
If a user can have multiple orders, then we want to load all orders for a userId? Then the orderLoader should return an array of orders for each userId.
But then in the User.orders resolver, we do:
return context.loaders.orderLoader.load(user.id); // returns an array of orders
That's correct.
However, if we have multiple users in a query (like a list of users), then the orderLoader will be called with multiple userIds and return an array of arrays? Then we have to map each userId to an array of orders.
So the batch function for orderLoader:
async (userIds) => {
const ordersByUser = await serviceClients.batchGetOrdersByUserIds(userIds);
// returns an object mapping userId to array of orders? Or an array of orders for each userId in the same order?
// We need to return an array of arrays, where the i-th element is the array of orders for userIds[i].
}
This is getting complex.
Alternatively, we can have two loaders:
ordersByUserLoader: keyed by userId, returns array of orders.
orderLoader: keyed by orderId, returns a single order.
Then, in the User.orders resolver, we use ordersByUserLoader.
And in the Order type, we use orderLoader? But the order object is already loaded by ordersByUserLoader? Then we don't need to load the order again.
But the Order type might have fields that require additional data (like items). Then we need to load the items for each order.
We can do:
In the ordersByUserLoader, we load the orders and also load the order items? That would be N+1 again.
So, we should have:
ordersByUserLoader: loads orders by userId (without items)
orderItemsLoader: loads order items by orderId
Then, in the Order.items resolver, we use orderItemsLoader.
And if we have a query that loads a single order by id (like a detail page), we might have an orderByIdLoader that loads the order by orderId (without items) and then the items are loaded by orderItemsLoader.
So, we need to design our loaders carefully.
Given the complexity, I think we should stop here and say that the exact DataLoader design depends on the backend services and the client needs.
The key takeaway:
We have two BFFs (mobile and web) that share serviceClients and context (with DataLoaders) but have separate schemas and resolvers.
This architecture allows for:
- Independent schema evolution for each client.
- Reuse of the service layer and context (DataLoaders, authentication, error handling).
- Tailored data fetching for each client.
I think this meets the requirement.
Let me know if you have any questions.
I'll architect a comprehensive GraphQL BFF (Backend for Frontend) pattern that aligns mobile, web, and API reuse. This pattern addresses the unique needs of each client while maximizing backend service reuse.