How-To Guide

How to Avoid N+1 Query Problems

Detect and fix the N+1 query pattern: load related data in one round trip, batch by key, and verify the query count stays constant as rows grow.

On this page

  1. Introduction
  2. Detect the pattern before fixing it
  3. Load children in one round trip
  4. Batch and map in memory
  5. Prevent the pattern from returning
  6. Test that the count stays flat
  7. Common pitfalls
  8. Conclusion

Introduction

The N+1 problem is the most common performance bug in database-backed applications. A first query loads a list of parents, and then the code issues one more query per parent to load its children. For ten parents that is eleven queries; for a thousand parents it is a thousand and one. Each query is fast in isolation, so the bug hides in development where datasets are small, and it explodes in production where they are large.

This tutorial shows how to detect N+1 by counting queries per request, how to replace it with a single join or a batched query, how to map batched results back to their parents, and how to test that the query count stays flat as the number of parents grows. The examples use SQL and a TypeScript data layer, but the pattern is language-agnostic.

Detect the pattern before fixing it

The signature of N+1 is a query count that grows with the number of rows returned. Instrument your data layer to count queries per request, then load a small dataset and a large one and compare. If the count is proportional to the number of parents, you have found it. Many ORMs can log queries in development; enable that and look at a request that renders a list.

Detection not by counting but by reading is fragile, because lazy loading is invisible at the call site. A loop that reads order.items inside a template triggers a query per order without any explicit query call. Counting is the reliable signal, and a test that asserts the count is the durable guard against reintroduction.

// N+1: one query for parents, then one per parent
const orders = await db.query('SELECT id FROM orders LIMIT 100');
for (const order of orders) {
  order.items = await db.query('SELECT * FROM order_items WHERE order_id = $1', [order.id]);
}
// 1 + 100 = 101 queries

Load children in one round trip

The fix is to stop issuing a query per parent and instead fetch all the children for the whole set of parent keys in one query. With a batched IN query, you collect the parent ids and select the children whose foreign key is in that set. With a join, you select parents and children together and let the database do the matching. Both reduce the round trips from N+1 to a small constant.

A join is compact but changes the result shape: a parent with five children appears five times, so you must group in memory to rebuild the tree. A batched IN query keeps two separate result sets, a parent list and a child list, which you then group by the foreign key. For a one-to-many where the child count varies widely, the batched query avoids the row multiplication that can bloat a join result.

-- one batched query for all children of a known parent set
SELECT oi.order_id, oi.product_id, oi.quantity
FROM order_items oi
WHERE oi.order_id = ANY($1::bigint[]);

-- or a single join that returns parent and child together
SELECT o.id, o.total, oi.product_id, oi.quantity
FROM orders o
LEFT JOIN order_items oi ON oi.order_id = o.id
WHERE o.id = ANY($1::bigint[]);

Batch and map in memory

After the batched query, build a map from parent key to its children in one pass, then attach each list to its parent. This pass is linear in the number of children and adds no round trips. Handle parents with no children by defaulting to an empty list rather than leaving the field undefined, so the downstream code does not need to distinguish absent from empty.

Watch the size of the batched query. If the parent set is extremely large, a single IN with tens of thousands of ids can be slow to parse and plan. Chunk the ids into batches of a manageable size and run several batched queries, still a small constant number relative to N. Keep the chunk size configurable so it can be tuned per database.

async function loadOrdersWithItems(parentIds: number[]) {
  const orders = await db.query('SELECT * FROM orders WHERE id = ANY($1)', [parentIds]);
  const items = await db.query(
    'SELECT * FROM order_items WHERE order_id = ANY($1)',
    [parentIds],
  );
  const byOrder = new Map<number, unknown[]>();
  for (const item of items.rows) {
    const list = byOrder.get(item.order_id) ?? [];
    list.push(item);
    byOrder.set(item.order_id, list);
  }
  return orders.rows.map((o) => ({ ...o, items: byOrder.get(o.id) ?? [] }));
}
// 2 queries regardless of parent count

Prevent the pattern from returning

Fixing one N+1 does not fix the next one a developer writes. Make the safe pattern the convenient one: provide a data-access function that loads a parent set with its children in a fixed number of queries, and require it instead of exposing a per-parent loader. If the framework supports eager loading, configure it as the default for relations that are almost always accessed, and require an explicit opt-out for rare lazy cases.

Also consider a dataloader pattern for GraphQL-like resolvers, which batches and caches loads within a single request. It collects the keys requested during a tick, fetches them in one query, and returns the results to each caller. This generalizes the fix and prevents the pattern from reappearing in resolver code.

Test that the count stays flat

Seed a dataset with ten parents and another with a hundred, and assert the query count per request is the same and small. A count that doubles when the parents double is a regression. Also assert the response is correct, because a batching bug can silently attach the wrong children. This pair of assertions, correctness plus a flat query count, is the durable guard.

# log queries per request and compare across dataset sizes
DB_LOG=1 node server.js &
curl -s 'http://localhost:3000/orders?limit=10'  >/dev/null
curl -s 'http://localhost:3000/orders?limit=100' >/dev/null
# assert the logged query count for each request is identical and small (e.g. 2 or 3)

Common pitfalls

Using lazy relations inside a loop, enabling eager loading globally so every request fetches unused data, joining many-to-many relations and multiplying rows without deduplicating, unbounded IN lists, and testing only with tiny datasets so the pattern is invisible are the recurring mistakes. Counting queries, batching by key, chunking large id sets, and testing at two sizes address them.

Conclusion

N+1 hides because each query is fast; only the count reveals it. Instrument query counts per request, replace per-parent lookups with a join or a batched query, group the results by key in memory, and test that the count stays constant as rows grow. Self-check by asserting the same small query count for ten and a hundred parents. When the safe accessor is the convenient one, the pattern stops returning.

Sources: PostgreSQL: Joins between tables, PostgreSQL: IN and subqueries, MDN: SQL JOIN overview.

FAQ

Why is N+1 so common with ORMs?
An object graph encourages accessing a relation lazily, so a loop over parents that touches a child list fires one query per parent. The convenience of lazy loading hides the cost until the number of parents grows.
Is a join always better than a batched IN query?
Not always. A join is one round trip but can duplicate parent rows when a parent has many children. A batched IN query keeps the parent and child result sets separate and is easier to map in memory. Choose based on shape and volume.

Related Examples