Your API performs perfectly during development. But when the application starts handling hundreds of records, response times increase dramatically.
The problem may not be your server configuration or frontend framework. It could be the number of database queries your backend executes.
The N+1 query problem is a common performance issue in backend applications, especially those using object-relational mapping libraries, relational databases and GraphQL.
Understanding how to identify and eliminate unnecessary database calls can help engineering teams build more scalable applications.
What is the N+1 query problem?
The N+1 query problem occurs when an application executes one query to retrieve a collection of records and then executes an additional query for each record.
Imagine an application displaying authors and their books.
The backend first retrieves all authors. It then retrieves the books belonging to each author individually.
For 100 authors, this implementation could execute 101 queries.
Why does the N+1 problem affect performance?
Each database request introduces potential network latency, connection usage, query processing and resource consumption.
Executing unnecessary queries can increase API response times and database load. Under heavy traffic, it may also contribute to connection-pool exhaustion.
The actual performance impact depends on query complexity, database configuration, network latency and application architecture.
How to identify N+1 queries
Start by enabling appropriate SQL logging in a development or test environment.
Look for repeated queries that have the same structure but different identifiers.
SELECT * FROM books WHERE author_id = 1;
SELECT * FROM books WHERE author_id = 2;
SELECT * FROM books WHERE author_id = 3;Repeated queries inside one API request are a useful indication that an N+1 pattern may exist.
Application performance monitoring and distributed tracing can also help identify database-heavy endpoints.
Avoid logging sensitive customer information or enabling unrestricted verbose logging in production.
Practical Python example
Before optimization
Consider this simplified Python implementation using a database cursor:
cursor.execute("SELECT id, name FROM authors")
authors = cursor.fetchall()
result = []
for author_id, name in authors:
cursor.execute(
"SELECT title FROM books WHERE author_id = %s",
(author_id,)
)
books = cursor.fetchall()
result.append({
"id": author_id,
"name": name,
"books": [row[0] for row in books]
})This implementation retrieves the authors once and then executes another database query for every author.
The number of queries increases as the number of authors increases.
After optimization using batch loading
The following example uses PostgreSQL-style parameter binding with Psycopg:
from collections import defaultdict
cursor.execute("SELECT id, name FROM authors")
authors = cursor.fetchall()
author_ids = [row[0] for row in authors]
books_by_author = defaultdict(list)
if author_ids:
cursor.execute(
"""
SELECT author_id, title
FROM books
WHERE author_id = ANY(%s)
""",
(author_ids,)
)
for author_id, title in cursor.fetchall():
books_by_author[author_id].append(title)
result = [
{
"id": author_id,
"name": name,
"books": books_by_author[author_id]
}
for author_id, name in authors
]Instead of executing a query inside the loop, this implementation retrieves the related books in one batch.
For a nonempty author collection, the example executes two database queries. Authors without books receive an empty list.
For very large collections, consider pagination or bounded batches rather than loading unlimited records.
Fixing N+1 queries using SQL JOIN
Another solution is to retrieve related data using a SQL JOIN.
SELECT
a.id,
a.name,
b.title
FROM authors a
LEFT JOIN books b
ON a.id = b.author_id;A LEFT JOIN preserves authors who do not have matching books.
However, joins can repeat parent information for each child record. Joining several one-to-many relationships can also produce large result sets.
Batch loading versus SQL JOIN
| Batch loading | SQL JOIN |
|---|---|
| Usually separate parent and child queries | Can retrieve related data in one query |
| Convenient for nested API responses | Convenient for flat relational results |
| Requires grouping in application code | May require deduplication |
| Can use bounded batches | Can produce large joined result sets |
Choose the strategy based on your data model and measured performance rather than assuming that fewer queries are always faster.
Using database indexes
Indexes can help the database locate related records efficiently.
For example:
CREATE INDEX books_author_idx
ON books(author_id);Before creating an index, check whether an equivalent index already exists and examine the query execution plan.
EXPLAIN
SELECT *
FROM books
WHERE author_id = 10;Indexes consume storage and introduce additional work during writes. They should be created based on actual query patterns.
Handling N+1 queries in GraphQL
GraphQL resolvers can introduce N+1 queries when every parent object independently resolves its related records.
A request-scoped DataLoader implementation can combine multiple lookup requests into batches and reuse results within the request.
The loader must preserve the relationship between requested keys and returned values. It should also respect authorization boundaries and avoid accidentally sharing private data across users.
Preventing N+1 regressions
Engineering teams should include database query behavior in their automated tests.
Useful testing practices include checking query counts for representative fixtures, verifying correct handling of empty relationships, testing pagination and measuring endpoint latency under realistic loads.
An application that passes functional tests can still have inefficient database access patterns.
Monitor performance after deployment to confirm that the optimization improves the actual workload.
Frequently asked questions
Does the N+1 query problem occur only in ORMs?
No. It can occur in manually written SQL, GraphQL resolvers, REST APIs and any application that repeatedly retrieves related data inside a loop.
Does adding an index fix N+1 queries?
An index may make individual queries faster, but it does not eliminate the repeated database calls. Batch loading or appropriate joins address the query pattern itself.
Is eager loading always the best solution?
No. Eager loading can retrieve unnecessary data or produce large result sets. Review the generated SQL and measure performance.
Can caching solve the N+1 problem?
Caching can reduce repeated lookups, but cache misses may still trigger inefficient queries. Caching should complement an efficient data-access strategy.
How many database queries should an API execute?
There is no universal ideal number. The goal is to avoid unnecessary work while maintaining correctness, security and predictable performance.
Conclusion
The N+1 query problem is a common but often overlooked cause of backend performance issues.
By identifying repeated database queries, using batch loading or suitable SQL joins, applying appropriate indexes and monitoring real application behavior, developers can build more efficient and scalable APIs.
Start by measuring your existing implementation, make targeted improvements and verify the results through automated tests and production monitoring.
Need help optimizing your application?
Connect with Tekody for remote engineering and AI development support, including backend performance optimization, API debugging, database integration and scalable application architecture.
👉 Request Support: https://tekody.com/get-support/
📲 WhatsApp for Support: +91-8527854783