DEV Community

Shubham Bhati
Shubham Bhati

Posted on

Optimize Read-Heavy API Performance

Building read-heavy APIs? Don't let your ORM do unnecessary work. By default, @Transactional implies a write-capable session. For operations that only fetch data, you're paying for dirty checking and other write-related overhead you simply don't need.

Marking your service methods with @Transactional(readOnly = true) tells Spring and your JPA provider (like Hibernate) that the session is strictly for reads. This allows Hibernate to perform critical optimizations: it won't flush changes to the database, won't hold onto entities for dirty checking and can potentially use a read-only JDBC connection if configured.

It's a small change with a noticeable performance gain, especially under heavy load.

@Service
public class ProductService {

    @Transactional(readOnly = true)
    public List<ProductDTO> getAllProducts() {
        // Fetch products, map to DTOs
        return productRepository.findAll().stream()
               .map(ProductDTO::fromEntity)
               .toList();
    }

    @Transactional
    public Product createProduct(Product product) {
        // Persist new product
        return productRepository.save(product);
    }
}
Enter fullscreen mode Exit fullscreen mode

This simple tweak keeps your read paths lean and efficient.

Top comments (0)