Fix N+1 Database Query Bottlenecks in Web APIs
How fetching child records inside a loop turns 1 request into 101 queries, and how JOINs or IN-clauses eliminate the bottleneck.
By the end of this tutorial you will know:
- How to spot an N+1 query bottleneck in your API logs
- Why 100 tiny 2ms queries can still stall an endpoint for 200ms+
- How to collapse N+1 queries into 1
JOINor 2 batchedIN (...)queries
Prerequisites: Basic SQL (SELECT, JOIN, WHERE).
1. The big idea
Suppose an API endpoint lists 50 blog posts and shows each author's name. You run 1 query to fetch the 50 posts, and then—inside a for loop—you run 1 query per post to fetch its author. That is 1 + 50 = 51 database round-trips for a single page load. At 500 posts, it is 501 round-trips!
2. Reproducing the N+1 pattern
-- Query 1:
SELECT id, title, author_id FROM posts LIMIT 50;
-- Repeated 50 times in a loop:
SELECT id, name FROM users WHERE id = $1;3. The fix: eager loading (JOIN or batched IN)
Fetch all the needed data in one JOIN query (or two queries using WHERE id = ANY($1) / WHERE id IN (...)).
SELECT p.id, p.title, u.name AS author_name
FROM posts p
JOIN users u ON u.id = p.author_id
ORDER BY p.created_at DESC
LIMIT 50;In ORMs:
- SQLAlchemy:
select(Post).options(selectinload(Post.author)) - Prisma:
prisma.post.findMany({ include: { author: true } }) - Go
database/sql: CollectauthorIDsand runSELECT id, name FROM users WHERE id = ANY($1).
Check your endpoint query count before and after switching to JOIN or IN (...). It should drop from N + 1 queries down to 1 or 2 constant queries regardless of list size.
4. Common pitfalls
| Mistake | Symptom | Fix |
|---|---|---|
| Lazy-loading ORM relationships in a template/serializer | Endpoint slows down linearly as rows grow | Use selectinload, include, or explicit JOIN |
Missing index on foreign key (posts.author_id) | Fast query count, slow JOIN | Add CREATE INDEX idx_posts_author_id ON posts(author_id) |
5. What you learned
You now know how N+1 query loops happen, how to spot them in dev logs, and how JOINs or batched IN queries keep API response times flat.