Database Integration with PostgreSQL and PrismaLesson 5.4
N+1 query problem in APIs and how to fix it with Prisma
N+1 query problem, eager loading, include, select with nested relations, query count, dataloader pattern, performance impact
The N+1 Query Problem
The N+1 problem is one of the most common API performance bugs. It happens when you fetch a list of N items and then make a separate database query for each item's related data — N+1 total queries.
The Problem
// BAD — N+1: 1 query for posts + 1 query per post for author
const posts = await prisma.post.findMany();
for (const post of posts) {
post.author = await prisma.user.findUnique({ where: { id: post.authorId } });
// This fires a separate SQL query for EVERY post
}The Fix — Eager Loading with include
// GOOD — 1 query (or 2 with Prisma's batching)
const posts = await prisma.post.findMany({
include: {
author: {
select: { id: true, name: true } // only fields you need
}
}
});
// posts[0].author.name is available — no extra queriesChecking Query Count
// Enable query logging during development
const prisma = new PrismaClient({
log: ['query'] // prints every SQL statement to stdout
});Enable query logging in development and count the number of queries per request. If a list endpoint fires more than 2-3 queries, investigate. With 100 posts, an N+1 bug turns one endpoint into 101 database calls — a 100x performance hit.
