The N+1 query problem
What the N+1 query problem is and how to fix it in any stack: how ORMs and lazy loading cause it, spotting it in logs and tests, fixes with joins, fetch joins and entity graphs in JPA, select_related and prefetch_related in Django, eager loading in Prisma and Rails-style ORMs, batching with IN queries and DataLoader, and preventing regressions.
CodexBash, , 5 min read
A page listing 50 orders with their customers' names works fine on a developer's laptop and then takes three seconds in production. The database logs show why: one query to load the orders, then one more query for each order to load its customer. That is the N+1 query problem: 1 query for the list plus N queries for related data. It is one of the most common performance bugs in applications that use ORMs, and one of the easiest to fix once you can see it. This article explains the cause and the fixes in several popular frameworks.
Sign in to read the rest
The whole 5 minute article is free with an account, along with every problem, lesson and tutorial. No card.