Sitemap
Backend Engineer

Backend Engineer

Hey, I'm Josh! Full-stack dev into Java, Spring Boot, React & .NET. I write code, break things, fix them, and repeat. 😄

Member-only story

10 Spring Boot Performance Optimization Techniques That Actually Make a Difference

8 min read3 days ago
Press enter or click to view image in full size

1. Fix N+1 Queries Before Optimizing Java Code

Consider an API that returns customers along with their orders.

@GetMapping("/customers")
public List<CustomerResponse> getCustomers() {
return customerRepository.findAll()
.stream()
.map(customer -> new CustomerResponse(
customer.getId(),
customer.getName(),
customer.getOrders().size()
))
.toList();
}

Free link

Suppose the application retrieves 100 customers. If accessing getOrders() triggers a separate database query for every customer, the application executes:

  • 1 query to retrieve customers.
  • 100 additional queries to retrieve their orders.

That’s 101 queries for a single API request.

This is the N+1 query problem.

One solution is to fetch the required relationship using a fetch join.

@Query("""
SELECT DISTINCT c
FROM Customer c
LEFT JOIN FETCH c.orders
""")
List<Customer> findAllWithOrders();

--

--

Backend Engineer
Backend Engineer

Written by Backend Engineer

Hey, I'm Josh! Full-stack dev into Java, Spring Boot, React & .NET. I write code, break things, fix them, and repeat. 😄