Skip to the page

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.

The notes

What you must know

  • Page<T> runs the data query plus count(*) 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() and Window<T>.
  • Cap the page size: spring.data.web.pageable.max-page-size defaults to 2000. Set it much lower, for example 100.
  • Return items plus an opaque nextCursor. Do not serialise Spring's Page as 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 support version = "2" on a mapping.
  • Unsupported version raises InvalidApiVersionException (400). Retire a version with Deprecation and Sunset headers 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

  1. Page, Slice or keyset for a customer with 30,000 orders?
  2. Why is offset 20000 slow?
  3. How do you version GET /orders/{id} when old apps stay for a year?
  4. 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 voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview