Skip to article content
FrontendXLesson 15 / 24

The N plus one query problem

Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.

advanced · about 55 minutes · 2 exercises

  • Predict
  • Debug

What you will be able to do

#
  • Detect an N plus one pattern from query logs or an ORM.
  • Replace it with a join, an eager load or a batched lookup.
  • Measure the query count before and after the fix.

Overview

#

N plus one happens when code runs one query to fetch a list and then one more query per item. For 100 articles that is 101 round trips instead of 1 or 2.

The pattern

snippet.js
const articles = await db.query('SELECT id, author_id FROM articles LIMIT 100');
for (const article of articles) {
  const author = await db.query('SELECT name FROM authors WHERE id = $1', [article.author_id]);
  article.author = author;
}

Each loop iteration is a separate round trip, so latency scales with the list size.

Fixes

  • Join the related table in the original query.
  • Eager load with the ORM in one query.
  • Collect the ids and fetch them in one WHERE id = ANY($1) query, then map in memory.
snippet.js
const ids = articles.map((a) => a.author_id);
const authors = await db.query('SELECT id, name FROM authors WHERE id = ANY($1)', [ids]);
const byId = new Map(authors.map((a) => [a.id, a]));
articles.forEach((a) => { a.author = byId.get(a.author_id); });

Common pitfalls

  • Fixing N plus one with a join that fans out and duplicates rows.
  • Fetching a batch with no bound on the id list, which can exceed parameter limits.
  • Not measuring, so the fix is assumed rather than confirmed.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Debug

    A page renders 50 products and issues 51 queries. Identify the pattern and rewrite the loop to one extra query.

    starter.javascript
    const products = await db.query('SELECT id, category_id FROM products LIMIT 50');
    for (const p of products) {
      p.category = await db.query('SELECT name FROM categories WHERE id = $1', [p.category_id]);
    }

    Reveal the reference answer
    reference.javascript
    const products = await db.query('SELECT id, category_id FROM products LIMIT 50');
    const ids = [...new Set(products.map((p) => p.category_id))];
    const categories = await db.query('SELECT id, name FROM categories WHERE id = ANY($1)', [ids]);
    const byId = new Map(categories.map((c) => [c.id, c]));
    products.forEach((p) => { p.category = byId.get(p.category_id); });

    Authored expected output: 2 queries total instead of 51.

    Collect the distinct foreign keys, fetch them in one query, then map in memory. The query count no longer scales with the list size.

  2. Exercise 2Predict

    A list of 200 items triggers N plus one. Roughly how many queries run, and what happens as the list grows?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.txt
    1 list query + 1 query per item
    Choose the best answer

Common misconceptions

#
  • An ORM prevents N plus one: lazy relations are exactly how it happens.
  • The fix is always a join: a batched second query is often simpler and avoids row fan-out.

Follow-up practice

#
  • backend-databases-connection-pooling

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.