Understanding and fixing N+1 query

Alexandre Ignjatovic
Doctolib
Published in
5 min readJul 10, 2020

--

In this article, you’ll learn about the famous N+1 query that everybody is talking about, and how to fix and prevent them.

Regarding backend performance, there is a performance issue that everybody has heard about at least once: N+1 query. What you’ll hear less often is that baking a chocolate cake is a perfect analogy to explain it.

What’s a N+1 query?

TL;DR: The N+1 query problem happens when your code executes N additional query statements to fetch the same data that could have been retrieved when executing the primary query.

If you understood the previous statement, you can skip right to the next section: “How to fix it?

If you did not understand the previous statement, don’t worry. We’ll sort it out together.

The recipe analogy

First, let put aside all those query, and SQL, and web application shenanigans, and imagine that you’d like to bake a cake.

For the sake of the example, let’s imagine that your fridge and pantry are not in your kitchen, but in your attic, forcing you to take the stairs anytime you’d like to fetch something out of the fridge.

Now, let’s imagine that you go to your bedroom to grab your cookbook, to find your chocolate cake recipe…

--

--