What is the N+1 query problem, and how do you find and fix it?
BackendMid-level
In shortLoading a list with one query and then running another query per item to load related data. Fix it with fetch joins, entity graphs, batch fetching or DTO projections, and catch it by counting queries in tests.
Model answer
N+1 happens when code loads N entities with one query and then touches a lazy association on each, so Hibernate runs one extra query per entity:
List<Author> authors = authorRepository.findAll(); // 1 query
for (Author a : authors) {
System.out.println(a.getBooks().size()); // + 1 query per author
}
With 10 test rows nobody notices; with 5,000 authors it’s 5,001 round trips.
Fixes, depending on the use case:
- Fetch join or
@EntityGraph: load the association in the same query (select a from Author a left join fetch a.books). Don’t combine a collection fetch join with paging: Hibernate then pages in memory. - Batch fetching (
hibernate.default_batch_fetch_size=50): lazy loads are grouped intowhere author_id in (…)queries, turning N+1 into N/50+1 without changing code. - DTO projections: for read-only endpoints, select exactly the columns you need, often with aggregation (
count(b)), and no entities at all.
Detection: set spring.jpa.open-in-view=false so lazy loading in the web layer fails loudly, enable Hibernate statistics or a datasource proxy in integration tests, and assert a maximum number of statements per request.
What they're looking for
A concrete example with lazy associations, at least two fixes with their trade-offs, the pagination caveat for collection fetch joins, and a way to detect it automatically. Bonus for mentioning open-in-view.
Common mistakes
- Making associations EAGER as the fix.
- Not knowing that paging a collection fetch join happens in memory.
- No idea how to detect it before production.
More backend questions
- What does Spring Boot's auto-configuration do, and how do you change what it set up?Mid-level
- How does a Spring backend authenticate requests from a mobile app, and how do you make sure users only see their own data?Mid-level
- Your Spring Boot service in Kubernetes keeps restarting with exit code 137. How do you investigate and fix it?Senior
- A Java service's p99 latency spikes every few minutes. How do you find the cause?Senior