Skip to lesson

The N+1 query problem

A ShopLite order list loads fast with 16 test orders and crawls with 2000 real ones, although no line of Java changed. The cause hides in a harmless-looking loop that sends one extra query for every row.

Reproducing N+1: orders and their customers' names

The N+1 problem is 1 query that loads N rows, plus N more queries that each load one linked row. The usual trigger is a loop that reads a lazy link, such as order.getCustomer().getFullName().

The ShopLite order list looks innocent: one repository call and a for loop. Example 1 prints the SQL that it sends for the 16 seed orders.

The same order list two ways. With N+1, the app sends 1 query for the 16 orders and then 7 more SELECTs, one for each distinct customer: 8 round trips. With a join fetch, one SELECT joins orders and customers: 1 round trip.

Example 1 · 16 orders, 8 SELECTs: the N+1 in the log

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// Order.java (fragment): the customer link is LAZY, as it should be@ManyToOne(fetch = FetchType.LAZY)@JoinColumn(name = "customer_id")private Customer customer;
// LabDemos.java (fragment). stats = Hibernate's Statistics object (section 2)public void ordersWithCustomerNames() {    stats.clear();    List<Order> list = orders.findAllByOrderByIdAsc();    for (Order o : list) {        System.out.println("Order " + o.getId() + " - " + o.getCustomer().getFullName());    }    System.out.println("Statements: " + stats.getPrepareStatementCount());}
Sample output
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 order by o1_0.order_id
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
Order 1 - Asha Rao
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
Order 2 - Ravi Kumar
Order 3 - Asha Rao
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
Order 4 - Meena Iyer
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
Order 5 - Kabir Singh
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
Order 6 - Priya Sharma
Order 7 - Ravi Kumar
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
Order 8 - Arjun Mehta
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
Order 9 - Divya Nair
Order 10 - Asha Rao
Order 11 - Kabir Singh
Order 12 - Priya Sharma
Order 13 - Meena Iyer
Order 14 - Ravi Kumar
Order 15 - Arjun Mehta
Order 16 - Divya Nair
Statements: 8

What this code does

  • Line 1 of the log is the list query. Every other SELECT is the proxy of one customer loading itself the first time the loop reads getFullName().
  • Orders 3, 7, 10 and later reuse customers already in the persistence context, so there are 7 customer SELECTs for 16 orders: N counts distinct customers.

Each getCustomer() finds a proxy, and each proxy runs its own select ... where customer_id=?. In Example 1 the 16 orders cost 8 statements, not 17, because the persistence context (the session's first-level cache from the Persistence Context module) loads each customer only once: orders 3 and 10 reuse Asha Rao. So N counts distinct linked rows. With real data, where most orders belong to different customers, N grows almost one-to-one with the rows.

Nothing in the Java says "database". That is why N+1 is found in the log, not by reading the code.

Predict the output

Count the statements

The loop reads each order's customer name. How many SQL statements run?

Round 1 of 3

5 orders, each from a different customer.

for (Order o : orders.findAll()) {
System.out.println(o.getCustomer().getFullName());
}

Spotting it in the SQL log and in Hibernate statistics

Hibernate statistics are counters that Hibernate keeps for the work it does, such as getPrepareStatementCount(), the number of SQL statements prepared since the counters were last cleared.

To catch N+1, count statements instead of reading code. Example 2 turns on the statistics, and Hibernate prints a metrics block when each session closes.

Example 2 · application.yml: statistics and the session metrics block

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

YAML
# application.yml (dev only): statistics plus one metrics block per sessionspring:  jpa:    properties:      hibernate:        generate_statistics: truelogging:  level:    org.hibernate.SQL: DEBUG    org.hibernate.session.metrics: DEBUG
Sample output
DEBUG metrics - HHH000401: Logging session metrics:
	1940100 ns acquiring 1 JDBC connections
	0 ns releasing 0 JDBC connections
	12478200 ns preparing 8 JDBC statements
	33108100 ns executing 8 JDBC statements
	0 ns executing 0 JDBC batches
	0 ns performing 0 second-level cache puts
	0 ns performing 0 second-level cache hits
	0 ns performing 0 second-level cache misses
	0 ns executing 0 flushes (flushing a total of 0 entities and 0 collections)
	1220900 ns executing 1 pre-partial-flushes
	608400 ns executing 1 partial-flushes (flushing a total of 0 entities and 0 collections)

What this code does

  • generate_statistics: true makes Hibernate count statements, and the org.hibernate.session.metrics logger prints this block when the session closes. Hibernate also prints empty blocks for short sessions during startup; only the last block, from the order list, is shown.
  • "preparing 8 JDBC statements" and "executing 8 JDBC statements" confirm the 1 + 7 from Example 1 without counting log lines by hand.

The SQL log pattern for N+1 is the same SELECT repeated with only the parameter changing: select ... from customers c1_0 where c1_0.customer_id=? seven times in a row. Whenever one request prints a block of identical lines, suspect N+1.

With hibernate.generate_statistics=true, the Statistics object (from entityManagerFactory.unwrap(SessionFactory.class).getStatistics()) has getPrepareStatementCount(), and the logger org.hibernate.session.metrics at DEBUG prints the block of Example 2: "preparing 8 JDBC statements". Statistics cost a little time on every statement, so turn them on in dev and test profiles, not in production. The Counting Queries lesson turns these numbers into a test that fails when they grow.

Hibernate 7 logs the metrics under org.hibernate.session.metrics at DEBUG. Older guides name StatisticalLoggingSessionEventListener at INFO, which prints nothing in Hibernate 7.

Hidden N+1: toString, mappers and Jackson

A hidden N+1 is an N+1 caused by code that does not look like data access: a toString() that prints a linked entity, a mapper that reads a lazy link, or Jackson writing entities straight to JSON.

Not every N+1 sits in a visible loop. Example 3 shows toString() sending queries, and Example 4 shows Jackson doing it while it writes a response.

Example 3 · Hidden N+1 in toString()

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// Order.java (fragment): a toString that "helpfully" shows the customer@Overridepublic String toString() {    return "Order#" + id + " (" + status + ", " + customer.getFullName() + ")";}
// LabDemos.java (fragment)public void ordersToString() {    stats.clear();    List<Order> list = orders.findAllByOrderByIdAsc();    System.out.println("Loaded " + list.size() + " orders");    System.out.println("Statements so far: " + stats.getPrepareStatementCount());    String text = list.subList(0, 3).toString();    System.out.println(text);    System.out.println("Statements now: " + stats.getPrepareStatementCount());}
Sample output
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 order by o1_0.order_id
Loaded 16 orders
Statements so far: 1
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
[Order#1 (DELIVERED, Asha Rao), Order#2 (DELIVERED, Ravi Kumar), Order#3 (DELIVERED, Asha Rao)]
Statements now: 3

What this code does

  • Loading the 16 orders cost 1 statement. Building the text of only 3 orders cost 2 more, because toString() read customer.getFullName() (orders 1 and 3 share a customer).
  • Nothing in the calling code mentions customers. The fix is a toString() with only the row's own fields (Practice 5).

Example 4 · Hidden N+1 in Jackson: entities in a response

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// OrderLabController.java (fragment): entities handed straight to Jackson/** Anti-pattern: entities straight to Jackson. */@GetMapping("/lab/orders")java.util.List<Order> entitiesToJson() {    return service.firstOrders();}
// OrderLookupService.java (fragment)public java.util.List<Order> firstOrders() {    return orders.findAllByOrderByIdAsc().subList(0, 3);}
// terminalcurl -i localhost:8080/lab/orders
Sample output
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:56:46 GMT
Connection: close

{"timestamp":"2026-10-16T06:56:46.708Z","status":500,"error":"Internal Server Error","path":"/lab/orders"}

(server log)
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 order by o1_0.order_id
DEBUG SQL - select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=?
DEBUG SQL - select a1_0.customer_id,a1_0.address_id,a1_0.city,a1_0.is_default,a1_0.label,a1_0.line1,a1_0.pincode,a1_0.state from addresses a1_0 where a1_0.customer_id=? order by a1_0.address_id
WARN  DefaultHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Document nesting depth (501) exceeds the maximum allowed (500, from `StreamWriteConstraints.getMaxNestingDepth()`)]

What this code does

  • While writing the JSON, Jackson called getCustomer() and then getAddresses(), and each lazy getter ran SQL in the middle of writing the response.
  • Address points back to Customer, so Jackson went round the loop until Jackson 3's nesting limit of 500 and the client got a 500. Entities in responses mean hidden queries and broken JSON; return DTO records.

In Example 3, printing three orders sent two more SELECTs. A log.debug("Loaded {}", orders) line does the same, and only when DEBUG is on, so the query count changes with the log level. Keep toString() to the entity's own columns.

In Example 4, returning entities from a controller makes Jackson call every getter: getCustomer(), then the customer's getAddresses(), then each address's getCustomer() again. Each lazy getter runs SQL while the response is being written, and the cycle never ends: Jackson 3 stops at nesting depth 500 and the client gets a 500. Controllers must return DTO records, as the DTO lesson of this module shows.

Find the bug

Find the hidden query

Each snippet looks like plain Java but can send SQL. Tap that line.

An Order entity with a lazy customer link.

Round 1 of 3
Example 4 works only because Open Session in View keeps the session open while Jackson writes. The Open Session in View lesson explains why ShopLite turns it off.

The cost: 20 rows vs 2000 rows

A round trip is the full trip of one statement: the app sends SQL, the database answers and the app waits. Every statement pays it once, about 0.1 to 1 ms on one machine and 1 to 2 ms or more across a network.

Each extra query is fast, so N+1 shows up only as the table grows. Example 5 times the same code on 20 and on 2000 orders.

Example 5 · Timing N+1 against one join: 20 rows vs 2000 rows

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// LabDemos.java (fragment): the loop is timed after one warm-up callpublic void timeNPlusOne() {    stats.clear();    long start = System.nanoTime();    int chars = 0;    for (Order o : orders.findAllByOrderByIdAsc()) {        chars += o.getCustomer().getFullName().length();    }    long ms = (System.nanoTime() - start) / 1_000_000;    long statements = stats.getPrepareStatementCount();    System.out.println("N+1: orders=" + orders.count() + " statements=" + statements            + " time=" + ms + " ms (" + chars + ")");}
public void timeJoinFetch() {    stats.clear();    long start = System.nanoTime();    int chars = 0;    for (Order o : orders.findAllWithCustomer()) {        chars += o.getCustomer().getFullName().length();    }    long ms = (System.nanoTime() - start) / 1_000_000;    System.out.println("join fetch: statements=" + stats.getPrepareStatementCount()            + " time=" + ms + " ms (" + chars + ")");}
// terminal: the same jar against a 20-order and a 2000-order databasejava -jar target/perf-lab-0.0.1-SNAPSHOT.jar --lab.demo=timing --logging.level.org.hibernate.SQL=WARN
Sample output
-- database with 20 orders of 20 different customers
join fetch: statements=1 time=450 ms (211)
N+1: orders=20 statements=21 time=225 ms (211)
join fetch: statements=1 time=14 ms (211)

-- database with 2000 orders of 2000 different customers
join fetch: statements=1 time=1122 ms (24893)
N+1: orders=2000 statements=2001 time=3260 ms (24893)
join fetch: statements=1 time=75 ms (24893)

What this code does

  • The first join fetch line is a warm-up (connection, JIT, query plans) and is ignored. Then N+1 and the join run on the same data: 21 vs 1 statements, 225 vs 14 ms for 20 rows; 2001 vs 1 statements, 3260 vs 75 ms for 2000 rows.
  • The join is the fix from the next lesson. The database here is on the same laptop; over a network every one of the 2001 round trips costs more.

With 20 rows, N+1 took 225 ms and the join 14 ms; nobody notices on a test page. With 2000 rows, N+1 sent 2001 statements and took 3260 ms, while the join took 75 ms, against a MySQL on the same computer. N+1 grows with the data; the join barely moves.

In production it is worse: many users call the page at once, each request holds a pool connection for all its round trips, and the database parses the same SELECT thousands of times. That is why interviewers ask about N+1: it passes every test and fails under real data.

Timings are from one laptop run ("Sample output"); yours will differ. The statement counts, 21 and 2001, will not.

Next step

Check your understanding

12 quick questions