The N+1 query problem: how to spot and fix it
An N+1 query happens when code runs one query to load a list and then one more query per row to load a related record, so 10 books and their authors become 11 queries. The fix is eager loading: Django select_related or prefetch_related, Rails includes, Prisma include. The related rows then come back in one or two queries. With tracing on, Sentry opens an 'N+1 Queries' performance issue when it sees a run of similar, sequential database spans that add up to more than 50 ms.
What an N+1 query looks like
This is the example from Sentry's docs. A view lists ten books with their authors:
def books(request):
books = Book.objects.all()[:10] # 1 query
titles = [f"{b.title} by {b.author.name}" for b in books] # +10 queries
return HttpResponse(", ".join(titles))Django loads the books lazily, so each b.author runs its own query. The database log shows one list query followed by a run of nearly identical ones:
SELECT ... FROM "books" LIMIT 10
SELECT ... FROM "authors" WHERE "authors"."id" = %s
SELECT ... FROM "authors" WHERE "authors"."id" = %s
... 8 more, identical apart from the parameterIn a trace it has an obvious shape: a staircase of short db spans, one after another and never overlapping, all with the same description. Each query takes a millisecond or two, so nothing looks slow on its own. The cost is the round trips. With 10 rows nobody notices, but at 500 rows on production data the endpoint takes seconds.
How Sentry detects N+1 queries
With tracing enabled, Sentry checks transactions for common performance problems and opens a performance issue called N+1 Queries. The detector looks for sequential, non-overlapping database spans with similar descriptions, and:
- their total duration is over
50ms; - their count is over a threshold (usually five spans);
- each span's description holds the full query, not one the SDK truncated with an ellipsis;
- at least one database span comes before the repeats. Sentry calls this the source span and uses it for fingerprinting.
The issue shows the transaction, the parent span (often a view or serializer), the preceding span, the repeating span and the waterfall. Search issue.category:db_query in Issues to list these issues together with Consecutive DB Queries and Slow DB Queries. Project Admins can raise or lower the thresholds, or turn the detector off, in Project Settings > Performance.
If the same loop shows up as many separate issues, your span descriptions probably contain literal values (WHERE books.id = 1) rather than placeholders (WHERE books.id = %s), so each value gets its own fingerprint. Sentry has a separate N+1 API Calls detector for HTTP requests made in a loop.
Fix it in Django: select_related vs prefetch_related
| Method | Relations | How |
|---|---|---|
select_related | ForeignKey, OneToOne (single-valued) | A SQL JOIN in the same query |
prefetch_related | Many-to-many, reverse FK, GenericRelation (and the ones above) | One extra query per lookup, joined in Python |
from django.db.models import Prefetch
# ForeignKey / OneToOne: one query with a JOIN
books = Book.objects.select_related("author")[:10]
# Reverse FK / many-to-many: one extra query per relation, joined in Python
books = Book.objects.prefetch_related(
Prefetch("reviews",
queryset=Review.objects.filter(approved=True),
to_attr="approved_reviews"),
)[:10]
# Writes in a loop are N+1 too
Book.objects.bulk_create([Book(title=f"Book {i}") for i in range(1, 11)])A Prefetch with a queryset lets you filter or order the related rows without bringing back a query per row.
Fix it in Rails: includes, preload, eager_load
Rails' guide uses the same books-and-authors case. Ten books with book.author in a loop make 11 queries.
# N+1: 1 query for books + 1 per author
Book.limit(10).each { |book| puts book.author.last_name }
# Fixed: 2 queries
Book.includes(:author).limit(10).each { |book| puts book.author.last_name }
# Make lazy loading fail loudly while you hunt them down
books = Book.strict_loading.limit(10)
books.first.author
# => ActiveRecord::StrictLoadingViolationError| Method | Queries for the example | Conditions on the association |
|---|---|---|
includes | 2 (a LEFT OUTER JOIN when you add where on the association) | Yes |
preload | 2, one per association | No |
eager_load | 1, a LEFT OUTER JOIN | Yes |
The Rails guide recommends includes, which picks between the other two for you.
Fix it in Prisma: include
In Prisma, an N+1 usually means an await inside a loop. This example assumes a Post model with an author relation.
// N+1: one findMany, then one query per post
const posts = await prisma.post.findMany({ take: 10 });
for (const post of posts) {
post.author = await prisma.user.findUnique({ where: { id: post.authorId } });
}
// Fixed: load the relation with the list
const postsWithAuthors = await prisma.post.findMany({
take: 10,
include: { author: true },
});According to Prisma's docs, include loads the relation in two SQL queries in total (one for the list, one for the related rows), not one per post. In GraphQL resolvers, where each field resolves separately, Prisma's dataloader batches findUnique() calls made in the same tick. That's why the docs suggest the fluent form prisma.user.findUnique({ where: { id } }).posts() rather than a findMany in each resolver.
The mistakes people make next
- Fixing the view but not the template or serializer. The loop that touches the relation is often in a template, a DRF serializer or a
to_json. Open the parent span in Sentry's evidence to see where it is. - Using a JOIN for a large has-many.
select_relateddoesn't accept many-valued relations. In Rails,eager_loadon a big has-many multiplies the rows that come back. Use separate queries (prefetch_related,preload) instead. - Forgetting writes. Calling
createin a loop is an N+1 too. In Django, usebulk_create. - Assuming it's fixed. Deploy, then open a new trace for the same transaction. The staircase should now be one or two spans.
Questions
Why is it called N+1?
You run one query for the list and N more, one for each of the N rows. People also write it as 'n plus one query'.
Why isn't Sentry flagging my N+1 query?
The repeated spans have to add up to more than 50 ms, pass the count threshold (usually five), carry full query descriptions and follow a preceding database span. Short loops, or SDKs that truncate queries, can miss these criteria. You can tune the thresholds in Project Settings > Performance.
Is a JOIN always better than prefetching?
No. A JOIN is best for single-valued relations. For has-many or many-to-many, a second query (prefetch_related, preload, Prisma include) usually moves less data than a JOIN that repeats every parent row.
Can N+1 happen with HTTP calls instead of SQL?
Yes. Calling an API once per item in a loop is the same pattern, and Sentry has a separate N+1 API Calls detector for it.
Sources
- N+1 Queriesdocs.sentry.io
- QuerySet API referencedocs.djangoproject.com
- Active Record Query Interfaceguides.rubyonrails.org
- Query optimizationwww.prisma.io