,

N+1 Queries: Find and Fix Them in Production

Learn what causes N+1 queries, how to confirm them with PostgreSQL or MySQL statistics and request traces, and how to fix eager loading and batching in Django, Rails, Hibernate, and Prisma.

N+1 query pattern with separate per-record database calls compared with a batched fetch.

An N+1 query problem occurs when one query fetches a list and the application issues one additional query for each result. A page of 500 orders can therefore trigger 501 database queries just to load each orderโ€™s customer. This often comes from lazy-loaded ORM relationships, but explicit queries inside a loop can cause the same problem.

Individual queries can be fast while their combined round trips make a request slow. This guide shows how to find suspicious query counts in PostgreSQL and MySQL, confirm the pattern in request traces, and fix it with eager loading or batching in Django, Rails, Hibernate, and Prisma.

Key takeaways

  • N+1 is a query-count problem: one list query followed by a query for each result.
  • Use database statistics to find candidates, then confirm repeated fetching within a request trace.
  • Fix the application fetch plan with eager loading or batching, and test realistic page sizes.
  • Caching and connection pooling can reduce other costs but do not inherently remove an ORM loop.

What is the N+1 query problem?

As a starting point, take two tables, orders and customers, one customer per order. You need a page of 500 orders with the customer name beside each one. That page is where the problem shows itself.

# Django: accessing an unloaded customer on each Order instance.
orders = Order.objects.order_by("-created_at", "-id")[:500]
for order in orders:
    print(order.customer.name)

# Simplified SQL shapes (actual aliases and placeholders vary):
# SELECT ... FROM orders ORDER BY created_at DESC, id DESC LIMIT 500;
# SELECT ... FROM customers WHERE id = ?;  -- first order's customer
# SELECT ... FROM customers WHERE id = ?;  -- next order's customer
# ... up to 500 customer queries, with different bound values

That is 501 statements: one for the list and 500 for the customers. In the developer’s mental model, order.customer reads as a property access. Whenever the relation is not loaded, the ORM turns that access into a round trip.

Nested relationships can increase the count further. With 500 orders and 20 items per order, loading each orderโ€™s item collection separately costs 500 queries; loading one product per item can add another 10,000. Including the initial order query gives 10,501 statements, assuming every access needs a database fetch. Shared entities already in an ORM cache can reduce that total.

Repeated requests add network and database overhead even when each query returns one row. Prepared statements can reduce parsing and planning work, but they do not remove the applicationโ€™s per-row database calls. Optimize both the number of calls and the amount of data fetched.

Why it hides in production

An N+1 pattern can escape a slow-query investigation when each statement finishes below the logging threshold. Short-lived queries can also disappear between activity snapshots. Request traces and query counts reveal the cumulative work that a per-statement latency threshold can miss.

Network distance compounds the problem. As an illustrative calculation, 500 sequential round trips at 0.3 ms each add roughly 150 ms of network latency; at 1 ms each, they add roughly 500 ms. Actual latency depends on topology and concurrency. A connection pooler can reduce connection overhead, but it does not remove N+1 calls; waiting for a free connection can add further delay.

Compare frequency and total execution time together. A statement averaging 0.2 ms over 4 million calls accumulates 800 seconds of execution time; one averaging 900 ms over 400 calls accumulates 360 seconds. These are elapsed execution totals, not measurements of CPU consumption. Sorting only by mean duration misses the first workloadโ€™s aggregate cost.

Detecting N+1 queries in production

Use pg_stat_statements to shortlist frequently executed statement shapes. Enable it in shared_preload_libraries (requiring a restart if it is not already loaded), enable query identifiers, and create the extension in the database used for inspection. On managed services, follow the providerโ€™s setup procedure. The query below uses fields available in PostgreSQL 16 and 17.

-- PostgreSQL 16/17; requires pg_stat_statements to be enabled.
SELECT
  userid,
  dbid,
  queryid,
  toplevel,
  calls,
  rows,
  round(rows::numeric / nullif(calls, 0), 2) AS rows_per_call,
  round(mean_exec_time::numeric, 3) AS mean_ms,
  round(total_exec_time::numeric, 1) AS total_ms,
  left(query, 90) AS query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database
              WHERE datname = current_database())
  AND query NOT ILIKE '%pg_stat_statements%'
ORDER BY calls DESC
LIMIT 20;

pg_stat_statements has no application_name column. Its aggregates are separated by database, user, query identifier, and top-level status. Use request traces for service and endpoint attribution. application_name in pg_stat_activity can help inspect current sessions, but cannot retroactively split accumulated statistics by application.

Reading the numbers

The following synthetic snapshot illustrates why both call count and execution time matter. The five displayed rows total 516,851.6 ms; assume all statements in the measurement interval total 590,000 ms. These totals are cumulative database execution time, not the length of the observation window.

-- Synthetic sample: assumed total execution time = 590,000 ms
 calls   | rows_per_call | mean_ms | total_ms  | query
---------+---------------+---------+-----------+---------------------------------
  30,000 |          1.00 |   0.180 |   5,400.0 | SELECT ... FROM customers WHERE id = $1
  30,000 |          1.00 |   0.240 |   7,200.0 | SELECT ... FROM order_items WHERE order_id = $1
  20,000 |          1.00 |   0.150 |   3,000.0 | UPDATE orders SET status = $1 WHERE id = $2
  10,000 |          3.00 |   0.412 |   4,120.0 | SELECT ... FROM orders ORDER BY created_at DESC LIMIT $1
   1,204 |          1.00 | 412.900 | 497,131.6 | SELECT ... FROM reports GROUP BY ...

The reporting query accounts for about 84.3% of the assumed total execution time. Sorting by calls instead puts the customer and item lookups first. Both views are useful: the report dominates execution time, while frequent small queries deserve a check for excessive round trips. Neither ranking proves N+1.

The customer and item statements each have three times as many calls as the parent listing statement. That is three calls per listing execution on average, not three calls per order. Different endpoints or background jobs may share these statement shapes. Confirm which calls belong to the same request before interpreting the ratio.

The 60,000 child lookups accumulate 12,600 ms, about 2.1% of the assumed total execution time. Database execution statistics do not measure the full network and application time of those requests. A request trace is needed to see their contribution to endpoint latency.

An index may make each lookup faster without reducing how often the application calls it. Measure query count per request as well as latency so an execution-plan improvement does not conceal an unresolved N+1 pattern.

A detection heuristic

A useful signal is query count growing with the number of parent records returned by one endpoint. Compare realistic small and large pages in traces or a staging test. A high aggregate call count or a fast mean execution time alone cannot distinguish N+1 from legitimate frequent lookups. Background jobs, shared queries, and ORM caches can all affect the ratios.

For before-and-after checks, compare counter deltas over equivalent traffic intervals, checking for resets or evicted entries. Avoid resetting shared production statistics just to test a code change. pg_read_all_stats does not grant reset permission; resetting requires a superuser or an explicit function EXECUTE grant. Add a query-count regression test for the endpoint so increasing page size does not silently restore per-row fetching.

On MySQL 8

On MySQL 8.0, use performance_schema.events_statements_summary_by_digest to inspect normalized statement counts. Verify that Performance Schema, the relevant statement instruments, and digest collection are enabled; do not assume every deployment uses the defaults.

-- MySQL 8.0; requires Performance Schema and digest collection.
SELECT
  SCHEMA_NAME,
  DIGEST,
  COUNT_STAR AS calls,
  ROUND(AVG_TIMER_WAIT / 1000000000, 3) AS mean_ms,
  ROUND(SUM_TIMER_WAIT / 1000000000000, 3) AS total_s,
  LEFT(DIGEST_TEXT, 90) AS digest_text
FROM performance_schema.events_statements_summary_by_digest
WHERE DIGEST_TEXT LIKE 'SELECT%'
ORDER BY COUNT_STAR DESC
LIMIT 20;

Keep SCHEMA_NAME with each digest so unrelated databases are not mixed. The digest summary has no per-request or application identity, so correlate candidates with traces. The general query log contains individual statements and can help a controlled investigation, but adds overhead and can expose literal values; the digest summary is a better starting point for aggregate counts.

On the application side

In staging, instrument a request with a realistic row count. Djangoโ€™s connection.queries is available with DEBUG=True, which should not be enabled in production for this investigation. Rails offers sql.active_record notifications, and Hibernate can collect statistics. Look for avoidable per-row relationship fetching rather than treating all linear query growth as a bug.

The APM view

Use request traces alongside database observability to connect statement frequency to an endpoint. A common N+1 trace shows a parent listing query followed by repeated child-query shapes within the same request. Verify the relationship and call site; tracing samples or span limits can hide some calls. Avoid collecting sensitive SQL parameter values just to identify the pattern.

From signal to code site

  1. Find high-call-count statement shapes in database statistics.
  2. Use request traces to associate repeated queries with an endpoint; aggregate statistics do not identify the request.
  3. Check how the query count changes with page size and identify the ORM relationship or explicit query loop.
  4. Apply eager loading or batching while preserving filtering, pagination, and required fields.
  5. Compare query-count and execution-time deltas under equivalent traffic; do not require a production-wide statistics reset.
  6. Measure endpoint p95/p99 latency, database time, rows transferred, and application memory. Add a query-count regression test.

The fixes, per framework family

The main remedies are eager loading, batched child lookups, and appropriate joins. Choose based on the relationship and the data the page needs. The table assumes one parent query and one requested relationship with no additional lazy loads.

Framework familyDefault behaviorFixCalls after fix
Django ORMUnloaded relations can issue queries; an instance can cache a loaded related objectselect_related() for FK/O2O joins, prefetch_related() for M2M and reverse FK1, or 2 with prefetch_related
Rails 8.0 (Active Record)Lazy association loading on first access, cached per record after thatincludes() / preload() / eager_load()1 with eager_load, 2 with preload
Hibernate ORM 6.6 / JPAStandard JPA mappings: to-one EAGER, collections LAZY; either needs a deliberate fetch planExplicit LAZY mapping where appropriate, then join fetch or configured batch fetching1 with a suitable to-one fetch join; ideally 1 + ceil(U/B) with batches of B for U unloaded targets
Prisma 6 (Node)Relation fields absent from include / select are not loaded; looping findUnique per id is the usual N+1include, or findMany({ where: { id: { in: [...] } } })Often 1 with a relation join or 2 for one separately loaded relation; verify the query log

Django: select_related and prefetch_related

# Before: up to 501 queries for 500 orders with unloaded customers.
orders = Order.objects.order_by("-created_at", "-id")[:500]
for order in orders:
    print(order.customer.name)

# After: one joined query when this queryset is evaluated.
orders = Order.objects.select_related("customer").order_by("-created_at", "-id")[:500]
for order in orders:
    print(order.customer.name)

# Collection alternative: two queries for a nonempty order page.
orders = Order.objects.prefetch_related("items").order_by("-created_at", "-id")[:500]
for order in orders:
    for item in order.items.all():
        print(item.id)

select_related() joins single-valued relationships. prefetch_related() loads collections separately and assembles them in Python. For a nonempty order page, prefetching one item collection usually uses two queries. If narrowing fields with only(), retain the linking foreign key: Prefetch("items", queryset=Item.objects.only("id", "order_id", "product_id")). Accessing other deferred fields can add queries. See the Django QuerySet reference.

Rails: includes

# Before: up to 501 queries for 500 orders with unloaded customers.
orders = Order.order(created_at: :desc, id: :desc).limit(500)
orders.each { |o| puts o.customer.name }

# After: preload uses two queries for a nonempty page.
orders = Order.preload(:customer).order(created_at: :desc, id: :desc).limit(500)
orders.each { |o| puts o.customer.name }

includes chooses between preload (two queries, joined in memory) and eager_load (one LEFT OUTER JOIN). It switches to a join when a condition references the included table. So where(customers: { region: "eu" }) flips it. Force the choice with preload(:customer) or eager_load(:customer) when the table is large. Either form ends the loop: 1 call with eager_load, 2 with preload.

Rails caches a loaded association on its record, and Django also caches non-callable related-object attributes on an instance. Neither behavior eliminates the first fetch across many separate parent records. Do not assume Rails makes the same N+1 pattern inherently cheaper than Django.

Hibernate / JPA: fetch joins and batch size

// Assumes customer is explicitly mapped @ManyToOne(fetch = FetchType.LAZY).
// Before: accessing unloaded customers can issue per-customer queries.
List<Order> orders = em.createQuery(
    "from Order o order by o.createdAt desc, o.id desc", Order.class)
    .setMaxResults(500)
    .getResultList();
for (Order o : orders) {
    System.out.println(o.getCustomer().getName());
}

// After: fetch the to-one relationship in the query.
// LEFT JOIN retains orders whose customer is optional.
List<Order> ordersWithCustomers = em.createQuery(
    "select o from Order o left join fetch o.customer order by o.createdAt desc, o.id desc",
    Order.class)
    .setMaxResults(500)
    .getResultList();

// Alternative: set this Hibernate property in your configuration.
// hibernate.default_batch_fetch_size=100
// For Spring Boot: spring.jpa.properties.hibernate.default_batch_fetch_size=100

With standard JPA mappings, Hibernate 6.6 defaults @ManyToOne and @OneToOne to EAGER. Explicit LAZY mappings still need an appropriate fetch plan. Batch fetching uses @BatchSize or hibernate.default_batch_fetch_size; bytecode enhancement does not itself enable batching. For 500 distinct eligible associations and batch size 100, the idealized total is six queries: one parent query plus five batches.

The fetch-join trap

Avoid paginating a collection fetch join: Hibernate 6.6 may fetch all matching results and apply the limit in memory. Page the parent IDs first, then fetch the required associations, or use batch fetching. The Hibernate user guide documents this behavior and hibernate.query.fail_on_pagination_over_collection_fetch, which can make unsafe collection pagination fail explicitly.

For a to-one association, the number of batched lookups depends on distinct unloaded target IDs. For a collection, it depends on unloaded owner collections. Actual counts also depend on cache state and the persistence context; verify the emitted SQL.

Prisma / Node: include

// Before: 1 + N (Prisma 6)
const orders = await prisma.order.findMany({ take: 500 });
for (const order of orders) {
  const customer = await prisma.customer.findUnique({
    where: { id: order.customerId },
  });
}

// After: include removes the per-row loop
const orders = await prisma.order.findMany({
  take: 500,
  include: { customer: true },
});

// Hot path: select only what the page renders
const orders = await prisma.order.findMany({
  take: 500,
  select: {
    id: true,
    createdAt: true,
    customer: { select: { name: true } },
  },
});

Prisma does not implicitly lazy-load relations. Use nested include/select or a batched findMany with an in filter. Query count depends on the relation load strategy, connector, and version. Compatible findUnique() calls in the same event-loop tick may be automatically batched; the sequential awaited loop above should not rely on that. A parent relation filter alone does not load the relation. Confirm with query logging. See Prismaโ€™s N+1 guidance.

A join is not always the answer, and the wider set of database optimization techniques covers the cases where a rewrite beats a join. So on a large child table where you need three columns, two batched queries can beat one wide join. Measure both against the same row count before you commit.

Can caching or connection pooling fix N+1?

Caching can reduce repeated database execution, but does not inherently remove the applicationโ€™s per-row fetch pattern. Fix the query shape or batching first, then evaluate caching for the remaining workload.

A cache hit may avoid a database lookup, while a miss, cold cache, or bypass path still executes it. A remote per-row cache lookup can also leave many network calls. Evaluate correctness, invalidation, hit rate, and cold-cache latency. Connection pooling addresses connection reuse and concurrency rather than combining the applicationโ€™s queries. Neither is a substitute for an appropriate ORM fetch plan.

Where Cast AI fits

Cast AI Database Optimizer provides continuous visibility into PostgreSQL and MySQL workloads. Its read-only Performance Advisor analyzes queries in real time, with no sampling, and uses workload context, including query frequency, to prioritize optimization opportunities.

The Performance Advisor recommends missing indexes, flags unused ones, and proposes query rewrites, ranked by the database time they would reclaim. Recommendations include the SQL, an explanation, and before-and-after plan comparisons showing projected impact. You review and apply the changes; the advisor does not change your schema or application code.

You can adopt DBO without migrating your database or rewriting application code. Start with the read-only agent; when ready, route traffic through the optional proxy by updating the connection string to enable caching and connection pooling. These capabilities can reduce repeated database reads and connection overhead. Correcting an N+1 fetch pattern remains an application-level task: use request traces to confirm the loop, implement eager loading or batching, and measure the result.

Start a free trial with read-only analysis to investigate your database workload, then validate application changes against your own request traces and traffic.

FAQ

What does N+1 mean in SQL?

N+1 means one query fetches a list and the application runs another query for each result. Loading 500 orders and then fetching one customer per order can require 501 queries.

How do I detect N+1 queries in production?

Find frequently executed statement shapes in PostgreSQL pg_stat_statements or MySQL digest statistics, then inspect request traces. Confirm that repeated child queries belong to the same endpoint and that their count grows with the number of parent records. High aggregate call count alone is not proof.

Does eager loading always fix N+1?

Eager loading can remove per-row fetching for the relationships it loads, but accessing other unloaded or deferred data can add queries. A wide collection join can also multiply rows. Choose joins or batched prefetching to match the data and pagination requirements, then verify the SQL.

Can caching or connection pooling fix N+1?

Not inherently. Cache hits can avoid database work, while misses still follow the application fetch pattern. Connection pooling reuses connections but does not combine per-row queries. Fix the ORM loop or batch the lookups, then measure caching and pooling separately.

Which ORMs can produce N+1 queries?

Django, Rails, and Hibernate can issue repeated queries when relationships are fetched per record. Explicit queries in a loop can create the same problem in Prisma or plain SQL. Fetching defaults, identity maps, and batching behavior differ, so inspect the queries emitted by your version.

Cast AI โ€บ Blog โ€บ N+1 Queries: Find and Fix Them in Production