What is the N+1 query problem in the context of an ORM like Mongoose or Sequelize, and how do you avoid it?
Short answer
The N+1 problem occurs when fetching a list of N parent records, then separately querying for each one's related data individually (N additional queries) instead of fetching everything in one or two efficient queries -- for example, fetching 100 blog posts and then looping…
Advertisement
AModel answer
The N+1 problem occurs when fetching a list of N parent records, then separately querying for each one's related data individually (N additional queries) instead of fetching everything in one or two efficient queries -- for example, fetching 100 blog posts and then looping through them to fetch each post's author separately triggers 101 total queries; the fix is eager loading (Mongoose's .populate(), Sequelize's 'include' option), which fetches the related data in the same or a single additional batched query.
// N+1 problem: 1 query for posts, then N queries for each author
const posts = await Post.find();
for (const post of posts) {
post.author = await User.findById(post.authorId); // triggers a separate query each time
}
// Fixed: a single additional query via populate()
const posts = await Post.find().populate('author');Real-world example
A blog's homepage that was taking several seconds to load under moderate traffic is fixed by replacing a loop that fetched each post's author individually with a single .populate('author') call, collapsing what had been 101 separate database round-trips into just 2.
Likely follow-ups
- How do you detect an N+1 query problem in an existing codebase, given it isn't always obvious from reading the code alone?
- What's the performance tradeoff of eager loading everything by default versus loading relations lazily only when actually needed?
Related topics