graphqlgraphql-js

Optimizing graphql database queries


Lets say we have following graphql schema:

type Author : Object {  
  id: ID!
  name: String,
  books: [Book]
}

type Book : Object {  
  id: ID!
  title: String
  authorId: Int
  author: Author
}

And then making a query like:

{
    books: {
        id 
        title
        author { id name }
    }
}

If, for example, we have 10 books, then we will end up with 10 author queries, as the resolve function will be called for each fetched book:

select id, name from author where id = 123

Instead of this we can execute all author queries as a single query:

select id, name from author where id in (123, 456, 789, 1011)

Is there some working solutions, best practices, techniques or something that can help to achieve this?


Solution

  • Dataloader is your answer, it has batching feature which means that it will queue all the ids. Only once its ready it will pull it as a batch.

    Demo can be found here (Last 5 minutes in particular)

    Algorithm explaination can be found here