DEV Community

Cover image for GraphQL query complexity + NestJS + Dataloader

GraphQL query complexity + NestJS + Dataloader

I was doing some exploration around GraphQL query complexity, depth limitation, and how to incorporate dataloader in NestJS to make my GraphQL API faster.

Heads up

  1. Just before getting into details I need to clarify that this is a contrived example.
  2. UPDATE: I just saw this issue in graphql-depth-limit-ts about Connection Spec for pagination. Frankly speaking I did not consider this at all πŸ˜…. So right now I think my implementation can be enhanced to cover this case too.

Database state

  • A dockerized PostgreSQL version 17.
  • I have about 1,000 users.
  • Each user has about 100 posts.

Resolver

I am fetching only 5 posts when you execute the following query inside the resolver for the getPosts:

{
  getPosts {
    id
    author {
      id
      posts {
        id
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

But in the posts resolver I decided to fetch all of their posts (100). And that's where the bottleneck is.

Statistics before Dataloader

It was talking up to 5.5 seconds to retrieve data. And it was freaking huge. As you might have guessed it, I was using @ResolveField and sending a separate SELECT command to my underlying database.

Statistics after Dataloader

Now it fetches the same dataset in ~3.7 seconds. It is 32% performance increase. This might sound a bit disappointing but look at it this way:

  1. This is a contrived example.
  2. Take into account all those I/O costs that will be eliminated to some extend.
  3. You do not need to pay more than you have to (in pay-as-you-go payment model your database instance was constantly being hit with new requests).

Repo


There go for: apps/dataloader-example. BTW in this repo you can see my implementation of static query cost analysis which you can learn more about it here. The part that I especially proud of is where I incorporated depth of a field in the overall complexity of a field (for context look at this issue).


If this helped you consider giving me a star on my GitHub repo for this Post :).


Follow me:

Instagram: https://www.instagram.com/node.js.developers.kh/
Facebook: https://www.facebook.com/kasirbarati
X: https://x.com/kasir_barati
YouTube: https://www.youtube.com/@kasir-barati
GitHub: https://github.com/kasir-barati/
Dev.to: https://dev.to/kasir-barati
LinkedIn: https://linkedin.com/in/kasir-barati

Top comments (0)