Spring REST APIs · mid
Pagination and API versioning
Page runs a count query on every call; Slice and keyset scrolling do not. Version an API only for breaking changes, and keep old versions alive for old clients.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
Page<T>runs the data query pluscount(*)on every request. Fine for admin tables.Slice<T>fetches one extra row to know if there is a next page, with no count.- Offset paging (
LIMIT 20 OFFSET 20000) still reads and discards skipped rows, and items shift when new rows arrive. - Keyset: rows after the last (created_at, id) seen. Spring Data supports it with
ScrollPosition.keyset()andWindow<T>. - Cap the page size:
spring.data.web.pageable.max-page-sizedefaults to 2000. Set it much lower, for example 100. - Return items plus an opaque
nextCursor. Do not serialise Spring'sPageas your API contract. - First try not to break anything: add fields, do not rename or remove, clients ignore unknown fields. Version only for real breaking changes.
- Options: path (
/v2/orders), header (API-Version: 2), query parameter, media type. Framework 7 and Boot 4 supportversion = "2"on a mapping. - Unsupported version raises
InvalidApiVersionException(400). Retire a version withDeprecationandSunsetheaders and measure who still calls it. Old mobile app versions stay installed for a long time: keep the old version working for the promised period and use a force-update screen for very old ones.
The red pen
Common traps: mistake → fix
Mistake: Page is best for infinite scroll
Fix: it runs a count query every time; use Slice or keyset.
Mistake: Offset paging is stable
Fix: items shift when rows are added.
Mistake: Every change needs a new API version
Fix: add-only changes are compatible.
Easy to hard
Questions interviewers ask, easy to hard
- Page, Slice or keyset for a customer with 30,000 orders?
- Why is offset 20000 slow?
- How do you version GET /orders/{id} when old apps stay for a year?
- What do you return as the response shape of a list?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.