The GraphQL Architect designs schemas and resolver trees that are maintainable, performant, and secure. The N+1 problem is the most common production issue in GraphQL - every resolver that fetches per-item instead of batching will exponentially multiply database queries as query depth increases.
Schema-First Design
type Query {
user(id: ID!): User
users(filter: UserFilter, pagination: PaginationInput): UserConnection!
}
type User {
id: ID!
email: String!
name: String!
posts(first: Int = 10, after: String): PostConnection! # Cursor-based pagination
createdAt: DateTime!
}
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type UserEdge {
node: User!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
endCursor: String
}
# Mutations follow the "input type + payload" pattern
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
}
input CreateUserInput { name: String! email: String! password: String! }
type CreateUserPayload { user: User errors: [UserError!]! }
type UserError { field: String message: String! }
N+1 Problem - DataLoader
import DataLoader from 'dataloader';
import { db } from './db';
// Without DataLoader: 1 query for users list + 1 query per user for their posts = N+1
// With DataLoader: batches all post fetches into ONE query
// In GraphQL context (created per-request to scope the per-request cache)
export function createLoaders() {
return {
postsByUserId: new DataLoader(async (userIds: readonly string[]) => {
const posts = await db.posts.findMany({
where: { userId: { in: userIds as string[] } }
});
// DataLoader requires results in same order as input keys
return userIds.map(id => posts.filter(p => p.userId === id));
}),
};
}
// Resolver
const resolvers = {
User: {
posts: (user, args, { loaders }) =>
loaders.postsByUserId.load(user.id), // Batches automatically
},
};
Authentication Middleware
// Context function - runs before resolvers
const server = new ApolloServer({
schema,
context: async ({ req }) => {
const token = req.headers.authorization?.replace('Bearer ', '');
const user = token ? await verifyJWT(token) : null;
return { user, loaders: createLoaders() };
},
});
// Auth directive or resolver guard
function requireAuth(resolver) {
return (parent, args, context, info) => {
if (!context.user) throw new GraphQLError('Unauthenticated', {
extensions: { code: 'UNAUTHENTICATED' }
});
return resolver(parent, args, context, info);
};
}