An N+1 query pattern issues a separate query inside a loop
Locate the failed assumption, reproduce it, then repair the cause.
What actually caused it
The N+1 query problem occurs when an application first executes one query to fetch N parent records and then executes N individual secondary queries inside an application loop to fetch related child records for each parent. Instead of retrieving the combined dataset in a single database round-trip or a couple of batched operations, the application executes 1 + N separate network trips across the connection. For , fetching 50 users requires 1 initial query followed by 50 queries for their orders, resulting in 51 round trips. In local development where network latency is near zero and datasets are tiny, the loop completes in milliseconds. In production environments where each round trip over the wire incurs latency and connection pool contention, 50 queries can easily delay responses by seconds and saturate the database server.
Minimal reproduction
Looping queries (1 + N round-trips)
const users = await db.all('SELECT id, name FROM users');
for (const user of users) {
user.orders = await db.all('SELECT * FROM orders WHERE user_id = ?', user.id);
}
Issues 1 initial query plus N queries inside the .
The fix
Eliminate the loop queries by fetching the data in a single joined query using SQL JOIN, or by batching the foreign keys using an IN clause (such as SELECT * FROM orders WHERE user_id IN (...)). In ORMs, this is solved by configuring eager loading (such as include in Prisma or populate in Mongoose) rather than accessing lazy-loaded relations inside a loop. When using raw SQL, join the parent and child tables in a single query and group or map the resulting rows in memory. Doing so reduces 1 + N database round-trips down to exactly 1 or 2 round-trips regardless of how many parent records exist, avoiding network latency bottlenecks and drastically reducing load on database connection pools.
Single joined query (1 round-trip)
const rows = await db.all(`
SELECT users.id, users.name, orders.id as order_id, orders.placed_at
FROM users
LEFT JOIN orders ON users.id = orders.user_id
`);
Combines users and orders in exactly 1 round-trip.