What best describes the N+1 problem in GraphQL?
Think about how many database calls happen when fetching related data for multiple items.
The N+1 problem happens when a query first fetches N items, then for each item, it makes another query to fetch related data. This leads to 1 query for the list plus N queries for each item, causing performance issues.
Given a GraphQL query fetching 3 authors and their books, if each author triggers a separate database call for books, how many total database calls are made?
query {
authors {
id
name
books {
title
}
}
}Count one call for authors plus one call per author for books.
There is 1 call to fetch all authors, then 1 call per author to fetch their books. For 3 authors, total calls = 1 + 3 = 4.
Which code snippet correctly uses DataLoader to batch load books for authors and avoid the N+1 problem?
const booksLoader = new DataLoader(async (authorIds) => { // Fetch books for all authorIds in one query const books = await db.books.where('authorId').in(authorIds).toArray(); return authorIds.map(id => books.filter(book => book.authorId === id)); });
Look for the method that fetches books for multiple author IDs at once and returns them grouped by author.
Option B correctly uses where('authorId').in(authorIds) to fetch all books for the given author IDs in one query, then maps results to each author ID. Other options either use wrong methods or return wrong structures.
Which approach best avoids the N+1 problem when resolving nested fields in GraphQL?
Think about batching and caching to reduce repeated database calls.
DataLoader batches multiple requests for nested fields into a single database call and caches results, effectively solving the N+1 problem. Other options cause multiple queries or inefficient data fetching.
Given the following resolver code, which line causes the N+1 problem?
const resolvers = {
Query: {
authors: () => db.authors.findAll(),
},
Author: {
books: (author) => db.books.findAll({ where: { authorId: author.id } }),
},
};Look for the resolver that queries the database for each author individually.
The books resolver queries the database separately for each author, causing one query per author and leading to the N+1 problem. The authors resolver fetches all authors in one call, which is correct.