Quick revision
The short answer
Passing sort and size straight from a public request to Spring Data lets any client choose how much work the database does: a huge size returns enormous results, sorting on an unindexed column or a nested path forces full sorts or unwanted joins, and deep page numbers make offset queries crawl. The guardrails are a maximum page size through spring.data.web.pageable.max-page-size or validation, an allow-list of public sort keys mapped to known properties, keyset pagination for public feeds, and rate limiting with slow-query monitoring per endpoint.
What to remember
In this answer, we saw that binding sort and size straight from a public request lets any client choose the query's cost: huge pages, unindexed or nested sorts with extra joins, and deep offsets. The guardrails are a maximum page size with max-page-size or validation, an allow-list of sort keys mapped to indexed properties, keyset pagination for deep public feeds, and rate limiting with slow-query monitoring per endpoint.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Passing sort and size straight from a public request to Spring Data lets any client choose how much work the database does: a huge size returns enormous results, sorting on an unindexed column or a nested path forces full sorts or unwanted joins, and deep page numbers make offset queries crawl. The guardrails are a maximum page size through spring.data.web.pageable.max-page-size or validation, an allow-list of public sort keys mapped to known properties, keyset pagination for public feeds, and rate limiting with slow-query monitoring per endpoint.
Why this question is asked
Spring Data's web support makes paging almost free to build: add a Pageable parameter to a controller method and clients can send ?page=3&size=20&sort=createdAt,desc. That convenience is exactly what makes a public endpoint fragile, because the client now decides the shape of the database query. Interviewers ask this scenario to see whether we think about the database as a shared resource that any anonymous caller can stress, and whether we know Spring's settings and the design changes that remove the risk. In this answer, we will see how the request becomes a query, go through each risk with what it costs, and add the guardrails one by one.
1How the Request Becomes a Query
When a controller method takes a Pageable, Spring's PageableHandlerMethodArgumentResolver builds it from the request parameters page, size and sort. The sort parameter accepts a property name and a direction, and it can be repeated. The Pageable is then passed to a repository method, and Spring Data turns it into an order by, a limit and an offset.
Spring does put a default ceiling on size, which is 2,000 in current versions, but that is still far more than a public page should return, and nothing restricts which properties can be sorted. Check your version for the default.
2The Risks, One by One
Large sizes come first. size=2000 on a product listing returns 2,000 rows with all their columns, serialised to JSON, with any lazy associations loaded per row. A few clients doing this in a loop can saturate the database and the application's memory.
Sorting is the subtle one. A sort on name, which has an index, is cheap. A sort on description, which has no index, makes the database read every matching row and sort them before returning 20. A nested path such as sort=supplier.country.name is also accepted by Spring Data, and it adds joins to two more tables just to sort. The client has effectively written a new, expensive query that nobody tuned or tested. Sorting on a property that should not be visible can even leak information through the order of results.
Deep offsets are the third risk. page=50000&size=20 asks the database to skip a million rows. With Page as the return type, each request also runs a count query, so an attacker or a careless crawler can generate two heavy queries per call.
| Client input | What the database does | Typical cost |
|---|---|---|
| size=20, sort on indexed column | Index scan, 20 rows | Milliseconds |
| size=2000 | Reads and returns 2,000 rows | 100x the data per call |
| sort=description (no index) | Full read and sort of matches | Seconds on large tables |
sort=supplier.country.name | Two extra joins, then sort | Seconds; untested plan |
| page=50000 | Skips 1,000,000 rows | Grows with page number |
3Guardrail 1: Cap the Page Size
The first guardrail is a hard maximum. Spring Boot exposes spring.data.web.pageable.max-page-size; a requested size above it is reduced to the maximum. Set it to what the product actually needs, often 50 or 100, together with a sensible default size.
If silently reducing the size would surprise clients, validate instead and return 400 Bad Request with a clear message. Either way, the maximum must be enforced on the server, not suggested in documentation.
4Guardrail 2: An Allow-List of Sort Keys
The real fix for sorting is to stop accepting entity property names at all. The public API defines a few sort keys that the product needs, each mapped to a property we have indexed and tested. Anything else is rejected.
This also decouples the API from the entity: renaming a field no longer changes the public contract. Each allowed key has an index, so we know the cost of every sort a client can ask for. The @Max on page needs @Validated on the controller class to be enforced, and it limits how deep offset paging can go.
5Guardrail 3: Keyset Pagination for Public Feeds
Capping the page number limits the damage, but some lists, such as a public feed or a search result that users scroll, really need depth. For those, keyset pagination is the better design: the client sends a cursor, an encoded form of the last row's sort values, and the query asks for rows after it, using the index without any offset. Spring Data's Window and ScrollPosition API supports this. Returning Slice or Window also removes the count query, which halves the queries per request.
6Guardrail 4: Rate Limits and Monitoring
Even well-shaped queries cost something, and a public endpoint can be called in a loop. A rate limit per client, at the API gateway or with a library such as Bucket4j, keeps one caller from monopolising the database.
Finally, watch it. Record query duration per endpoint, alert on slow queries, and look at the database's top queries regularly; pg_stat_statements in PostgreSQL shows which statements cost the most in total. If a new sort key or filter turns out to be expensive, the monitoring shows it before users do.
- Gateway rate limitRequests per client per minute
- Controller validationAllowed sort keys, max size, max page
- Query designKeyset or Slice, no count, indexed sort
- DatabaseIndexes for every allowed sort
- MonitoringSlow queries per endpoint, alerts
5 layers, from the top down. Step through them one at a time.
Each layer limits what reaches the next.
7Follow-up questions
Is the sort parameter a SQL injection risk?
Spring Data validates sort properties against the entity for derived and JPQL queries, and it checks native sort expressions for unsafe input, so classic injection is unlikely. But it still lets clients choose expensive or revealing sorts, which is a performance and information risk. An allow-list removes both.
Should a public API return Page with totals?
Usually not for large collections. Totals require a count on every request, and exact totals are rarely important to users. A Slice or a cursor with hasNext is cheaper; if a total is needed, show an approximate or cached one.
What should happen when a client asks for size=5000?
Either clamp it to the maximum, which is what max-page-size does, or reject it with a 400 and a message. Rejecting is clearer for API consumers; clamping is friendlier for browsers. Pick one, document it and be consistent.
8Conclusion
In this answer, we saw that binding sort and size straight from a public request lets any client choose the query's cost: huge pages, unindexed or nested sorts with extra joins, and deep offsets. The guardrails are a maximum page size with max-page-size or validation, an allow-list of sort keys mapped to indexed properties, keyset pagination for deep public feeds, and rate limiting with slow-query monitoring per endpoint.
Open with
The core risk is that the client now designs part of the query. With size passed through, someone can ask for thousands of rows per call, and Spring's default ceiling of a couple of thousand is far too high for a public endpoint.
Then, if they want more
With sort passed through, they can sort on a column with no index, which makes the database read and sort every matching row, or on a nested path like supplier.country.name, which Spring Data happily turns into extra joins. That is a query nobody tuned or tested, and the sort order can even leak data.
Deep page numbers add a third problem: offset paging skips rows, so page fifty thousand makes the database discard a million rows, and with Page there is a count query on every call too. So I would add guardrails in layers. First, cap the size with spring.data.web.pageable.max-page-size, say 100, or validate and return a 400.
Second, stop accepting property names: the API offers a few sort keys like newest, name and price as an enum, each mapped to an indexed property, with id added as a tie-breaker, and anything else is rejected. That also decouples the API from the entity.
Third, for public feeds that people scroll deeply, use keyset pagination with Window and ScrollPosition and return a cursor, which removes offsets and the count query. Finally, rate limit per client at the gateway and monitor slow queries per endpoint so we notice when a new option becomes expensive.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A public endpoint accepts sort=anyProperty and size=anything, passed straight to Spring...": https://scrivio-interview-library.netlify.app/databases/spring-data-jpa/6757b40539/