Member-only story

Solving the N+1 Problem in GraphQL

Ben Grunfeld
3 min readMay 4, 2021

The N+1 problem occurs when we use data returned from the database to fuel a list of further queries to the database.

Article title image. Solving the N+1 Problem in GraphQL

Meaning, if you receive a list of results from a query, then for each result, you will make another query to the database.

In this case, the N stands for the number of results returned from the database, and 1 stands for the initial query that was made.

To clarify: the problem is that for each of the N results returned, we will have to make another query, so there will be N requests made to the database, plus the 1, which was the initial request.

This can easily become a performance bottleneck.

Example of an N+1 Situation

You want to query the grades for all the students who go to a school. The N+1 problem would occur if you first queried all the students who go to that school, and then made a loop that would query the grades for each student that was returned, one at a time.

Here’s some example pseudocode:

const students = `SELECT * FROM students`students.forEach(student => 
`SELECT * FROM grades WHERE student_id = ${student.student_id}`)

Traditional Solution for the N+1 Problem

--

--

Ben Grunfeld
Ben Grunfeld

Written by Ben Grunfeld

I’m a Front End Engineer who loves React, NextJS, and GraphQL. Looking for a developer in #Israel? Contact me at: https://www.linkedin.com/in/bengrunfeld/

Responses (1)