I was doing some exploration around GraphQL query complexity, depth limitation, and how to incorporate dataloader in NestJS to make my GraphQL API faster.
- Just before getting into details I need to clarify that this is a contrived example.
-
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
}
}
}
}
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:
- This is a contrived example.
- Take into account all those I/O costs that will be eliminated to some extend.
- 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
kasir-barati / graphql-js-ts
Where you can learn all about GraphQL and its intricacies
Caution
Keep this file in sync with index.md
.
GraphQL
Tip
Just for those curious minds who always jump from one branch to another like mine:
You can find a good definition usually in glossary.
- Intro.
- Data types.
- A simple todo app written with GraphQL + ReactJS + Relay
- Queries and mutations in depth.
- Let's breakdown the query language a bit more.
-
Functions provided by
graphql
. - Document your GraphQL service API.
- GraphQL request lifecycle
- Code-first approach.
- Auth.
- How to query information about a GraphQL schema.
- Improve developer experience
- Security in GraphQL.
- NestJSβ¦
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)