Spring Data JPA Pagination: Choose Page or Slice and Bound Offsets
When to use Page versus Slice, how COUNT queries affect performance, and why unbounded offsets can slow down feed endpoints.
09 Feb 2026, 06:39 UTC

The problem and the practical takeaway
Your feed endpoint slows down as users scroll deeper. Spring Data JPA’s Page returns the total number of matching rows, but that convenience runs a separate COUNT query on every request. Slice skips the count and only checks whether another page exists, which is cheaper for infinite-scroll interfaces. The larger risk is not just the extra query: large OFFSET values force the database to scan and discard preceding rows, and unsorted pages can return inconsistent results when data changes between requests.
Takeaway: Use Slice when the UI does not need a total count. Use Page only when the screen genuinely requires total pages or total elements. Always bind a maximum page size and sort on a unique column or a unique tie-breaker.
Requirements
- Spring Boot 3.x with Spring Data JPA 3.x (assumed version range; verify your dependency tree before relying on version-specific features).
- A relational database backing JPA entities.
- Repository interfaces extending
JpaRepositoryorPagingAndSortingRepository. - A client consuming paginated results, such as a REST controller or feed service.
Smallest suitable design
Expose both operations in the repository so callers can choose based on whether they need a total:
public interface AuditLogRepository extends JpaRepository<AuditLog, Long> {
Page<AuditLog> findByActor(String actor, Pageable pageable);
Slice<AuditLog> findByActor(String actor, Pageable pageable);
}
Pageable carries the offset, page size, and sort order. Page extends Slice and adds getTotalElements and getTotalPages. Slice exposes hasNext but no total count.
Controller example
@GetMapping("/feed")
public Slice<AuditLog> feed(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
return auditLogRepository.findByActor("current-user", pageable);
}
Bound the page size
Spring Boot resolves Pageable from request parameters. Without a cap, a client can request size=1000000. Configure limits in application.properties:
spring.data.web.pageable.default-page-size=20
spring.data.web.pageable.max-page-size=100
spring.data.web.pageable.one-indexed-parameters=false
Trust and data boundaries
Pageableis unbounded by default unlessmax-page-sizeis configured.Page.totalElementsis a snapshot. Concurrent inserts or deletes make it stale immediately after the count query. Treat totals as approximate, not authoritative.- Sorting without an explicit
ORDER BYis nondeterministic. The database may return rows in a different order across pages when data changes between requests. - Keyset pagination (seek methods) avoids
OFFSETpenalties, but requires a unique sort column or a unique tie-breaker to avoid skipped or duplicated rows.
Operational checks
1. Confirm count-query behavior with SQL logging
Enable SQL logging locally or in staging:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
Request the same page through a Page method and then through a Slice method. Expect a separate SELECT count(...) before the data query for Page, and no count query for Slice. Do not treat this as proof of production performance; it confirms query shape only.
2. Compare offset response times
Run an integration test against an embedded database or staging copy. Measure response time for offset 0 versus offset 100000 on the same table. Expect latency to grow as the offset increases because the database scans and discards preceding rows.
3. Verify the Spring Data JPA version
./mvnw dependency:tree | grep spring-data-jpa
Run in the project root. Required permission: read access to project files and ability to execute the Maven wrapper. Expected output: a Spring Data JPA 3.x artifact. Risk: older 2.x releases may lack keyset or seek-method support.
4. Test max page size enforcement
Send ?size=999999 to a paginated endpoint and verify the response is capped at the configured maximum or rejected with a client error.
Failure modes
| Failure mode | Cause | Effect |
|---|---|---|
| Deep pagination | Large OFFSET values | Database scans and discards rows; latency grows roughly linearly with offset on most relational engines. |
| Stale totals | Concurrent writes between count and data queries | totalElements no longer matches the actual result set; last page may be empty or missing rows. |
| Skipped or duplicated rows | Keyset pagination on a non-unique column without a tie-breaker | Rows sharing the same sort value are omitted or repeated across pages. |
| Memory or query timeout | Unbounded size parameter | JVM heap pressure or database statement timeout from very large result sets. |
Conditions that would change the design
- If the UI requires a total-count badge, use
Page, but consider caching the count or accepting an approximate total. - If the table has millions of rows and users paginate beyond the first few dozen pages, switch to keyset pagination using a seek method on the entity identifier or a unique timestamp-plus-identifier tuple.
- If the sort column is not unique, append the entity ID as a tie-breaker:
Sort.by("createdAt").descending().and(Sort.by("id").descending()). - If the derived count query is expensive because of complex joins, replace
PagewithSliceor maintain a materialized count table.
Limitations and verification
This note covers offset-based Page and Slice behavior in Spring Data JPA. It does not cover NoSQL repositories, reactive Pageable implementations, or database-specific count approximations. Keyset or seek-method availability depends on the Spring Data release train; verify your version before adopting seek-based APIs.
Practical verification: enable SQL logging, request page one with a Page method, and confirm a SELECT count(...) appears before the data query. Repeat with a Slice method and confirm no count query appears.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.