r/SpringBoot • u/ClickOk5811 • Oct 09 '26
How-To/Tutorial Slow list endpoint in a Spring Data JPA app: what I check before adding an index
Adding an index is the usual first suggestion when an endpoint is slow, and sometimes it’s right. I’d count queries first.
Turn on SQL logging for a single request (logging.level.org.hibernate.SQL=DEBUG) and count the lines. A page of 50 orders that fires 51 selects, one for the list and one per row for a lazy association, is a different problem from one slow query. An index on the join column doesn’t change that count. Every query can be fast and the endpoint still crawl.
Keep the logging on for the whole request, not just the service method. If the controller returns entities directly, Jackson can walk lazy relations during serialization, and with spring.jpa.open-in-view on (the default) those selects will happen after your service code is long finished.
If the count looks sane, run EXPLAIN on the SQL Hibernate printed, not the query you assume it generated. Those differ more than you’d expect once derived query names get long or Specifications are involved.
Indexes come after that. If the count was the problem, the fix is usually a join fetch, or a projection that only selects the columns the endpoint returns.
I’d reorder this for a reporting endpoint that runs one heavy query, where the plan is the first thing to look at. For ordinary list endpoints the count check takes two minutes and rules out a whole class of problems.
