The Hidden Cost of Spring Data JPA's Page<T> and How to Avoid It
Spring Data JPA's Page<T> runs a COUNT(*) query for every paginated request. On large tables this becomes a full scan. Use Slice<T> to drop the count, or keyset pagination for deep pages.
03 Jun 2026, 23:21 UTC

The Problem: Pagination That Works Until It Doesn't
You add Pageable to a Spring Data JPA repository method, wire up a controller, and pagination works instantly. The API returns content, totalPages, totalElements, and navigation links. Everything looks fine in development with a few hundred rows.
Then the table grows to millions of rows. The same endpoint that returned in 50 ms now takes 3 seconds. The culprit isn't the LIMIT/OFFSET query—it's the separate COUNT(*) query that Page<T> executes automatically to populate totalElements.
What Page Actually Does
When a repository method returns Page<T>, Spring Data JPA executes two statements:
- Data query:
SELECT * FROM entity WHERE ... ORDER BY ... LIMIT ? OFFSET ? - Count query:
SELECT COUNT(*) FROM entity WHERE ...
The count query runs without LIMIT, scanning every row matching the WHERE clause. On a large table with indexes that don't cover the filter, this becomes a full table scan. Even with good indexes, COUNT(*) on InnoDB or PostgreSQL must visit each visible row version due to MVCC visibility checks.
When OFFSET Pagination Degrades
The OFFSET approach has a second problem: the database still reads and discards offset rows before returning the page. At page 10,000 with size 20, the engine processes 200,000 rows just to throw them away. This is why keyset pagination (seek method) using WHERE id > ? ORDER BY id LIMIT 20 outperforms OFFSET at depth—but it requires a stable, unique sort key and doesn't support random page jumps.
Worked Example: Dropping the Count Query with a Projection
Suppose you have a ProductRepository and a high-traffic endpoint that only needs "next page" navigation, not "page X of Y".
// Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
// Returns Page - triggers COUNT query
Page<Product> findByCategory(Category category, Pageable pageable);
// Returns Slice - no COUNT query, only checks if next page exists
Slice<Product> findByCategory(Category category, Pageable pageable);
// Custom projection for keyset pagination
@Query("SELECT p FROM Product p WHERE p.category = :category AND p.id > :lastId ORDER BY p.id ASC")
List<Product> findNextPage(@Param("category") Category category,
@Param("lastId") Long lastId,
Pageable pageable);
}
Controller using Slice (no total count):
@GetMapping("/products")
public ResponseEntity<Slice<ProductDto>> listProducts(
@RequestParam Category category,
Pageable pageable) {
Slice<Product> slice = repository.findByCategory(category, pageable);
return ResponseEntity.ok(slice.map(this::toDto));
}
With Slice<T>, Spring Data executes only the data query. The response includes content, number, size, hasNext, and hasPrevious—enough for infinite scroll or "load more" buttons. The totalElements and totalPages fields are absent, eliminating the count query entirely.
For keyset pagination, the client sends the last seen id instead of a page number:
@GetMapping("/products/next")
public List<ProductDto> nextPage(@RequestParam Category category,
@RequestParam Long lastId,
@RequestParam(defaultValue = "20") int size) {
Pageable pageable = PageRequest.of(0, size, Sort.by("id").ascending());
return repository.findNextPage(category, lastId, pageable)
.stream()
.map(this::toDto)
.toList();
}
Trade-offs and Limitations
- Slice vs Page: You lose
totalElementsandtotalPages. UIs showing "page 3 of 47" needPage; infinite scroll does not. - Keyset pagination: Requires a unique, immutable, sequentially ordered column (usually
idorcreated_at+id). Cannot jump to arbitrary pages. Sorting by other columns breaks the seek predicate. - Soft deletes and custom filters: The default count query may not respect
@Whereclauses or soft-delete filters. You may need a custom@Query(countQuery = "...")or a projection that filters in the count. - Unbounded page sizes: Clients can request
?size=100000. Setspring.data.web.pageable.max-page-size=100(or your limit) to cap it. The framework will clamp the size, but the client won't know unless you document it. - Transaction isolation: Uncommitted inserts/deletes in the same transaction can make
totalElementsinconsistent with the returned page, depending on flush mode and isolation level.
Actionable Checklist
- Audit endpoints returning Page<T>. Enable SQL logging (
logging.level.org.hibernate.SQL=DEBUG) and verify a separateCOUNTruns. - Switch to Slice<T> where the UI only needs "next/previous" navigation. Change the repository return type and update the controller—no query changes needed.
- For high-volume, deep pagination, implement keyset pagination with a dedicated repository method and a cursor-based API (
?after=12345&size=20). - Configure
max-page-sizeinapplication.ymlto prevent accidental large fetches. - Test with production-scale data. Run
EXPLAIN ANALYZEon both the data and count queries. If the count query shows a sequential scan, add a covering index or move toSlice/keyset.
The default Page<T> behavior is convenient, but the automatic COUNT(*) is a silent performance tax. Choose Slice when you don't need totals, and keyset pagination when you paginate deep into large datasets. Your database will thank you.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.