N+1 Problem
ELI5 — The Vibe Check
The N+1 problem is when your code makes 1 query to get a list of things, then N more queries to get related data for each thing. Fetching 100 users and their posts? That's 1 + 100 = 101 database queries. Your database is crying. Use eager loading or batch loading to fix it.
Real Talk
The N+1 query problem occurs when an application executes one query to retrieve N records, then N additional queries to fetch related data for each record. It's a common ORM anti-pattern that causes severe performance degradation at scale. Solutions include eager loading (JOIN), batch loading (WHERE IN), DataLoader, and query optimization. Detectable via query logging and APM tools.
Show Me The Code
// N+1 Problem (BAD) - 101 queries
const users = await User.findAll(); // 1 query
for (const user of users) {
user.posts = await Post.findByUserId(user.id); // N queries
}
// Fixed - 2 queries
const users = await User.findAll({ include: [Post] }); // eager load
When You'll Hear This
"We had a 2-second API response caused by an N+1 query loading 500 users with their roles." / "Always check for N+1 queries when using an ORM — they're the most common performance killer."
Related Terms
Batch Loading
Batch loading is fetching many things in one call instead of one at a time. Instead of asking 'give me user 1... give me user 2... give me user 3...
Data Loader
DataLoader batches and caches database calls in GraphQL. Without it, fetching 100 users with their posts makes 101 database queries (the N+1 problem).
Eager Loading
Eager loading fetches all the related data you need upfront in one or two queries.
Query Optimization
Query optimization is the art of making slow database queries fast. Add an index here, rewrite that subquery as a JOIN, fetch only the columns you need.