0
0
Spring Bootframework~8 mins

N+1 query problem in Spring Boot - Performance & Optimization

Choose your learning style9 modes available
Performance: N+1 query problem
HIGH IMPACT
This affects page load speed by causing many database queries during data fetching, which delays server response and slows down rendering.
Fetching a list of entities with their related data
Spring Boot
List<Order> orders = orderRepository.findAllWithCustomers(); // uses JOIN FETCH or EntityGraph
// customers loaded in one query with orders
Fetches orders and customers in a single query, reducing database calls drastically.
📈 Performance GainSingle query regardless of N, cutting database calls from N+1 to 1.
Fetching a list of entities with their related data
Spring Boot
List<Order> orders = orderRepository.findAll();
for (Order order : orders) {
  Customer customer = customerRepository.findById(order.getCustomerId()).orElse(null);
  order.setCustomer(customer);
}
This runs 1 query to get orders plus N queries to get each customer, causing many database hits.
📉 Performance CostTriggers N+1 database queries, increasing server response time linearly with N.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
N+1 Query PatternNo direct DOM impactNo direct reflowsBlocks initial paint due to slow server response[X] Bad
Batch Fetching with JOIN FETCHNo direct DOM impactNo direct reflowsFaster initial paint due to quicker server response[OK] Good
Rendering Pipeline
The server delays sending HTML until all data queries finish. Multiple queries increase server processing time, delaying HTML delivery and first paint.
Server Data Fetching
HTML Generation
First Paint
⚠️ BottleneckServer Data Fetching due to multiple database queries
Core Web Vital Affected
LCP
This affects page load speed by causing many database queries during data fetching, which delays server response and slows down rendering.
Optimization Tips
1Avoid running one database query per item in a list; batch fetch related data.
2Use JOIN FETCH or EntityGraph annotations in Spring Boot to load related entities eagerly.
3Reducing database queries improves server response time and speeds up page load (LCP).
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem caused by the N+1 query pattern?
AMultiple database queries increase server response time
BToo many DOM nodes are created
CCSS selectors become very complex
DJavaScript bundle size increases
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, and observe the number and timing of API/database calls or backend requests.
What to look for: Look for many sequential API calls or slow backend responses indicating multiple queries causing delays.