Logo

dev-resources.site

for different kinds of informations.

GraphQL query complexity + NestJS + Dataloader

Published at
12/24/2024
Categories
nestjs
graphql
dataloader
node
Author
Mohammad Jawad (Kasir) Barati
Categories
4 categories in total
nestjs
open
graphql
open
dataloader
open
node
open
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:

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
      }
    }
  }
}

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

Featured ones: