Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL and nested resources would make unnecessary calls?

Tags:

graphql

I read GraphQL specs and could not find a way to avoid 1 + N * number_of_nested calls, am I missing something?

i.e. a query has a type client which has nested orders and addresses, if there are 10 clients it will do 1 call for the 10 clients + 10 calls for each client.orders + 10 calls for each client.addresses.

Is there a way to avoid this? Not that it is not the same as caching an UUID of something, those are all different values and if you GraphQL points to a database which can make joins, it would be pretty bad on it because you could do 3 queries for any number of clients.

I ask this because I wanted to integrate GraphQL with an API that can fetch nested resources in an efficient way and if there was a way to solve the whole graph before resolving it would be nice to try to put some nested stuff in just one call.

Or I got it wrong and GraphQL is meant to be used only with microservices?

like image 237
Jayson Reis Avatar asked Oct 18 '22 15:10

Jayson Reis


1 Answers

This is one of the difficulties of GraphQL's "resolver architecture". You must avoid incurring a ton of network latency by doing a lot of I/O in each resolver. Apps using a SQL DBMS will often grapple with the N + 1 problem at first. You need to use some batching and/or caching techniques to get around this.

If you are using Node.js on the server, I have two tools to recommend:

  • DataLoader - A database-agnostic tool for batching resolvers for each field and caching individual records.

  • Join Monster - A SQL-tailored tool that reads each query and your schema and compiles a SQL query for you. It leverages JOINs and DataLoader-style batching to fetch the data from your tables in a few (or a single) SQL queries.

like image 123
Andy Carlson Avatar answered Oct 21 '22 08:10

Andy Carlson