Spring Data JPA: Page<T> with COUNT query vs Slice<T> for paginating a multi-million-row table
0 reputation · 11 Jul 2020, 13:07 UTC
I'm designing a read endpoint over a table expected to hold tens of millions of rows, using Spring Data JPA (assume Spring Boot 3.x / Spring Data JPA 3.x). The API needs stable, bounded queries, but I'm torn between two documented approaches: returning Page<T> from a repository method with a Pageable, versus returning Slice<T> to skip the total-count query.
My understanding is that Page<T> triggers an additional COUNT query to populate totalElements and totalPages, which can become expensive on very large tables, while Slice<T> only fetches one extra row to determine whether a next page exists. The trade-off seems to be losing total-count metadata that a UI pager typically displays.
There is also the offset concern: deep pages via LIMIT/OFFSET degrade as offsets grow, and I'm unsure whether either abstraction mitigates that or whether keyset-style paging would be required instead.
Given a large dataset where clients mostly page forward:
- Is
Slice<T>the documented way to avoid the COUNT query, and what metadata do I actually lose? - Does either approach address large-offset degradation, or is that orthogonal to the Page/Slice choice?
- Are there version-specific behaviors in recent Spring Data JPA releases I should verify before committing?