Skip to content

N+1 Problem

Medium — good to knowBackend

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."

Made with passive-aggressive love by manoga.digital. Powered by Claude.