44. Why is this endpoint slow when a user has many orders, and how do you fix it?
MediumDebugging & production
Technical
const orders = await db.query('SELECT * FROM orders WHERE user_id = ?', [userId]);
for (const order of orders) {
order.items = await db.query('SELECT * FROM items WHERE order_id = ?', [order.id]);
}
return orders;Show model answer
It runs one query for the orders and then one more query per order to load its items: the N+1 query problem. With 500 orders that is 501 round trips.
Fix it by loading all items in one query (WHERE order_id IN (...)) or with a join, then grouping in memory, or by using the ORM's eager-loading feature. Add pagination so the response size is bounded, and watch query counts in tests or monitoring.