Video in progress
What architectural problems come up when producing and accepting large collections as JSON in a REST API?
If the collection size isn't bounded, the response and the request are built fully in memory, and a single big request can fill the heap. On top of that, the collection that comes out of deserialization differs from what you expect (mutable or not, with nulls, ordering). The solution is pagination or streaming, limits on input, and explicit DTO types.
📖 Answer
On the output side, the classic mistake:
@GetMapping("/transactions")
List<TxDto> all(@RequestParam String accountId) {
return service.findAll(accountId); // 3 million rows on a single corporate account
}
All the rows go into entities, then into a DTO list, then into JSON bytes: three copies in memory. A single request like this takes down a pod with an OOM, and other users suffer too.
The options:
- Pagination (offset or cursor). On large tables a cursor (
afterId) is better, since the DB slows down as the offset gets deeper. - Streaming:
StreamingResponseBodyor NDJSON, reading from the DB with a cursor and writing right away. Memory stays constant, but if an error occurs midway, the client gets a half response, so the protocol has to be ready for that. - Asynchronous export: the request creates a job, the result is written to a file, and the client downloads it later.
On the input side:
@Size(max = 1000)validation on list fields. But it runs after deserialization, when the array is already in memory. So you also need a limit on body size (at the proxy and server level) and Jackson'sStreamReadConstraints.- Jackson fills a
Listfield with anArrayList. If you doList.copyOfin a record's constructor, a null element causes an NPE. Handle that separately in the error handler so it doesn't turn into a 500 instead of a 400. - With a
Setfield, duplicates sent by the client silently vanish. That can hide a bug, so in an API I prefer to accept aListand return an explicit error on a duplicate.
At the organization level: put in the API guideline the rule "every endpoint that returns a collection is paginated or bounded", and check it in API review. Introducing it is much cheaper than doing it after a 3-million-row incident.
Sign up to mark studied questions and save your progress.