The N + 1 problem in GraphQL is a classic question when discussing GraphQL API design or comparing it with REST. It occurs when a single GraphQL query results in a large number of small database queries.
Let's look at a simple example with an online store. We query for products and want to fetch their comments as well. If we were using REST API, we could do a JOIN at the ORM level and fetch all the data in a single query. But in GraphQL, we fetch all the products with one query and then start calling Resolvers separately for each product.
A separate SQL query will be executed for each product. If we have 100 products, 100 additional database queries will be run to fetch the comments for each individual product.
How to solve this problem?
It is solved quite simply with DataLoader, whose main purpose is Batching. In our case, DataLoader will collect all the product ids into a single array and call a function that fetches the comments in a more optimized way. For example, instead of 100 database queries, we can get everything with a single query using WHERE IN([…productIds]).