Back to all questions

What is the N + 1 problem in GraphQL?

Devs Hive

Devs Hive

Seen on interview: 1 user

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.

type Query {
products: [Product]
}

type Product {
id: ID!
name: String!
price: Float!

comments: [Comment]
}

type Comment {
id: ID!
author: String!
body: String!
createdAt: String!
}

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.

SELECT *
FROM comments c
WHERE c.product_id = 1;

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]).

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!