A page that lists 50 blog posts with their authors works fine on your laptop. In production it takes two seconds. The database is not overloaded, no single query is slow, and the code looks clean. You open the query log and find 51 queries for one page view. That is the N+1 query problem, and it is one of the most common performance bugs in web applications.
What N+1 means
You run one query to get a list of N rows. Then, for each of those rows, your code runs one more query to fetch something related. One query for the list, plus N queries for the details: N+1 in total.
Here is the classic example in Django:
posts = Post.objects.all()[:50] # 1 query for post in posts: print(post.title, post.author.name) # 1 query per post The first line sends one SELECT to the post table. The loop looks innocent, but post.author is a foreign key. The ORM does not have the author yet, so the first time you touch post.author it sends:
SELECT * FROM author WHERE id = 7; And then WHERE id = 12, WHERE id = 7 again, and so on, once per post. Fifty posts, fifty extra round trips.
The same pattern shows up in every ORM that loads relations lazily: Django, Rails Active Record, Hibernate/JPA, Entity Framework, SQLAlchemy, Sequelize, Eloquent. It also shows up without an ORM, when a loop in your code calls a function that runs a query, or when a GraphQL resolver fetches one related object per item.
Why it hurts more than it looks
Each of those small queries is fast on its own, often well under a millisecond inside the database. The cost is everything around it:
- Network round trips. Every query is a request and a response between the app and the database. If the database is on another machine, each trip adds latency, and the trips happen one after another.
- Per-query overhead. Parsing, planning, locking a connection, building result objects in the ORM.
- It grows with data. 10 rows in development means 11 queries. 500 rows in production means 501. Nested relations multiply it: posts, then comments per post, then the author per comment.
This is why N+1 rarely shows up in tests or on a developer machine with a local database and tiny tables. It appears when real data and real network latency meet.
How to spot it
You cannot see N+1 by reading a single query. You see it by counting queries per request.
- Turn on query logging in development. Django has
django-debug-toolbar, Rails prints every query in the development log, Hibernate hasshow_sqland statistics, SQLAlchemy hasecho=True. - Look for repeated queries that differ only in the parameter: the same
SELECT ... WHERE id = ?many times in one request. - Use tools that warn you. The
bulletgem for Rails andnplusonefor Python report lazy loads inside loops. APM tools usually group identical queries per request. - Assert query counts in tests. Django's
assertNumQueriesfails a test if a view sends more queries than expected, which catches regressions early.
A useful habit: for every list page or list endpoint, know how many queries it sends, and check that the number does not grow with the number of items.
How to fix it
The fix is always the same idea: fetch the related data in a fixed number of queries, not one per row. There are two main ways.
1. Join it in the same query
When the relation is "many to one" (each post has one author), a SQL join fetches everything at once:
SELECT post.id, post.title, author.name FROM post JOIN author ON author.id = post.author_id LIMIT 50; In Django this is select_related:
posts = Post.objects.select_related("author")[:50] # 1 query with a JOIN Rails has includes or eager_load, JPA has JOIN FETCH in JPQL or entity graphs, SQLAlchemy has joinedload.
2. Fetch the related rows in a second query
When the relation is "one to many" or "many to many" (each post has many comments), a join would repeat every post once per comment. The better approach is two queries: one for the posts, one for all their comments using IN:
SELECT * FROM comment WHERE post_id IN (1, 2, 3, ..., 50); The ORM then matches comments to posts in memory. In Django this is prefetch_related("comments"), in SQLAlchemy selectinload, in Rails preload (or includes, which picks a strategy for you).
Either way, the number of queries no longer depends on N. Fifty posts or five hundred, you send one or two queries.
3. Batch in code
Outside an ORM, or in GraphQL, the same idea is called batching. Collect the IDs you need, send one query for all of them, and build a lookup map. The DataLoader pattern does this automatically: resolvers ask for author(7), author(12), and the loader groups those requests within one tick into a single WHERE id IN (...).
Common mistakes
Fixing it in one place, breaking it in another. You add select_related("author") in the view, but the template also calls post.category.name. Now you have a new N+1 on categories. Check the whole request, including templates and serializers.
Joining everything. Eager loading every relation "just in case" brings back wide rows and data you never use. A join on a one-to-many relation can multiply rows and memory. Load what the page actually needs.
Hidden queries in properties and methods. A model method like post.comment_count() that runs COUNT(*) will run once per post in a loop. Use an annotation or aggregate in the main query instead, for example Django's annotate(Count("comments")).
Serializers. REST serializers that include nested objects often trigger lazy loads for each item. Prepare the queryset with the right eager loading before you pass it in.
Paginating after fetching. Loading all rows and then slicing in Python means you pay for rows you never show. Limit in the query.
Is N+1 always wrong?
Not always. If N is small and bounded (a page that always shows three items), a few extra queries may not matter. Sometimes lazy loading is the right choice: on a detail page you might only need a relation in rare cases. And a very large IN (...) list has its own limits, so for huge sets you may batch in chunks.
The real rule is: the number of queries for a request should not grow with the amount of data. When it does, you have a problem that will show up as soon as the data grows.
Watch the animated version: https://youtu.be/Yigo07_1UwU
In short
- N+1 means one query for a list, then one more query per item to load related data.
- It comes from lazy loading inside loops, in templates, serializers and resolvers.
- Spot it by counting queries per request and looking for repeated queries that differ only by ID.
- Fix it with a join (
select_related,joinedload,JOIN FETCH) for single relations, or a secondINquery (prefetch_related,selectinload,preload) for collections, or a DataLoader-style batch. - Add query-count assertions to tests so it does not come back.
Originally published at abdeldjalilchougui.biz.

