Guide

Finding N+1 queries in Node.js

What an N+1 query is, how to find one in a Node.js app (Prisma, Mongoose, TypeORM, Sequelize, Knex, Drizzle) and how to fix it.

npm install peekinside
Quick start

An N+1 query is a loop that runs one query per row: one query fetches a list of N things, then N more queries fetch something for each of them. It's the most common reason a Node.js endpoint that was fast in development gets slow in production, because the loop grows with the data: 10 orders in your seed data, 500 for your biggest customer.

// 1 query for the orders...
const orders = await prisma.order.findMany({ where: { userId } });
for (const order of orders) {
  // ...and 1 more for each order: N+1
  order.items = await prisma.orderItem.findMany({ where: { orderId: order.id } });
}

Each query is fast on its own, so nothing looks wrong in a log or a slow-query report. What gives it away is the count: the same statement, with a different value, many times in one request.

How PeekInside finds them#

PeekInside records every database query your app runs, per request, and flags a statement that runs 5 times or more in one request as an N+1. It reads queries from the drivers, so it works whatever you build them with:

Library How its queries are recorded
Prisma Prisma 7: the queries its driver adapter runs, labeled with the Prisma call (OrderItem.findMany). Prisma 5 and 6: one span per call
TypeORM, Sequelize, Knex, Drizzle, Kysely Through pg or mysql2, the drivers they run on
Mongoose Through the mongodb driver it uses (find, aggregate...)
pg, mysql2, mongodb Directly

Install it and add one line; nothing else changes in your code:

import PeekInside from 'peekinside';

PeekInside.attach(app); // Express, Koa, Fastify, NestJS, Hono or an http.Server

Then use your app as usual. Requests that ran an N+1 are marked in the request list, and filtering by has:n+1 keeps only those. Open one and its Queries tab shows the statement that repeated, how many times, how long all of them took together, and the file and line of your code that ran it. The Queries page shows every statement across requests, with a view of the N+1 loops alone, and the Routes page points out the routes where a quarter or more of the requests query in a loop.

The threshold is yours to set, along with what counts as a slow query (100 ms by default):

PeekInside.attach(app, { nPlusOneThreshold: 10, slowQueryMs: 250 });

Running the same statement with the same values twice is counted separately, as a duplicate: usually a value fetched again that could have been passed along.

Fixing one#

The fix is always the same idea: ask for all the rows at once, then match them up in your code (or let the ORM do it).

Prisma: ask for the relation with include (or select), and Prisma fetches all of it with one query per relation, not one per row:

const orders = await prisma.order.findMany({ where: { userId }, include: { items: true } });

Mongoose: populate() fetches the referenced documents with one $in query:

const orders = await Order.find({ user: userId }).populate('items');

TypeORM: load the relation with the query, with relations: { items: true } or a join:

const orders = await orderRepository.find({ where: { userId }, relations: { items: true } });

Sequelize: eager-load with include:

const orders = await Order.findAll({ where: { userId }, include: OrderItem });

SQL, Knex, Drizzle or Kysely: one query with IN (or a join), then group the rows:

const orders = await db('orders').where({ user_id: userId });
const items = await db('order_items').whereIn('order_id', orders.map((order) => order.id));

GraphQL resolvers are where N+1 loops hide best, because each field resolves on its own: DataLoader batches the lookups of one request into one query.

Then check: the request's Queries tab should show one statement where there were N, and the request list loses its N+1 mark.

Questions#

Why don't N+1 queries show up in development?#

Because the loop runs once per row, and development databases have few rows. Ten fast queries don't stand out; five hundred do. PeekInside flags the pattern at 5 runs, so you see it while the data is still small.

Does Prisma prevent N+1 queries?#

include and select fetch relations without a query per row, and Prisma batches findUnique calls made at the same time. A loop that awaits a query for each row still runs one query per row; that's the loop to look for.

Can I find N+1 queries in production?#

Yes: the same SDK sends to PeekInside Cloud when PEEKINSIDE_API_KEY is set, with the same flags on every request, its queries encrypted before they leave your server.

Try it on your app

Install the package, add PeekInside.attach(app), and start your app as usual: it prints the link to its dashboard. Free, no account, and your data stays on your machine. On your servers, the same line reports to PeekInside Cloud once it has an API key.