P50 28s Analyze →
↩ All field notes
Querk · Field notes

Spotting N+1s in Your ORM Before They Page You at 3 AM

Published November 18, 2026 · Querk — Postgres review pipeline

An application executes one query to retrieve a collection of parent records—say, 50 orders. Then, for each order, the ORM issues a separate query to load related data, such as the customer or line items attached to that order. The result is 51 queries instead of one or two. Under light traffic, the endpoint might return in 50 milliseconds. Under load, with concurrency and larger result sets, the same endpoint can stretch past two seconds as the database processes dozens or hundreds of round trips.

The pattern often hides in development. A small local dataset produces negligible latency, so the issue does not surface until production traffic exposes it.

How the N+1 Pattern Emerges

The root cause is deferred association loading. The ORM fetches the parent collection first, then resolves each related record individually as the application iterates over the results. What looks like a single data access in application code becomes N+1 round trips to PostgreSQL, where N is the number of parent rows.

Detecting N+1s by ORM

Each ORM reveals the problem through repeated, nearly identical queries against the same related table.

In Rails, ActiveRecord issues one query per association unless the developer uses `includes`, `eager_load`, or `preload`. Scanning the log for repeated `SELECT` statements against `customers` or `order_items` after an `orders` query is a reliable signal.

Django’s ORM behaves similarly when foreign-key or reverse-relationship attributes are accessed inside a loop. `select_related` covers single-valued relationships, while `prefetch_related` handles collections. A query count that scales linearly with result-set size indicates the problem.

Hibernate relies on lazy loading by default. Accessing a proxy or collection outside the original transaction can trigger individual select statements per entity. `JOIN FETCH` in HQL or `@EntityGraph` annotations consolidate the work, though joining multiple collections can duplicate rows.

Prisma performs one query per `findMany` call, but nested relations accessed afterward can generate additional round trips. Using `include` or `select` at the top level loads related records in a single additional query rather than one per parent row.

Fixing the Query Explosion

The standard remedy is eager loading: instructing the ORM to retrieve related records up front instead of deferring them. In SQL terms, this often replaces multiple filtered scans with a single join or an `IN` clause.

Developers should verify the fix with `EXPLAIN ANALYZE` rather than assuming fewer queries means better performance. A poorly written join can produce a cartesian product or force a sequential scan that is slower than the original N+1. Indexing the foreign keys involved in the association is equally important; without them, eager loading may simply shift the cost from query count to row examination.

Keeping Regressions Out of Production

Because N+1 issues scale with data volume, code review alone is insufficient. Teams should instrument test suites to assert query counts and monitor slow-query logs in staging. Repeated identical queries against the same table, especially when execution time grows with concurrency, warrant investigation before deployment.

Observability tools that parse PostgreSQL logs can highlight these patterns automatically. Querk, for example, surfaces repeated query shapes and execution trends so teams can spot an emerging N+1 before it triggers an alert at 3 AM.

Paste your slowest query — 3 free reviews, no signup. Index DDL, rewrites, write-path impact, and a verification command back in ~30 seconds. Analyze a query →