Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A client uploads 50 MB JSON payloads to a POST endpoint and the service runs out of memory. How would you protect the service?

A 50 MB JSON body gets read and turned into an object tree in memory, often several times its size, and a few of those at once exhaust the heap. I would protect the service in layers: limit request size at the proxy and in the server, set Jackson's stream read constraints for document length, nesting and string sizes, move legitimately large data to multipart upload or streaming instead of one JSON body, process big inputs asynchronously from storage with 202 Accepted, and monitor request sizes so we see the problem coming.

Why this question is asked

Out of memory errors from large requests are a production classic, and they are also a denial-of-service risk: if one large payload can kill an instance, a handful of malicious ones can take down the whole service. Interviewers ask this to see whether we understand where the memory goes and whether we can combine quick limits with a better design for genuinely large data. In this answer, we will see why a 50 MB body uses so much memory, add limits at each layer, change the API for large data, and set up monitoring.

1Why a 50 MB Body Uses So Much Memory

When a controller method takes @RequestBody, Jackson reads the whole body and builds the full object graph before our code runs. The bytes themselves are one cost. The Java objects are a bigger one: each JSON object becomes a Java object with headers and references, each string becomes a String with its own array, and numbers become boxed objects or BigDecimal. A 50 MB JSON document commonly turns into 150 to 300 MB of live objects, depending on its shape.

Now picture an instance with a 1 GB heap and 20 request threads. Four or five of these requests at the same moment are enough to fill the heap. The garbage collector works harder and harder, latency for every other request climbs, and eventually the JVM throws OutOfMemoryError. Often the instance is restarted, the client retries, and the next instance falls over too.

Where the memory goes for one request
StageMemory usedWhy
Body bytesabout 50 MBRead by Jackson through a buffer
Parsed objects150 to 300 MBObject headers, Strings, boxed numbers
Mapped to entitiesAnother copyDTO to entity mapping keeps both alive
5 concurrent uploads1 GB or moreEnough to fill a 1 GB heap

2Limit the Size at the Edge and in the Server

The first defence is to reject oversized requests before they reach the JVM heap at all. The reverse proxy or API gateway is the best place, because it can refuse the request after reading only its headers.

Java
# nginx in front of the service
client_max_body_size 2m; # larger bodies get 413 Request Entity Too Large
# Spring Boot (Tomcat): limits that exist out of the box
server.tomcat.max-http-form-post-size=2MB # form posts only, not JSON bodies
server.tomcat.max-swallow-size=2MB # how much of a rejected body Tomcat reads
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=110MB

Notice the comment on max-http-form-post-size: it only applies to form-encoded bodies, so it does not protect a JSON endpoint. The servlet container has no general limit for JSON bodies that Spring Boot exposes as a property, which is why the proxy limit matters. Inside the application, a small filter can check Content-Length and reject anything over the limit for JSON endpoints with 413 Content Too Large.

3Reject Oversized JSON Inside the Service

Here is such a filter. It runs before the DispatcherServlet, so Jackson never sees the oversized body. With chunked uploads, where there is no Content-Length, the same filter can wrap the input stream in one that counts bytes and fails after the limit.

Java
@Component
class JsonBodyLimitFilter extends OncePerRequestFilter {
private static final long MAX = 2 * 1024 * 1024; // 2 MB
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
if (req.getContentLengthLong() > MAX) {
res.sendError(413, "Request body too large"); // rejected before Jackson reads anything
return;
}
chain.doFilter(req, res); // chunked bodies: wrap the stream to count bytes
}
}

Notice that the check costs nothing for normal requests: it reads one header. The limit should match what the API really needs, for example 2 MB for order endpoints, and the documentation should state it so clients are not surprised.

4Set Jackson's Stream Read Constraints

Size is not the only danger. A small document can still be expensive: deeply nested arrays, a single string of 30 million characters, or a number with a hundred thousand digits. Since version 2.15, Jackson has StreamReadConstraints that cap these, with defaults such as a maximum nesting depth of 1000 and limits on string and number length. Newer versions also offer a maximum document length. We can tighten them for our API through a Jackson customiser.

Java
@Bean
Jackson2ObjectMapperBuilderCustomizer readLimits() { // Boot 3 with Jackson 2.x
return builder -> builder.postConfigurer(mapper ->
mapper.getFactory().setStreamReadConstraints(StreamReadConstraints.builder()
.maxDocumentLength(2_000_000) // about 2 MB of input
.maxNestingDepth(64)
.maxStringLength(100_000)
.maxNumberLength(50)
.build()));
}
// a 3 MB body -> StreamConstraintsException -> 400 instead of a heap spike

The defaults and exact builder methods differ between Jackson versions, and Spring Boot 4 uses Jackson 3 with a different customiser type, so check your version. The principle stays the same: limits that match what our API really accepts.

5Change the API for Legitimately Large Data

Sometimes a client really does need to send 50 MB, for example a nightly product catalogue. Then limits alone just break the client, and the API should change. One JSON body is the wrong shape for bulk data. Better shapes are a multipart upload of a file, which Spring stores to a temporary file on disk rather than the heap above a threshold, or a streaming endpoint that reads the input stream incrementally, for example with Jackson's streaming JsonParser or a line-per-record format like NDJSON, so only one record is in memory at a time.

Java
@PostMapping(path = "/catalogue/imports", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<ImportStatus> upload(@RequestParam("file") MultipartFile file) throws IOException {
String key = storage.save(file.getInputStream()); // stream to object storage, not the heap
ImportJob job = imports.start(key); // a worker processes it later
return ResponseEntity.accepted() // 202 Accepted
.location(URI.create("/catalogue/imports/" + job.id()))
.body(new ImportStatus(job.id(), "QUEUED"));
}
// GET /catalogue/imports/{id} -> {"status":"RUNNING","processed":120000}
Step throughLarge import, processed asynchronously
ClientImport APIObject storageWorker
POST multipart file
stream file to storage
202 Accepted, Location: /imports/7
read file record by record
update status: RUNNING, DONE
GET /imports/7
status DONE, 120000 records

7 messages in order. Play them, or step through them one at a time.

Notice the 202 Accepted. The request returns quickly with a link to a status resource, and a worker reads the file from storage record by record, at its own pace. A slow or huge import no longer holds a request thread, and its memory use is bounded by one record, not the whole file. For very large files, a pre-signed URL that lets the client upload straight to object storage keeps the bytes out of our service entirely.

6Monitor Request Sizes

Finally, we want to see this coming. The proxy's access logs and the gateway can record request body sizes per endpoint and per client, and a histogram metric in Micrometer can do the same inside the service. An alert when the 99th percentile of body size on an endpoint grows, or when any client sends near the limit, tells us a partner's data is growing before it becomes an outage. Heap usage and GC time per instance complete the picture, and a heap dump on OutOfMemoryError, with -XX:+HeapDumpOnOutOfMemoryError, makes the next incident easy to diagnose.

7Follow-up questions

What status should an oversized request get?

413, named Content Too Large in RFC 9110 and Payload Too Large in older texts. It tells the client the problem is size, not syntax. The response can mention the limit and point to the bulk upload endpoint.

Would a bigger heap fix it?

Only until the payloads or the concurrency grow again, and it makes garbage collection pauses longer. Bounded memory per request, through limits and streaming, is the real fix; heap size is then a capacity decision rather than a defence.

8Conclusion

In this answer, we saw that a 50 MB JSON body becomes several times that size in objects, so a few concurrent requests can exhaust the heap. We protected the service with size limits at the proxy and a filter in the server, tightened Jackson's stream read constraints for document length, nesting and string sizes, moved legitimately large data to multipart upload or streaming with asynchronous processing and 202 Accepted, and added monitoring of request sizes and heap usage.

What to say in the interviewAbout 80 seconds aloud

Open with

The root cause is that a @RequestBody is read fully into memory and turned into an object graph that's often three to six times the size of the JSON, so a few 50 MB requests at once fill the heap.

Then, if they want more

I'd protect the service in layers. First, size limits at the edge: the proxy or gateway rejects bodies over, say, 2 MB with 413 before they reach the JVM. Tomcat's form post limit doesn't cover JSON, so inside the service I'd add a small filter that checks Content-Length or counts bytes for chunked bodies.

Second, Jackson's stream read constraints, which since 2.15 limit nesting depth, string and number length, and in newer versions document length, so even small but nasty documents can't blow up.

Third, if clients legitimately need to send large data, I'd change the API: a multipart upload or a pre-signed URL to object storage, streamed to disk rather than the heap, then processed asynchronously by a worker record by record, with the endpoint returning 202 Accepted and a status link. That keeps memory per request bounded.

Finally, I'd monitor request body sizes per endpoint and client, plus heap and GC time, and enable heap dumps on OutOfMemoryError, so we see growth before it causes an outage.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 4
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 client uploads 50 MB JSON payloads to a POST endpoint and the service runs out of...": https://scrivio-interview-library.netlify.app/spring-boot/rest-controllers/5ef7764824/