
What it looks like
const orders = await db.orders.findMany({ where: { status: "open" } }); // 1 query
for (const order of orders) {
order.customer = await db.customers.findById(order.customerId); // N queries
}Why nobody notices in development
On a laptop the test database has five orders, so the page runs six queries and feels instant. In production the list has five hundred, each query adds a trip to the database, and the page takes seconds. The code did not change. The data did.
How to spot it
- The query log shows the same query many times in a row, with only the id changing.
- The number of queries on a page grows with the number of items shown.
- A page that was fast last year is slow now, and nobody touched it.
The two fixes
- Fetch them together. Collect the ids, then load all the customers in one query.
- Join. Ask the database for the orders with their customers in a single query.
const orders = await db.orders.findMany({ where: { status: "open" } });
const ids = orders.map((o) => o.customerId);
const customers = await db.customers.findMany({ where: { id: { in: ids } } });
// 2 queries, whatever N isMost data libraries have a built-in way to ask for related records up front. It is worth knowing what yours calls it.
Where it hides
- In templates and serializers that reach for a related record.
- In helper functions that look harmless and are called in a loop.
- In APIs that return nested data.
Questions you will hear in a meeting
- How many queries does this page run?
- Does that number change with the size of the list?
- Are we loading the related records up front?
In an interview
If you write a loop with a database call inside it during a coding round, say so before the interviewer does, and say how you would batch it. Noticing it yourself is worth more than never writing it.