categories.database Intermediate
What Is the N+1 Query Problem? How to Detect and Fix It?
N+1 Query Problem
What Is It?
Fetch N parent records in 1 query, then execute 1 query per record for children → N+1 total queries
Example (common ORM pitfall)
// Fetch 100 Users (1 query)
const users = await User.findAll()
// Fetch posts for each user (100 queries!)
for (const user of users) {
const posts = await user.getPosts()
}
// Total: 101 queries
Solutions
1. Eager Loading
// Sequelize
const users = await User.findAll({ include: [Post] })
// Only 2 queries (1 for users + 1 for posts WHERE id IN (...))
2. SQL JOIN
Fetch all data in a single query using a JOIN
3. DataLoader (GraphQL)
Batch-collect all IDs, execute one query, distribute results
Detection
- Enable SQL logging in dev to spot repeated query patterns
- Use APM tools (Datadog, New Relic) to track query counts
- Bullet gem (Rails) auto-detects N+1
Interview bonus: Eager loading can also backfire—over-eager loading with too many JOINs may slow down queries. Selectively load only the associations you need.
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
