SevyDevy

N+1 Query Problem Explained: Lazy Loading, Eager Loading and DataLoader

, Last updated , 19 min read

Summary

  • The N plus one query problem, usually written N+1, is when code runs 1 query to fetch a list, then 1 more query for every row in it.
  • It hides behind lazy loading: the ORM (the library that turns database rows into objects) quietly fetches related data the moment your code touches it.
  • You spot it in the query log, the list of SQL your app sent. The same SELECT, the SQL command that reads rows, repeats again and again with only the ID changing.
  • The fix is to ask for related rows up front. Use a join (one query that combines two tables), or eager loading such as selectinload, select_related, prefetch_related or includes. In GraphQL, use DataLoader, a small library that batches many lookups into one query.
  • Beginners can stop after the log section. Engineers get measured counts on SQLAlchemy 2.1.6, Django 6.1.2 and DataLoader 2.2.3, plus the new Django 6.1 fetch modes and the traps we hit.

What goes wrong when a page loads a list through an ORM?

The page sends far more database queries than you think, a pattern called the N plus one query problem. It gets slower as your data grows, and one innocent loop can turn 1 query into 101.

Picture a common setup. A food-delivery app has an admin page that lists the 50 latest orders, each with the customer's name and the dishes ordered. The setup is made up, but the pattern is real. On a laptop with 5 test orders the page felt instant. In production it showed 50 orders and slowed down, yet nobody had changed the code.

The code looked like one query: fetch 50 orders, loop, print each customer's name and dishes. Behind the loop, the N plus one query problem was at work. We rebuilt this page on SQLAlchemy and Django, and the plain loop sent 101 queries. After the fixes in this guide, it sent 2.

Which words do you need before fixing slow ORM queries?

Six terms carry the whole guide. Each one is short, and the rest of the guide uses them often.

  • ORM (object-relational mapper): a library that turns database rows into objects in your code. SQLAlchemy, the Django ORM and Rails Active Record are ORMs.
  • Relationship: a link between tables, like each order pointing to one customer. Many-to-one means many orders share one customer. One-to-many means one order has many items.
  • Round trip: one message from your app to the database and the answer coming back. Every query costs at least one round trip.
  • Lazy loading: the ORM waits until your code touches a related object, then runs a query to fetch it. It is the default in all three ORMs here.
  • Eager loading: you tell the ORM which related data you will need, so it fetches it up front in one or two queries.
  • Query log: a record of every SQL statement your app sent. It is the main tool for finding the problem.

What is the N plus one query problem?

The N plus one query problem is when one query fetches N rows and your code then runs one extra query per row. The total is N plus 1 queries, where 1 or 2 would do.

In the orders page, N is 50. One query fetches 50 orders. Then reading each order's customer sends another query, 50 times. The Django docs describe exactly this pattern and call it the N+1 queries problem.

Think of shopping for a recipe with 50 ingredients. The slow way is to walk to the shop, buy one ingredient, walk home, and repeat 50 times. The fast way is to write a list and make one trip. Each walk is a round trip, and the walking, not the buying, is what costs you.

Where the picture breaks: one big trip is not always cheaper in a database. A join can return the same order data many times over, as a later section measures.

How one loop becomes 51 queries

Notice that the database is asked the same question shape 50 times. Only the customer ID changes.

Diagram connections:

  • Page code loops orders to Query 1: 50 orders (Fetch the list)
  • Query 1: 50 orders to Touch order.customer (Each order in turn)
  • Touch order.customer to Lazy query per order (Not in memory)
  • Lazy query per order to Total: 1 + 50 = 51 (Repeated 50 times)
  • Page code loops orders: for order in orders: show customer name
  • Query 1: 50 orders: SELECT orders ... LIMIT 50
  • Touch order.customer: Customer not loaded yet
  • Lazy query per order: SELECT customer WHERE id = ?
  • Total: 1 + 50 = 51: 51 round trips for one page

Why does one line of ORM code send so many queries?

Because related objects are lazy by default. The ORM loads only the table you asked for, and fetches each relationship the first time your code reads it.

The SQLAlchemy docs say plainly that all relationships lazy load by default. Django and Rails behave the same way out of the box. Lazy loading is a sensible default, because it never fetches data you do not use.

The trouble is the loop. A template (the page layout) or a serializer (code that turns objects into JSON) reads order.customer.name inside a loop, and each read is a separate query. Nothing in that line looks like database work, which is why the problem hides so well.

We rebuilt the orders page and counted every query. Reading only the customer names sent 51 queries. Reading names and item lists sent 101: 1 for orders, 50 for customers and 50 for item lists.

A detail that hides the problem in testing

On SQLAlchemy 2.1.6 the lazy loop sent 6 queries, not 51. Django 6.1.2 sent 51 for the same data.

The reason is a SQLAlchemy shortcut. A session keeps an identity map, a record of loaded objects by primary key, the row's unique ID. For a simple many-to-one link, it skips the query when the related object is already in the session.

So a test database with a few repeated customers can look fine on SQLAlchemy and fall over in production, where most customers are different.

How do you spot N+1 queries in a query log?

Turn on SQL logging, load the page once and look for the same SELECT repeated many times with only a parameter changing. That repeated shape is the signature.

A slow page alone does not prove N+1. A missing index or one huge query can also be slow. The log tells you which it is.

  1. Turn on the log

    In SQLAlchemy pass echo=True to create_engine, or set the sqlalchemy.engine logger to INFO. In Django set DEBUG to True and read connection.queries. Other ORMs have a similar switch.

  2. Load the page once

    Clear the log first, then request the slow page a single time. Mixed traffic makes the pattern hard to see.

  3. Count the statements

    Count how many SQL statements one page view sent. Compare it with the number of rows on the page.

  4. Find the repeated shape

    Look for one SELECT, such as a customer lookup by ID, that appears once per row with a different ID each time.

  5. Trace it to the loop

    Find the template, serializer or loop that reads that relationship. That line is where the eager loading option goes.

With echo=True on SQLAlchemy 2.1.6, three orders printed one SELECT on orders, then three copies of SELECT customer.id, customer.name FROM customer WHERE customer.id = ?. Only the bound values changed: 1, then 2, then 3.

Django logs look the same. The first statement read the shop_order table, then each following statement read shop_customer WHERE id = 1, then 2, and so on. Django's connection.queries shows the SQL with values filled in, so the IDs show directly.

For engineers

Beginners can stop here. You now know what N+1 is, why ORMs cause it and how to find it in a log. The rest is for engineers: fixes per ORM with measured counts, Django 6.1 fetch modes and DataLoader for GraphQL.

How do joins and eager loading fix N+1 queries?

They fetch the related rows up front, in one or two queries, instead of one per row. There are two shapes: a join in the same query, or a second query that loads all related rows with IN.

A join is SQL that combines rows from two tables in one result. An IN query is a second SELECT that asks for many IDs at once, such as WHERE customer_id IN (1, 2, 3).

Two ways to load related rows up front

Both paths replace 50 small queries. The join returns one wide result; the IN path keeps two narrow ones.

Diagram connections:

  • Orders page to Many-to-one or list? (Plan the loading)
  • Many-to-one or list? to One query with a JOIN (One parent per row)
  • Many-to-one or list? to Second query with IN (Many children per row)
  • One query with a JOIN to ORM matches rows (Wide result)
  • Second query with IN to ORM matches rows (Narrow result)
  • Orders page: Needs orders, customers and items
  • Many-to-one or list?: Pick the loader by relationship
  • One query with a JOIN: Orders joined to customer rows
  • Second query with IN: Items WHERE order_id IN (1..50)
  • ORM matches rows: Puts customers and items on each order
Query counts for the 50-order page, measured on 30 October 2026 (Rails figures are from its guide, not run)
ORM and versionLazy loopLoad customersLoad item listsMeasured total
SQLAlchemy 2.1.6101 queriesjoinedload: same query, LEFT OUTER JOINselectinload: one IN query2 queries
Django 6.1.2101 queriesselect_related: same query, JOINprefetch_related: one IN query2 queries
Rails 8.1 Active RecordGuide: 11 queries for 10 booksincludes, preload or eager_loadincludes, preload or eager_loadGuide: includes gives 2 queries

SQLAlchemy: joinedload and selectinload

Here is the whole orders page as a runnable script. It counts SQL statements with an event hook, a function SQLAlchemy calls just before it sends each statement.

python
from sqlalchemy import ForeignKey, create_engine, event, select
from sqlalchemy.orm import (DeclarativeBase, Mapped, Session, mapped_column,
                            relationship, joinedload, selectinload)


class Base(DeclarativeBase):
    pass


class Customer(Base):
    __tablename__ = "customer"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]


class Order(Base):
    __tablename__ = "orders"
    id: Mapped[int] = mapped_column(primary_key=True)
    customer_id: Mapped[int] = mapped_column(ForeignKey("customer.id"))
    customer: Mapped[Customer] = relationship()
    items: Mapped[list["Item"]] = relationship()


class Item(Base):
    __tablename__ = "item"
    id: Mapped[int] = mapped_column(primary_key=True)
    order_id: Mapped[int] = mapped_column(ForeignKey("orders.id"))
    dish: Mapped[str]


engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as s:
    for n in range(1, 51):
        s.add(Order(customer=Customer(name=f"Customer {n}"),
                    items=[Item(dish="dosa"), Item(dish="idli"), Item(dish="vada")]))
    s.commit()

queries = []
event.listen(engine, "before_cursor_execute",
             lambda conn, cur, sql, *args: queries.append(sql))


def render_page(*options):
    queries.clear()
    with Session(engine) as s:
        orders = s.scalars(select(Order).options(*options).limit(50)).all()
        for order in orders:
            line = (order.customer.name, [i.dish for i in order.items])
    return len(queries)


print("lazy:", render_page())
print("eager:", render_page(joinedload(Order.customer), selectinload(Order.items)))

On SQLAlchemy 2.1.6 with SQLite, it printed lazy: 101, then eager: 2. Run it yourself and you should see the same two lines.

joinedload adds a join to the main query. By default it is a LEFT OUTER JOIN, which keeps every order even when no customer row matches. Our log showed orders LEFT OUTER JOIN customer AS customer_1.

selectinload runs a second query with IN and the parent IDs. The SQLAlchemy docs call it generally the best strategy for collections, and joinedload the most general one for many-to-one links.

Two behaviours surprised us. A joinedload on a collection needs .unique() on the result in the 2.x style, or SQLAlchemy raises an error. The error says unique() must be invoked because the result has joined eager loads against collections.

Second, selectinload sends up to 500 parent IDs per IN query. We loaded 1,200 orders and saw 4 queries: 1 for orders and 3 batches of IDs. SQLAlchemy 2.1 added a chunksize option; chunksize=1000 gave 3 queries.

Django: select_related and prefetch_related

select_related follows foreign keys, columns that point at a row in another table, and one-to-one links in the same query, using a join. prefetch_related runs a separate query per relationship and joins the results in Python.

The Django docs explain why: select_related is limited to single-valued links to avoid the huge result a join across a many relationship would produce. Our log showed an INNER JOIN, which keeps only matching rows. In a separate check, a nullable foreign key switched it to LEFT OUTER JOIN.

One trap cost us 50 extra queries. After prefetch_related on items, calling order.items.filter() inside the loop ignores the prefetched rows. That run sent 52 queries.

The Django docs warn about this: any chained method that implies a different query ignores the cache. The fix is a Prefetch object with the filter inside its queryset. That ran in 2 queries.

Rails: includes, preload and eager_load

Rails offers three methods, and we did not run them. Our sandbox blocked the Ruby package server, so these lines rely on the Rails guide, which showed version 8.1.4 as of 30 October 2026.

The guide's example loops over 10 books and reads each author, which costs 11 queries. Book.includes(:author) cuts it to 2. preload always uses one query per association. eager_load always uses one query with a LEFT OUTER JOIN.

includes picks between the two. Conditions given as a hash on the associated table make it use a LEFT OUTER JOIN. An SQL string condition needs references to force the join.

Which fix should you choose: a join or a second query?

Use a join for many-to-one links like order to customer, and a second IN query for lists like order to items. That rule matches the SQLAlchemy docs and what we measured.

A join across a list repeats the parent row once per child. Our 50 orders with 3 items each came back as 150 joined rows, though the page shows 50 orders. The IN approach returned 50 order rows plus 150 item rows, with no repeats.

Join vs second query, for the same orders page
QuestionJoin (joinedload, select_related, eager_load)Second IN query (selectinload, prefetch_related, preload)
Queries for one relationshipAdds 0 queriesAdds 1 query; SQLAlchemy adds one per 500 IDs
Best fitMany-to-one and one-to-one linksOne-to-many and many-to-many lists
Repeated dataParent columns repeat for every child rowNo repeats; each table read once
Limits and paginationSQLAlchemy wrapped our LIMIT 50 query in a subquery, so the limit counted orders, not joined rowsLIMIT applies to the parents only
Filtering on the related tableDjango and Rails can filter in the same query. SQLAlchemy's joinedload cannot, so use an explicit join with contains_eager.Needs its own filter, like a Prefetch queryset

Nesting works too. The SQLAlchemy docs chain loaders, as in selectinload(Order.items).selectinload(Item.keywords). Django's prefetch_related takes a double-underscore path, such as pizzas__toppings in its docs.

How do you stop N+1 queries from coming back?

Make lazy loading fail loudly in the places that matter, and keep a query-count test. Each ORM has a switch that turns a hidden lazy query into an error.

Raise instead of query

  • SQLAlchemy: raiseload or lazy='raise' replace lazy loading with an error. Our run raised: 'Order.customer' is not available due to lazy='raise'.
  • Django 6.1: calling fetch_mode(models.FETCH_RAISE) on a QuerySet, Django's query object, raised FieldFetchBlocked with the message Fetching of Order.customer blocked.
  • Rails: strict_loading makes a lazy association load raise ActiveRecord::StrictLoadingViolationError, according to the Rails guide. Rails can also log instead of raising.

What do Django 6.1 fetch modes change for N+1 queries?

Django 6.1 added fetch modes, which control what happens when code reads a field that was not loaded. FETCH_ONE is the default and behaves like earlier versions. FETCH_RAISE blocks the query. FETCH_PEERS is the interesting one.

FETCH_PEERS loads the missing field for every instance from the same QuerySet at once. On the orders page, Order.objects.fetch_mode(models.FETCH_PEERS) needed 2 queries for customer names, with no select_related.

It has a scope limit we measured. The docs list foreign keys, one-to-one links, deferred fields (columns you chose not to load) and generic relations. Reverse lists like order.items are not covered, and the page with items still sent 52 queries.

Here is the guard as a Django test, run on Django 6.1.2. All three tests passed.

python
from django.core.exceptions import FieldFetchBlocked
from django.db import models
from django.test import TestCase
# Order is the orders page model, with customer and items relations.


class RecentOrdersTest(TestCase):
    def render(self, orders):
        return [(o.customer.name, [i.dish for i in o.items.all()]) for o in orders]

    def test_lazy_page(self):
        with self.assertNumQueries(101):
            self.render(Order.objects.all()[:50])

    def test_fixed_page(self):
        orders = Order.objects.select_related("customer").prefetch_related("items")
        with self.assertNumQueries(2):
            self.render(orders[:50])

    def test_blocked_page(self):
        orders = Order.objects.fetch_mode(models.FETCH_RAISE)
        with self.assertRaises(FieldFetchBlocked):
            self.render(orders[:50])

How does DataLoader fix N+1 queries in GraphQL?

DataLoader collects every key requested in one tick of the event loop and sends them to your batch function in a single call. Fifty customer lookups become one IN query.

A tick is one uninterrupted run of JavaScript before it waits on anything, such as a database reply. A key is the ID you ask for, like a customer ID.

GraphQL is an API style where the client picks the fields it wants. That makes N+1 easy. Each field has its own resolver, a function that fetches that field's data. A list of 50 orders calls the customer resolver 50 times, and a plain resolver runs 50 lookups.

We ran this with graphql 17.0.2. The query asked for recentOrders with each customer's name. Plain resolvers made 51 database calls. With a DataLoader created per request, the same query made 2.

javascript
const DataLoader = require('dataloader');

const customers = new Map([[1, 'Customer 1'], [2, 'Customer 2'], [3, 'Customer 3']]);

// The batch function: gets every key asked for in this tick, runs one query.
async function selectCustomers(ids) {
  console.log('SELECT ... FROM customer WHERE id IN', ids);
  return ids.map(function (id) {
    return customers.get(id) ?? new Error('no customer ' + id);
  });
}

// Create one loader per incoming request, never one per server.
const customerLoader = new DataLoader(selectCustomers);

// Five resolvers ask for customers in the same tick of the event loop.
const asks = [1, 2, 1, 3, 2].map(function (id) {
  return customerLoader.load(id);
});
Promise.all(asks).then(function (names) {
  console.log(names);
});

On dataloader 2.2.3 this printed one line, SELECT ... FROM customer WHERE id IN [ 1, 2, 3 ], then five names in the requested order. Duplicate keys were sent only once, because DataLoader caches each key. In a separate run of 50 loads with the cache option set to false, all 50 keys reached the batch function, repeats included.

DataLoader turns 50 loads into one batch

Notice the wait for the end of the tick. Loads made after an await land in a new batch.

Diagram connections:

  • 50 customer resolvers to DataLoader queue (load(id) x 50)
  • DataLoader queue to Batch function (End of tick)
  • Batch function to Database (One query)
  • Database to Results by key (Rows mapped to keys)
  • 50 customer resolvers: Each calls loader.load(customerId)
  • DataLoader queue: Collects keys during one tick
  • Batch function: Gets all unique keys at once
  • Database: SELECT customer WHERE id IN (...)
  • Results by key: Same length and order as the keys

Rules the batch function must follow

  • Return an array of the same length as the keys, in the same order. We returned a shorter array and DataLoader rejected every load with an error saying so.
  • Put an Error object in the slot of a missing key, rather than dropping it. The README allows values or Error instances in the array.
  • Create a new loader for each request. The README says the cache is per request and warns against sharing one loader between users.
  • A load made after awaiting another load's result goes into a new batch. Two loads written that way made 2 batches in our run.
  • maxBatchSize caps the keys per call. With maxBatchSize set to 2, 5 unique customers took 3 calls.

When is an N+1 query pattern not worth fixing?

When N is small and fixed, such as a page that always shows 3 settings rows. A few extra fast queries cost less than the time spent tuning them.

Watch for growth instead. A list that is 5 rows today and paginated to 50 tomorrow will hit the problem. A query-count test catches that change before users do.

Eager loading has its own waste. Loading every item list for 50 orders, when the page shows only names, fetches 150 rows nobody reads. Load what the page shows, and check the log after each change.

In the interview

How do you explain the N plus one query problem in a system design interview?

Name it, show the count, then give the fix and the trade-off. A strong answer shows that you measure queries, not that you memorised method names.

  1. Define it in one line

    I'd say: a list query returns N rows, then lazy loading fires one query per row, so the page sends N plus 1 round trips.

  2. Put a number on it

    For a page of 50 orders with customers and items, the lazy loop sent 101 queries. The fixed version sent 2.

  3. Show how you find it

    Turn on SQL logging, load the page once and look for one SELECT repeated per row with a changing ID.

  4. Give the fix by relationship

    Join for many-to-one links, a second IN query for lists. Name one ORM's options, such as select_related and prefetch_related.

  5. Cover the API layer

    In GraphQL, resolvers run per field, so use a per-request DataLoader to batch keys into one query.

  6. Close with prevention

    Add a query-count test and make lazy loads raise on hot paths, using raiseload, FETCH_RAISE or strict_loading.

Questions people ask

What does N+1 mean in N+1 queries?

It means 1 query to fetch a list of N rows, plus N more queries, one for each row's related data. With 50 orders that is 51 queries. Adding a second relationship, like each order's items, adds another N, so our page reached 101.

Is a join always faster than two queries?

No, not always. A join across a one-to-many list repeats the parent columns for every child row, so 50 orders with 3 items each came back as 150 rows. For lists, a second query with IN is often leaner. For a single parent, such as an order's customer, a join is usually the simplest choice.

Does adding a database index fix N+1 queries?

No, an index only makes each query faster. You still pay one round trip per row, and 51 fast queries can still be slower than 2. Fix the query count with eager loading first. Then add indexes on the columns used in the join or IN lookup, such as the foreign key.

What is the difference between select_related and prefetch_related in Django?

select_related uses a SQL join and works only for foreign keys and one-to-one links. prefetch_related runs one extra query per relationship and matches rows in Python, so it also handles many-to-many and reverse lists. On our page, both together brought 101 queries down to 2 on Django 6.1.2.

Why did my prefetch stop working after I added a filter?

Because filter() on a prefetched relation starts a new query and ignores the cache. The Django docs warn about this. In our run it turned 2 queries into 52. Put the filter inside a Prefetch object's queryset instead, which kept the page at 2 queries.

Do I need DataLoader if my GraphQL server uses an ORM?

Usually yes. Eager loading needs to know the shape of the data up front, but GraphQL clients choose fields at request time and each resolver runs alone. DataLoader batches whatever keys the resolvers ask for in one tick. Create one loader per request so users never share cached results.

How do I find N+1 queries in production?

Look at queries per request, not only slow queries. Tracing or database monitoring tools that group queries by request show one statement repeated many times. Then reproduce the page locally with SQL logging on, confirm the repeated SELECT and add a query-count test with the fix.