Understanding and fixing N+1 query
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, and go back to your kitchen with it.

You check the first line:

200 grams of Dark Chocolate.

You go into your attic to fetch a tablet of chocolate, go back to the kitchen, and read the second line:

3 Eggs

Once again, you take the flight of stairs to fetch those 3 eggs, go back to the kitchen and read the next lines of the recipe:

100 grams of Butter

A bit exhausted by all those back and forth, you take the path to the attic, AGAIN. If only there was a simpler way…

What you would be experiencing, if you cooked this way, is exactly what happens when we have a N+1 query problem. Your ORM is forced by your code to do N additional queries (the round trips to fetch the ingredients) after the first initial query (when you fetched your recipe).

A concrete example

We’ll stay in the cooking business by considering a web application that displays a listing of cooking recipes like follow:
['Alexandre Ignjatovic']
['Sql', 'Ruby', 'Software Development', 'Performance', 'Technology']