Pagination & sorting, offset vs cursor
Spring Data Pageable, @PageableDefault, sort whitelisting, PageResponse DTOs, and when to switch to keyset (cursor) pagination.
The concept
Never return an unbounded list. A table that holds 50 rows today will hold 5 million later.
Offset pagination
SELECT * FROM bookings ORDER BY requested_at LIMIT 20 OFFSET 40; -- page 3
In Spring Data:
@GetMapping("/bookings")
Page<BookingSummaryDto> list(
@PageableDefault(size = 20, sort = "requestedAt", direction = Sort.Direction.ASC) Pageable pageable) {
return service.list(pageable);
}
// GET /bookings?page=2&size=20&sort=requestedAt,desc
A Page<T> runs two queries: the slice, plus a COUNT(*) for the total. Use Slice<T> when you don’t need totals, for example with infinite scroll.
Problems with offset
- Performance.
OFFSET 100000still makes the database scan and throw away 100,000 rows. - Drift. If a row is inserted while the user pages, items get skipped or duplicated.
Keyset (cursor) pagination
SELECT * FROM messages
WHERE (created_at, id) < (:lastCreatedAt, :lastId) -- continue after the last item seen
ORDER BY created_at DESC, id DESC
LIMIT 50;
With an index on (created_at, id), this is O(log n) no matter how deep you go, and it is stable under inserts. The cost is that you can’t jump to page 37. Clients receive an opaque nextCursor (often base64 of the last sort key).
In your projects
module/booking/controller/BookingController.java@PageableDefault(size = 20, sort = "requestedAt", direction = Sort.Direction.ASC) returning Page<T>, combined with Specifications for filtering (next lesson).
shared/web/PageResponse.javaSperoTek doesn’t serialise Spring’s Page directly. It maps it to a stable DTO:
public record PageResponse<T>(List<T> items, int page, int size, long totalItems, int totalPages) {}Spring’s own PageImpl JSON shape has changed between versions, and Spring now warns against serialising it. Your own record is a contract you control.
chat/web/ChatController.java · ReceiptCursorServiceChat messages use Page<MessageResponse>, while read receipts use cursors (ReceiptCursorService). Chat is a classic keyset use case, because new messages arrive constantly.
controllers/UserController.javaStore has no pagination, but it does whitelist sort fields:
if (!Set.of("email", "name").contains(sort)) sort = "name";
userRepository.findAll(Sort.by(sort));The whitelist matters because an arbitrary sort property can error or expose internal columns.
POST /api/financial-reports/list · /api/reports/searchRM uses POST with a body for complex searches, because filter objects get too big for query strings. It is pragmatic, but you lose GET’s cacheability and bookmarkable URLs.
Alternatives
| Strategy | Use when |
|---|---|
Offset (Page) |
Admin tables, “page X of Y”, small to medium data |
Slice (no count) |
Infinite scroll where the total isn’t needed |
| Keyset / cursor | Feeds, chat, logs, big tables, APIs used by syncing clients |
| Time-window | Analytics (“last 7 days”) |
Related concepts you must know
COUNT(*)is expensive on big Postgres tables. Consider estimates (pg_class.reltuples) or skip the count.- Max page size. Cap
size(spring.data.web.pageable.max-page-size), otherwise?size=1000000becomes a denial of service. - Deterministic ordering. Always add a unique tiebreaker,
ORDER BY created_at, id, or rows with equal timestamps shuffle between pages. - Index to match the sort. Hostel’s composite
idx_bookings_room_period_statusfollows its query shape.