N+1 Queries Are Not a Small Bug. They Quietly Kill Latency
N+1 queries rarely explode loudly. They quietly turn an 80ms endpoint into a 1-second one while the source code still looks clean.
0xNN · · 9 min read
N+1 queries are dangerous because they rarely fail dramatically. They quietly turn a fast endpoint into a slow one while the code still looks elegant in review.
The pattern is simple: one query fetches the main list, then N extra queries fetch related data item by item. ORMs often make this easier to write and harder to notice because property access feels harmless while the database pays the price.
Why it gets missed
In local development, small datasets hide the problem. In production, bigger pages and richer relationships multiply the cost: more round trips, more parsing, more planner work, more waiting.
Practical fixes
• Use eager loading when you know related data is needed.
• Batch related lookups instead of fetching one by one.
• Use joins carefully when they reduce waste without exploding result size.
• Monitor query count per request, not just latency.
Recommended reading
• Prisma Docs - Query optimization
• PlanetScale - What is the N+1 query problem?
• Use The Index, Luke!
• PostgreSQL Documentation
The real lesson is that query count is part of system design. If a single page triggers 101 queries, that is not just a database issue. It is a thinking issue.
---
*Written after tracing a clean-looking list endpoint that was quietly making the database work far harder than necessary.*