Sitemap
The Marcy Lab School

The Marcy Lab School is an alternative to college that provides historically underrepresented students with a holistic accelerated pathway to land a high-paying job in the tech industry.

What is the N+1 Problem in GraphQL?

A crash course on a surprisingly common problem

3 min readJun 27, 2019

--

Press enter or click to view image in full size

https://mostlyfocused.com/pages/articles/n_plus_1_graphql is a free, improved version of this article

Once you get beyond the basics of GraphQL, you’ll likely hear people talk about the “N+1 problem.” This might seem scary, it does sound like O(N) notation, which is usually the last thing you hear before your whiteboard interview implodes. But, rest assured this is a simple concept hiding behind a computer science-y name.

The Situation in Question

Let’s say I have a DB of authors and their books, a simple “has many” relationship. Now, I want to get all my authors, and all their books. In REST, you’d make a route that uses your ORM of choice to do something along the lines of:

route: '/authors/books',
method: 'GET',
handler: async () => ORM.getAuthors().getTheirBooks();

Under the hood, it would execute 2 queries: one to get all the authors, and one to get all their books. To use pseudo SQL it would be like:

SELECT *
FROM authors;
-- pretend this returns 3 authors
SELECT *
FROM books
WHERE author_id in (1, 2, 3); -- an array of the author's ids

--

--

The Marcy Lab School
The Marcy Lab School

Published in The Marcy Lab School

The Marcy Lab School is an alternative to college that provides historically underrepresented students with a holistic accelerated pathway to land a high-paying job in the tech industry.

Responses (8)