N+1 Query Problem
N+1 Query Problem
A query explosion when fetching related data. Solved with joins.
N+1 Query Problem
A query explosion when fetching related data. Solved with joins.
The N+1 Query Problem is a typical performance issue that occurs when using an ORM (Object-Relational Mapping). After one query that retrieves a list of parent entities, N additional queries are issued to retrieve each parent's child data. Example: retrieving 10 posts takes 1 query, and fetching each post's comments takes 10 additional queries = 11 queries in total.
The N+1 Query Problem is dangerous because the number of queries increases explosively in proportion to the amount of data. 100 posts result in 101 queries, and 1000 posts result in 1001 queries. Each query incurs network round-trip, connection acquisition, and SQL parsing overhead, so response time increases sharply.
Solution 1 - Eager Loading: Use a JOIN to fetch parents and children at once. Examples include JPA's fetch join, Django's select_related/prefetch_related, and Prisma's include. The number of queries is reduced to 1–2, but data that is not needed may also be fetched.
Solution 2 - DataLoader Pattern: Used mainly in GraphQL, it collects multiple requests into a batch and processes them at once. They are converted into a single query using an IN clause. Solution 3 - Query Optimization: Improve query efficiency by selecting only the required fields (projection), using subqueries, and applying appropriate indexing.
// N+1 문제 예시 (TypeORM)
// ❌ N+1 문제 발생 코드
async function getPostsWithComments() {
const posts = await postRepository.find(); // 1개 쿼리: SELECT * FROM posts
for (const post of posts) {
// N개 쿼리: SELECT * FROM comments WHERE post_id = ?
const comments = await commentRepository.find({
where: { postId: post.id }
});
post.comments = comments;
}
// 총 N+1개 쿼리 발생!
return posts;
}
// ✅ 해결 1: Eager Loading (JOIN)
async function getPostsWithCommentsOptimized() {
// 1개 쿼리: SELECT ... FROM posts LEFT JOIN comments ON ...
const posts = await postRepository.find({
relations: ['comments'] // 또는 relations: { comments: true }
});
return posts;
}
// ✅ 해결 2: QueryBuilder로 Fetch Join
async function getPostsWithFetchJoin() {
const posts = await postRepository
.createQueryBuilder('post')
.leftJoinAndSelect('post.comments', 'comment')
.leftJoinAndSelect('post.author', 'author')
.where('post.published = :published', { published: true })
.getMany();
return posts;
}
// ✅ 해결 3: DataLoader 패턴 (GraphQL)
import DataLoader from 'dataloader';
// 배치 함수: 여러 ID를 한 번에 조회
const commentLoader = new DataLoader(async (postIds: number[]) => {
// 1개 쿼리: SELECT * FROM comments WHERE post_id IN (1, 2, 3, ...)
const comments = await commentRepository.find({
where: { postId: In(postIds) }
});
// postId별로 그룹화하여 반환
const commentsByPostId = new Map();
for (const comment of comments) {
const existing = commentsByPostId.get(comment.postId) || [];
commentsByPostId.set(comment.postId, [...existing, comment]);
}
return postIds.map(id => commentsByPostId.get(id) || []);
});
// GraphQL Resolver에서 사용
const resolvers = {
Post: {
comments: (post, _, { loaders }) => loaders.commentLoader.load(post.id)
}
};
// ✅ Prisma에서의 해결
const posts = await prisma.post.findMany({
include: {
comments: true, // Eager loading
author: {
select: { name: true, email: true } // 필요한 필드만
}
}
});
// ✅ Django에서의 해결
# select_related: FK 관계 (1:1, N:1) - JOIN 사용
posts = Post.objects.select_related('author').all()
# prefetch_related: Reverse FK, M:M 관계 - 별도 쿼리 + 메모리 조인
posts = Post.objects.prefetch_related('comments').all()
In performance debugging:
"The list page takes as long as 5 seconds." - "I checked the query log, and over 200 queries are being sent. The N+1 problem is occurring because of Lazy Loading. If you add the relations option or use fetch join with QueryBuilder, you can reduce it to 2 queries."
In a technical interview:
"Do you have experience solving the N+1 Query Problem?" - "I turned on ORM logging and monitored the number of queries. I solved it with Eager Loading, but loading every relationship unconditionally causes an over-fetching problem, so I improved it to selectively load only the relationships needed for each screen."
In a code review:
"There is code that queries the DB inside a for loop. It could become a problem as the data grows, so it would be better to switch to batch queries with an IN clause or to a JOIN. It looks fine now with 10 items, but when it reaches 1000 later, it will cause an outage."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free