Pagination & Sorting
Unbounded Orders lists become production incidents.
Introduction
Unbounded Orders lists become production incidents. Spring Data's Pageable and Page<T> give offset pagination and sorting with almost no boilerplate — but you must cap page size and choose stable sort keys.
Controllers accept Pageable (or explicit page/size/sort params). Repositories take Pageable on finder methods. Prefer @PageableDefault for sensible defaults (size=20, sort by createdAt DESC). Hard-cap maximum size (for example 100) so clients cannot request a million rows.
Offset pagination slows on deep pages. For very large ledgers, plan keyset/cursor pagination (where id < :cursor). Always include a unique tiebreaker in sort order to avoid duplicate/missing rows across pages.
Map Page<Order> to Page<OrderView> (or a custom page DTO) — never return entities.
Purpose of this lesson
Page and sort Orders lists with Spring Data Pageable, safe defaults, size caps, and stable ordering.
Understanding the topic
Pagination is an API contract and a database kindness.
- Pageable: page index, size, sort.
- Page<T>: content + total elements/pages metadata.
- defaults:
@PageableDefaultfor empty query strings. - caps: reject oversized
sizeto protect Postgres. - cursors: better than deep offsets at scale.
Step-by-step explanation
- Add
Page<Order> findByStatus(OrderStatus, Pageable)to the repository. - Expose
GET /api/orderswith@PageableDefault. - Map to
OrderView; enforce a max size in a resolver or manual check. - Verify
?page=0&size=20&sort=createdAt,descagainst sample data.
Informative example
Paged Orders list.
// RepositoryPage<Order> findByStatus(OrderStatus status, Pageable pageable);// Controller@GetMappingPage<OrderView> list(@RequestParam(defaultValue = "PENDING") OrderStatus status,@PageableDefault(size = 20, sort = "createdAt",direction = Sort.Direction.DESC) Pageable pageable) {if (pageable.getPageSize() > 100) {throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "size max 100");}return orderService.list(status, pageable);}// Service@Transactional(readOnly = true)public Page<OrderView> list(OrderStatus status, Pageable pageable) {return orders.findByStatus(status, pageable).map(OrderView::from);}// GET /api/orders?status=PAID&page=2&size=50&sort=totalCents,desc
Output
{
"content": [{"id": 90, "status": "PAID", "amountCents": 4999}],
"totalElements": 134,
"totalPages": 3,
"number": 2,
"size": 50
}Real-world use
Ops browses TechLearningPRO paid orders during a sale. Without size caps, a mistaken size=100000 could exhaust memory and the pool. Defaults plus a hard cap keep the dashboard responsive.
Security implications
Pagination parameters are attacker-controlled.
- Cap
sizeto prevent resource exhaustion. - Do not allow sorting on arbitrary entity graphs without a whitelist.
- Still filter by tenant/user — paging is not authorization.
Best practices
- Default sort includes a unique tiebreaker (
createdAt, id). - Prefer
Slicewhen total count is unnecessary. - Plan cursor pagination for infinite-scroll mobile feeds.
Common mistakes
- Sorting only by a non-unique column (duplicate rows across pages).
- Returning
Listfrom finders that should be paged. - Counting total elements on huge tables for every request without caching strategy — know the cost of
PagevsSlice.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat does Pageable encapsulate?+
Answer
2BeginnerQuestionWhy cap page size?+
Answer
3AdvancedQuestionWhen prefer keyset pagination over offset?+
Answer
OFFSET expensive; keyset uses a seek predicate on the last seen key for stable performance.Hands-on exercise
Lab. Seed 50 orders. Call page 0 size 20 and page 1 size 20; confirm no overlap with a unique sort. Then request size 500 and assert your cap rejects it.
Summary
Pagination keeps Orders lists honest under growth. Next: wrap multi-step writes in transactions.