Back to Backend

What is the N+1 query problem in ORMs and APIs?

N+1 happens when you load a collection in one query, then run an extra query per item for a related object - often in nested loops. An API that returns 100 users and triggers 100 follow-up profile queries is slow and can overload the DB. Fixes include eager loading (JOIN or batch `WHERE id IN (...)`), DataLoader-style batching in GraphQL, or denormalized reads for read-heavy paths. The fix is not “add more machines” as the first move; you profile, count queries, and fix the data access pattern.

// N+1 smell (pseudocode)
for (const order of await db.orders.findMany()) {
order.user = await db.users.findById(order.userId); // 1 + N
}

Start simple: try this concept in a tiny project before moving to advanced tools.

ormperformancesql

Want to check this topic right now?

Check this question