The N+1 query problem, and why your ORM hides it
One query for the list, then one more per row, forever
Key takeaways
- Loop bodies that touch the database are the smell.
- Log your SQL in development — the count is the tell.
- Fix it by fetching related rows in one query, not by caching the symptom.
You fetch 50 posts. Then, for each one, you read its author. That is 1 + 50 = 51 queries where 2 would do. It looks harmless because each individual query is fast. The problem is t…