Skip to content

N+1 Problem

In one line

N+1 problem: 1 query loads N records, then N queries load each record's relations — should be 1 query with a join.

In simple words

The N+1 problem is a common ORM performance issue. You load a list of N records (1 query), then for each record you load a related record (N queries). Total: N+1 queries instead of 1 query with a JOIN.

Example: loading 100 orders and their customers:

  • N+1: 1 query for orders + 100 queries for each customer = 101 queries
  • Fixed: 1 query with JOIN = 1 query

Solutions:

  1. Eager loading — use JOIN or IN to load relations in one query
  2. DataLoader pattern — batch relation lookups (popular in GraphQL)
  3. Manual JOIN — write the JOIN yourself instead of using ORM lazy loading

The N+1 problem is the #1 cause of slow ORM applications. Always check your query log for unexpected repeated queries.

Example

javascript
// N+1 Problem (BAD — 101 queries)
const orders = await Order.findAll(); // 1 query
for (const order of orders) {
  const customer = await order.getCustomer(); // N queries!
  console.log(order.id, customer.name);
}

// Fix 1: Eager loading with JOIN (1 query)
const orders = await Order.findAll({
  include: [{ model: Customer }] // JOIN in one query
});
for (const order of orders) {
  console.log(order.id, order.Customer.name); // already loaded
}

// Fix 2: DataLoader batching
const customerLoader = new DataLoader(async (ids) => {
  // SELECT * FROM customers WHERE id IN (1, 2, 3, ...)
  return Customer.findAll({ where: { id: ids } });
});
for (const order of orders) {
  const customer = await customerLoader.load(order.customerId);
  // Batches all loads into one query
}

N+1: 1 query for orders + N queries for customers. Fix with eager loading (JOIN) or DataLoader (batched IN query). Always check ORM query logs.

Common confusions

  • Confused with: lazy loading

    The difference: Lazy loading is the ORM feature that loads relations on demand — it CAUSES the N+1 problem. Eager loading loads relations upfront with a JOIN — it FIXES the N+1 problem. Lazy loading is convenient but slow; eager loading is explicit but fast.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary