Scrivio Interview library
ScenarioAdvanced6 min read · updated 12 November 2026

A public endpoint accepts sort=anyProperty and size=anything, passed straight to Spring Data. What risks does this create and what guardrails would you add?

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.

Java
@GetMapping("/api/products")
Page<ProductView> list(Pageable pageable) {
return products.findAllBy(pageable); // client values go straight through
}
// GET /api/products?page=0&size=20&sort=name,asc
// select ... order by p.name asc offset 0 rows fetch first 20 rows only
// select count(...) ...

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.

What each parameter can cost
Client inputWhat the database doesTypical cost
size=20, sort on indexed columnIndex scan, 20 rowsMilliseconds
size=2000Reads and returns 2,000 rows100x the data per call
sort=description (no index)Full read and sort of matchesSeconds on large tables
sort=supplier.country.nameTwo extra joins, then sortSeconds; untested plan
page=50000Skips 1,000,000 rowsGrows with page number
The client, not the developer, chooses which row of this table runs.

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.

Properties
# application.properties
spring.data.web.pageable.default-page-size=20
spring.data.web.pageable.max-page-size=100
// GET /api/products?size=5000 -> served as size=100

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.

Java
enum ProductSort {
NEWEST("createdAt"), NAME("name"), PRICE("price");
final String property;
ProductSort(String p) { this.property = p; }
}
@GetMapping("/api/products")
Slice<ProductView> list(@RequestParam(defaultValue = "NEWEST") ProductSort sort,
@RequestParam(defaultValue = "DESC") Sort.Direction dir,
@RequestParam(defaultValue = "0") @Max(200) int page,
@RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) {
Sort s = Sort.by(dir, sort.property).and(Sort.by(dir, "id")); // id breaks ties
return products.findAllBy(PageRequest.of(page, size, s));
}
// ?sort=NAME -> order by name, id
// ?sort=supplier.name -> 400 Bad Request: not a ProductSort value

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.

Step throughLayers of protection for a public listing
  1. Gateway rate limitRequests per client per minute
  2. Controller validationAllowed sort keys, max size, max page
  3. Query designKeyset or Slice, no count, indexed sort
  4. DatabaseIndexes for every allowed sort
  5. 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.

What to say in the interviewAbout 100 seconds aloud

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.
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/