Skip to content
jshacks.dev
Performance

Avoid N plus 1 queries with batching

Replace a query per row inside a loop with one query using ANY and a lookup Map, so loading 100 posts with authors takes 2 queries instead of 101.

1 min read
Summarize in AI

An N+1 problem appears when you load a list with one query and then run another query for each item. The number of round trips grows with the list.

posts.jsJavaScript
// N+1: one query for the posts, then one per post.
const { rows: posts } = await db.query('SELECT id, title, author_id FROM posts LIMIT 100');
for (const post of posts) {
  const { rows } = await db.query('SELECT name FROM users WHERE id = $1', [post.author_id]);
  post.author = rows[0].name;
}

// Batched: two queries in total.
const ids = [...new Set(posts.map((post) => post.author_id))];
const { rows: users } = await db.query('SELECT id, name FROM users WHERE id = ANY($1)', [ids]);
const names = new Map(users.map((user) => [user.id, user.name]));
for (const post of posts) post.author = names.get(post.author_id);

console.log(posts[0]);
Text
{ id: 1, title: 'Hello', author_id: 7, author: 'Ada' }

The first version sends 101 statements for 100 posts; the second sends 2. = ANY($1) takes an array parameter in PostgreSQL's pg driver, and the Map joins the results to the posts in the application.

A SQL JOIN does the same in one query and is often simplest. The batching approach suits cases where the second lookup comes from another service or store. Libraries such as DataLoader batch automatically within one tick. See [ANY in PostgreSQL](https://www.postgresql.org/docs/current/functions-comparisons.html).

Also inNode.js
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.