The N+1 Query Problem: What It Is and How to Fix It

Raghav Chamadiya9 min read
On this page

The N+1 query problem is a database performance anti-pattern where code runs one query to fetch a list of N records, then one more query for each record to load related data. Loading 100 posts with their authors costs 101 queries instead of 1 or 2. It usually comes from an ORM's lazy loading inside a loop.

N+1 is easy to write and invisible in development, where tables hold ten rows. It shows up in production as a page that gets slower as data grows. This guide shows the problem in a SQL log, the fix in the major ORMs and GraphQL, and how to catch it before it ships.

What is the N+1 query problem?

N+1 means one query for the parent rows plus N queries for their children, one per row. Here it is in Django:

python
posts = Post.objects.all()[:100]
for post in posts:
    print(post.title, post.author.name)   # each access to post.author runs a query

The SQL log shows what happens:

sql
SELECT id, title, author_id FROM blog_post LIMIT 100;
SELECT id, name FROM auth_user WHERE id = 7;
SELECT id, name FROM auth_user WHERE id = 12;
SELECT id, name FROM auth_user WHERE id = 7;
-- ... 97 more, one per post

One query fetched the posts. Then the template or loop touched post.author, the ORM saw the author was not loaded, and it fetched it. One hundred times. The fix produces one query with a join, or two queries with an IN list:

sql
SELECT p.id, p.title, u.id, u.name
FROM blog_post p JOIN auth_user u ON u.id = p.author_id
LIMIT 100;

The problem is not limited to ORMs. Any loop that calls the database, an HTTP API, a cache or the file system once per item has the same shape. ORMs just make it easy to write without seeing it.

Why N+1 queries are slow

Each query pays a full round trip (network, parsing, planning, locking), and N+1 multiplies that fixed cost by the row count. The per-row work is tiny; the per-query overhead is not.

Rows (N)Queries with N+1Queries after the fixAdded time at 1 ms per round tripAt 5 ms (cross-zone database)
10111 or 210 ms50 ms
1001011 or 2100 ms500 ms
1,0001,0011 or 21 s5 s

Scroll the table sideways to see every column.

The latencies in the table are illustrative round-trip times, and the arithmetic is the point: cost grows linearly with data that your test fixtures never had. It also stacks. Two nested relations in a loop (posts, then each post's comments, then each comment's author) is N times M queries. And each of those queries holds a connection from the pool, so an N+1 under load slows down every other request too.

Use select_related for foreign keys and one-to-one relations (one query with a SQL join) and prefetch_related for many-to-many and reverse relations (one extra query with IN). Both are in the Django QuerySet reference.

python
# Foreign key: one query with a JOIN
posts = Post.objects.select_related("author")[:100]

# Reverse foreign key and many-to-many: two queries total
posts = Post.objects.prefetch_related("comments", "tags")[:100]

# Control the prefetched queryset, including its own select_related
from django.db.models import Prefetch
posts = Post.objects.prefetch_related(
    Prefetch("comments", queryset=Comment.objects.select_related("author"))
)

Django REST Framework serializers are a common hiding place: a nested serializer reads a relation per object. Add select_related or prefetch_related to the view's get_queryset. In tests, self.assertNumQueries(2) fails the test the day someone adds a relation without prefetching.

N+1 in Rails, Laravel, SQLAlchemy and Prisma

Every mainstream ORM has an eager-loading call; the work is remembering to use it.

ORMN+1 versionFixed versionMake lazy loads fail loudly
Rails (Active Record)Post.all.each { |p| p.author.name }Post.includes(:author)strict_loading on a relation or model (Rails 6.1+)
Laravel (Eloquent)foreach (Post::all() as $p) $p->author->name;Post::with('author')->get()Model::preventLazyLoading() in a service provider
SQLAlchemyfor p in session.scalars(select(Post)): p.author.nameselect(Post).options(selectinload(Post.author))lazy="raise" on the relationship, or raiseload("*")
Prismafor (const p of posts) await prisma.user.findUnique({ where: { id: p.authorId } })prisma.post.findMany({ include: { author: true } })Use include or select for relations

Scroll the table sideways to see every column.

Notes per framework:

  • Rails: includes picks between a separate query (preload) and a join (eager_load). The Bullet gem warns about N+1 queries and unused eager loading in development.
  • Laravel: with('comments.author') eager loads nested relations; load() does the same on a collection you already have. See Eloquent eager loading.
  • SQLAlchemy: selectinload runs one extra SELECT ... WHERE id IN (...) per relation and is the default choice for collections; joinedload uses a join and suits many-to-one. See the relationship loading techniques.
  • Prisma: include loads relations in the same call. Prisma Client also batches findUnique calls made in the same tick, which helps GraphQL resolvers (query optimization docs).

N+1 in GraphQL: DataLoader

GraphQL is N+1 by design: each field has its own resolver, so a list of 100 posts calls the author resolver 100 times. DataLoader fixes it by collecting the keys requested in one tick and loading them in a single batch.

javascript
import DataLoader from "dataloader";

const userLoader = new DataLoader(async (ids) => {
  const users = await db.user.findMany({ where: { id: { in: ids } } });
  const byId = new Map(users.map((u) => [u.id, u]));
  return ids.map((id) => byId.get(id) ?? null);   // same order as the keys
});

const resolvers = {
  Post: { author: (post) => userLoader.load(post.authorId) },
};

Create the loader per request, not globally, so its cache never leaks data between users. The batch function must return results in the same order as the keys. The DataLoader README covers caching and options; Python has the same pattern in Strawberry's and graphene's dataloaders.

How to detect N+1 queries

Runtime tools catch N+1 queries on the code paths you run; static analysis catches them on the paths you have not run yet. Use both. A CPU profile drawn as a flame graph shows whether the loop is actually hot.

MethodHow it worksCatches
Query logsLog every SQL statement in development (django.db.backends logger, Rails log, Laravel DB::listen)Repeated near-identical queries on pages you open
Debug toolbarsdjango-debug-toolbar, Laravel Debugbar show query counts and duplicates per requestSame, with a per-request summary
N+1 detectorsBullet (Rails), nplusone (Django, SQLAlchemy), preventLazyLoading and strict_loadingLazy loads in loops, raised as warnings or errors
Query-count testsassertNumQueries in Django, query counters in other stacksRegressions on tested endpoints
APM tracesDatadog, New Relic, Sentry performance and similar flag repeated spans in a traceN+1 in production traffic
Static detectionReads the code for a query or I/O call reached from inside a loopLoops on paths no test or user has hit, including across functions

Scroll the table sideways to see every column.

The runtime methods share one limit: they see only what executes. A rarely used admin action, a nightly job or a branch for one customer tier can carry an N+1 for months. And the hardest cases cross function boundaries. The loop is in a view, the query is three calls down in a helper, and a per-function linter looks at each piece and sees nothing wrong.

Find N+1 queries before they ship with repowise

repowise finds database, network, file and subprocess calls reached from inside a loop, follows the resolved call graph up to three hops to find them across functions and files, and groups the findings by the one place you would edit. It reads the parse tree and the call graph, so nothing has to run (performance in the code health docs). ORM lazy loads in Django and SQLAlchemy and Spring Data or MyBatis calls in Java loops are recognized directly.

A real example from the open-source Saleor e-commerce platform, on its public repo page. list_shipping_methods_for_checkout loops, and inside the loop it calls trigger_webhook_sync_promise, which calls create_promise_delivery_for_subscription_sync_event, which calls generate_payload_promise_from_subscription, which hits the database. No single function contains both the loop and the query. repowise reports it as one cross-function N+1 with the full path, and groups 8 such call sites in 4 files into a single opportunity on the shared helper, with a batch-or-prefetch fix strategy.

Each opportunity says what its loop walks (rows from a query, a collection passed in, a fixed set), whether it grows with the data, and what runs it (a request handler, a scheduled job, a CLI command). Loops that run per request and grow with the data rank first. Test and tooling code is counted separately, so the queue is the production code that ships.

Coverage spans Python, TypeScript and JavaScript, Java, Go, C#, Rust, Kotlin, Scala, Ruby, C++, Dart, Pascal and Apex. See the performance feature page for the full list of detectors. For the wider picture, what is static code analysis explains how this kind of detection works, the code health guide shows where performance sits next to complexity and ownership, and deterministic PR review covers putting checks like this in front of every pull request.

FAQ

What is n+1?
N+1 is a performance problem where code runs one query to load a list, then one extra query per item to load related data, for N+1 queries in total. It typically comes from an ORM lazily loading a relation inside a loop. The fix is to load the related data up front with a join or a single batched query.
Is N+1 only an ORM problem?
No. Any loop that makes one call per item to a database, an HTTP API, a cache or the file system has the same shape and cost. ORMs make it common because lazy loading hides the query behind an attribute access. GraphQL resolvers and microservice clients produce it without any ORM.
How do I detect N+1 queries in Django?
Watch the SQL with django-debug-toolbar or the django.db.backends logger and look for repeated near-identical queries. The nplusone package raises a warning or error on lazy loads in loops, and assertNumQueries in tests stops regressions. Static analysis finds the cases no test exercises.
What is the difference between eager and lazy loading?
Lazy loading fetches a related object only when the code first accesses it, which is cheap for one object and causes N+1 in a loop. Eager loading fetches the related objects together with the parent query, through a join or one batched IN query. Use eager loading whenever you know you will read the relation for every row.
Can static analysis find N+1 queries?
Yes. A static analyzer can find a database or I/O call reached from inside a loop by reading the code and its call graph, without running it. repowise follows calls up to three hops, so it finds an N+1 even when the loop and the query are in different functions and files.