How to find N+1 queries in Spring Boot and fix them
An endpoint that is fine with five rows and slow with five hundred is usually an N+1. Logs hide it. A trace shows it.
What an N+1 looks like
You load a list of orders with one query. Then, while building the response, your code touches order.getLines() on each one, and Hibernate runs one more query per order to load them. One query for the list, plus N for the children: N+1.
It passes every test on a dev database with a handful of rows. It shows up as a slow endpoint once the table grows, and by then nobody remembers which line caused it.
Why the logs don’t show it
With spring.jpa.show-sql on, you get a wall of near-identical select statements, mixed with every other request and with no hint of which one loaded which. You can count them, but you can’t see who asked for them.
What a trace shows instead
In a trace every SQL statement is a span with its real values, nested under the controller, service or repository method that ran it. An N+1 is then easy to spot: the same statement repeated under one parent.
Causeline flags it when the same query runs five or more times under one parent. The hint names the query that loaded the rows, so you know which association to change, not just that something is repeating.
N+1 queriesselect ... from order_line where order_id = ? ran 40 times under OrderService.list. Loaded by the query on orders.
To try it, add the starter, switch it on in a dev profile and open /causeline. The install page takes about five minutes.
Three ways to fix it
JOIN FETCH loads the children in the same query. It is the most direct fix when you always need them.
@Query("select distinct o from Order o join fetch o.lines where o.status = :status")
List<Order> findWithLines(@Param("status") String status);@EntityGraph says the same thing without writing the query, and keeps derived query methods.
@EntityGraph(attributePaths = "lines") List<Order> findByStatus(String status);
Batch fetching keeps lazy loading but loads children for many parents at once, so 40 queries become one or two. It is a good fit when you can’t always join, for example with several collections.
spring:
jpa:
properties:
hibernate.default_batch_fetch_size: 50Check the fix on the same trace
After the change, replay the captured request and compare the two runs span by span. The repeated statement should be gone, and the request should have fewer spans overall. Comparing the same request before and after is more convincing than reading the diff.
Keep it fixed with a test
An N+1 comes back the next time someone adds a field to a response. Causeline’s JUnit 5 guard fails the build when it does. It asserts on counts and shape, never on timing, so it gives the same answer on any machine.
causeline.trace("GET /api/orders")
.hasNoFailedSpans()
.hasQueryCountAtMost(2)
.hasNoRepeatedQueries();You can copy a captured request from the UI as a MockMvc or WebTestClient test with these assertions already filled in.