June 23, 2026

Finding and Fixing an N+1 Query Problem

The fix starts by proving the query shape, not by guessing at the slow line.

The smell

An endpoint feels slow, but the code looks fine. The real bug is often the query shape: one parent query followed by a query for every child row.

That is an N+1 problem.

The fix pattern

First count the queries. Then identify the relation causing fan-out. Only then choose the fix: eager loading, prefetching, an aggregate query, or a new read model.

The lazy fix is the root-cause fix. Patch the shared query path once instead of adding guards around every caller.

The lesson

Performance work is not vibes. Measure the query count, change the query shape, then measure again.