Performance
N+1 Queries: Why Your AI-Built App Got Slow the Moment Real Data Arrived
The N+1 query pattern AI coding tools generate constantly: how to detect it, why it cripples apps at scale, and the batching and eager-loading fixes.
By AI Production Partner · · 3 min read
The pattern
Fetch a list of 100 orders, then loop through them fetching each customer — 101 queries where 2 would do. That's N+1: invisible with 10 test rows, catastrophic with 100,000 real ones. AI tools generate it constantly because the naive loop is the most statistically likely code for the prompt, and it works perfectly in the demo.
If your app 'suddenly got slow' as data grew, this is the first suspect — it's the cause in well over half the performance engagements we run.
Detection in ten minutes
Turn on query logging (or an APM tool) and load your slowest page. If one page view produces dozens or hundreds of similar queries differing only by ID, you've found it. Sort your endpoints by query count per request — the worst offenders are usually a handful of hot paths.
The fixes, in order of preference
Eager-load the association through your ORM (include/joins/select_related — every ORM has it) so the list and its relations arrive in one or two queries. Where the ORM can't express it, batch by collecting IDs and querying once with IN. Where reads dominate, add caching on top. Typical result: endpoints drop from seconds to tens of milliseconds — and the database bill drops with them.
Then make it stay fixed: add query-count assertions to tests for hot endpoints, so the next AI-generated feature can't quietly reintroduce the loop.