Imagine loading a page that displays 100 users.
Simple, right?
But what if your backend makes 101 database queries just to display them?
This is called the N+1 query problem.
Here's a simplified example:
const users = await db.user.findMany();
for (const user of users) {
user.posts = await db.post.findMany({
where: { userId: user.id }
});
}
If you have 100 users, this can execute:
- 1 query to fetch users
- 100 queries to fetch their posts Total: 101 queries. That's a lot of unnecessary database communication. A better approach is to fetch the posts for all users in one query: const users = await db.user.findMany();
const posts = await db.post.findMany({
where: {
userId: { in: users.map(user => user.id) }
}
});
Now you've reduced the example to 2 queries instead of 101.
You still need to group the posts by user before returning the response, but you've eliminated the repeated database calls.
The actual improvement depends on your database, data size, indexes, and query patterns.
The lesson?
Sometimes your API isn't slow because your code is complicated.
It's slow because your code keeps asking the database the same kind of question again and again.
Next time an API feels slow, check how many database queries it executes.
You might discover that the biggest performance improvement requires less querying, not more code.
Top comments (0)