API with NestJS #28. Dealing in the N + 1 problem in GraphQL

JavaScript NestJS TypeScript

This entry is part 28 of 168 in the API with NestJS

In the previous article, we’ve implemented resolvers and queries. There is quite a common catch with them, though. It is referred to as the N + 1 problem. In this article, we illustrate the issue and provide a few ways to deal with it.

The N + 1 problem

The N + 1 problem can appear when we fetch nested, related data. A good example would be the following query:

Graphql query

Above, we request an author for every post. One way to do so would be to use the decorator that NestJS gives us. Let’s add it to our resolver:

posts.resolver.ts

In this example, we create a field resolver. What we return from it becomes the value of the author. To figure out which author we need to query from the database, we access the parent. In this case, the post is the parent of the author.

In this series, we use the TypeORM library. To have access to the property, we need to use decorator.

post.entity.ts

We also need to add it to our GraphQL model.

post.model.ts

Seeing the issue

While the above certainly works, it has a serious flaw. To visualize it, let’s modify our slightly:

You can find more options connected to the logging functionality in the official TypeORM documentation.

Thanks to , we can now see what queries we make to the database. It looks a bit like the following:

The core of the issue is that for N posts, we make N + 1 queries to the database. This is why it is called the N + 1 problem.

Solving the N + 1 problem with the DataLoader

One of the ways of solving the above issue is using the DataLoader library. We can use it to batch our requests and load all entities at once.

With the above code, we tell the DataLoader that we will need authors with certain ids. Our goal is to batch all of those and create queries like that:

Some libraries aim to integrate the DataLoader with NestJS, but they are not well maintained.

The crucial thing to understand with the DataLoader is that it should be initialized once per request. Therefore, it is commonly used within a GraphQL context object that can be initialized once per every request. We could achieve it with a code like that:

Unfortunately, this is not very elegant, because we would need to put all of our loaders there in one place. Instead, we can follow a very cool idea by Jeppe Smith.

First, let’s create a method that can query multiple users from the database at once.

users.service.ts

An important thing to remember that the order of the results in is not guaranteed. The results that we return from our DataLoader need to be in the same order as the ids. Therefore, we need to map them to ensure that.

Let’s create an with . This means that NestJS will reinitialize our class for every request.

posts.loaders.ts

We also need to add to array in the .

The last thing is to use the above loader in our resolver.

posts.resolver.ts

With the above solutions, we make just two queries to the database. The first one is for the posts, and the second one is for all of the authors.

Solving the N + 1 issue with JOIN queries

Instead of the above approach, we might create just one database query that joins posts and users. First, let’s look into the implementation of a method that does that in the .

posts.service.ts

Above, our method contains the pagination functionality. If you want to know more about it, check out API with NestJS #17. Offset and keyset pagination with PostgreSQL and TypeORM

Now, let’s use the method in our resolver:

posts.resolver.ts

Thanks to that approach, TypeORM generates a single query both for the posts and the authors. There is an issue here, though. With the above code, we always fetch both posts and authors, even if the client does not request it.

Fortunately, we can access the details about the GraphQL query with the decorator. The most straightforward way to use it is with the graphql-parse-resolve-info library.

posts.resolver.ts

Thanks to the above optimization, we join posts with authors only if the user requests it through the query.

Summary

This article tackled the N + 1 problem, which is a common issue in the GraphQL world. The first approach that we’ve implemented was with the DataLoader library. With it, we’ve limited the number of queries that we perform to two. The second way of solving the problem was with a JOIN query performed through TypeORM.

There are a lot more topics when it comes to GraphQL, so you can expect more articles about it. Stay tuned!

Series Navigation<< API with NestJS #27. Introduction to GraphQL. Queries, mutations, and authenticationAPI with NestJS #29. Real-time updates with GraphQL subscriptions >>
Subscribe
Notify of
guest
9 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Luis Schweigard
Luis Schweigard
3 years ago

Tried this method, and failed!

The error: TypeError: dataloader_1.default is not a constructor

Any ideas?

Luis Schweigard
Luis Schweigard
3 years ago

[Edit]: The issue seems to be the Typescript Compiler screwing up the import.

Changing import DataLoader from ‘dataloader’; to import * as DataLoader from ‘dataloader’; solved the issue, but this is very weird …

Itunedy
Itunedy
3 years ago

If you config in tsconfig.json: “allowSyntheticDefaultImports”: true,

Then you are able to import module directly :

Apapacy
Apapacy
3 years ago

Join-monster npm package is solve n+1problem too

Last edited 3 years ago by Apapacy
Tal Shtark
Tal Shtark
3 years ago

What if i have “Post” and “Comment” entities (both with “author” field) and i want to utilize the same “batchAuthors” function to load the author field for both of them? should it be defined in “PostsLoaders”/”CommentsLoaders”? both? or in other place?

Roy B
Roy B
2 years ago
Reply to  Tal Shtark

If you’re making two requests, to fetch both posts and comments with relation to their author,
as long as they run at the same event loop tick, Dataloader won’t load the same author twice.

Last edited 2 years ago by Roy B
Rafael
Rafael
2 years ago
Reply to  Tal Shtark

You can create users.loader.ts and don’t forget to user Scope as REQUEST.

Leonard Mounir
Leonard Mounir
2 years ago

Can you add an example for an external data source. Example , Apollo use rest endpoint datasource- how would you work with that?