Systems & Backend

N+1 Query Problem

A performance bug where fetching a list then looping to fetch each item’s details fires 1 + N queries instead of one.

The N+1 query problem is a common performance bug: you run one query to fetch a list of N items, then a separate query for each item to load related data — 1 + N round trips where a single join or batched query would do.

Worked example: loading 50 blog posts (1 query) then fetching each post’s author in a loop (50 queries) is 51 queries; replacing the loop with a single “fetch all authors WHERE id IN (…)” or a join makes it 2 or 1. Gotcha: ORMs cause this silently through lazy loading — the code looks innocent (post.author) but each access hits the database; the fixes are eager loading / joins or a batch loader that coalesces the N lookups.