How to solve 1+n Problem in GraphQL

Yashod Perera
2 min readMar 12, 2024

--

Photo by JJ Ying on Unsplash

GraphQL has been widely used to fetch data from different data sources dynamically and provide results which are needed for consumers. Let’s go through an example where we have authors and author can have multiple books. Then the graph looks like follows.

When we need to get all the authors and the books they have written there are multiple calls sends as follows.

As you can see if we are getting 3 authors then it will send 1 call for get authors and 3 calls for get book information for each author. If we have n authors then it will call 1 to get all authors and n calls for get book information which we introduced as 1+n problem in GraphQL

How to solve it?

In GraphQL above problem has been solved with data loaders. It is a simple solution which we can used for any number of levels. We need to introduce a function which accepts all the author ids and fetch all the books for the given authors.

As given above it will send a one call to get authors and it will pass author ids to the data loader and in the data loader function it fetch all the books with a single client call. Then it will pass book information to the lower level.

Following code repository has an example with and without data loaders.

  • Without Data Loaders — Link
  • With Data Loaders — Link

Hopefully this is helpful.

If you have found this helpful please hit that 👏 and share it on social media :).

--

--

Yashod Perera

Technical Writer | Tech Enthusiast | Open source contributor