Back to results for “Performance Optimization & Profiling”
Node.js › Databases

What is the N+1 query problem, and how does it commonly arise in a Node.js application using an ORM?

Intermediate

Answer

The N+1 query problem occurs when code fetches a list of N parent records with one query, then issues a separate additional query for each parent's related child data inside a loop, resulting in N+1 total queries instead of a single efficient join or batched query -- commonly introduced accidentally through an ORM's lazy-loading behavior, where accessing a related field triggers an implicit, easy-to-miss query.
// N+1 problem: one query for users, then one additional query per user for their orders
const users = await User.findAll();
for (const user of users) {
  const orders = await user.getOrders(); // triggers a separate query, N times
}

// Fixed: a single query with eager loading
const users = await User.findAll({ include: [Order] });
Real-world example A dashboard listing 100 users along with each user's most recent order was issuing 101 total database queries until the team added eager loading via the ORM's include option, collapsing it down to a single efficient join query.

Common follow-ups: How would you detect an N+1 query problem in an existing codebase before it becomes a production performance issue?;Does the N+1 problem apply to raw SQL queries as well, or is it specifically an ORM concern?