Video in progress
You need to upload and serve gigabyte-sized files through a Spring Boot service, and the heap is 512 MB. How do you design the whole path?
The bytes must never land in memory in full: stream the multipart to disk or straight to storage, and serve the response through StreamingResponseBody/Resource. Best of all, don't pass large files through the service at all; send the client to the storage with a presigned URL.
📖 Answer
The classic mistakes that fill the heap: MultipartFile.getBytes(), ResponseEntity<byte[]>, Files.readAllBytes, sending Base64 inside JSON. Any one of them gives OutOfMemoryError with a 2 GB file.
Upload:
- Spring's standard multipart writes the parts above
spring.servlet.multipart.file-size-thresholdto temporary disk. So the pod needs enough ephemeral storage, and it has to be counted in the Kubernetes limits. - Better than that: stream from
request.getInputStream()straight to the storage (S3 multipart upload, with 8-16 MB chunks). This way you also compute the size and hash along the way.
@GetMapping("/files/{id}")
ResponseEntity<StreamingResponseBody> download(@PathVariable UUID id) {
StoredFile f = storage.meta(id);
StreamingResponseBody body = out -> {
try (InputStream in = storage.open(id)) {
in.transferTo(out); // streamed with an 8 KB buffer
}
};
return ResponseEntity.ok()
.contentLength(f.size())
.contentType(MediaType.parseMediaType(f.mime()))
.body(body);
}
When serving, support Range requests too: re-downloading 2 GB from the start is a nightmare for the user. Spring MVC does this with ResourceRegion.
In the bigger picture:
- Don't pass it through the service. Presigned PUT/GET URLs: the service only checks permission and hands out a 5-minute link. The bytes travel between the client and the storage, freeing threads, heap and service traffic.
- Threads. Serving 2 GB to a slow client can hold a thread for hours. If the Tomcat pool is 200, 200 slow clients stop the service. Virtual threads or presigned URLs remove this problem.
- Timeouts and limits. The body size limit on the ingress/proxy (
client_max_body_sizeand the like) and the request timeouts have to suit large files, otherwise the upload is cut off at 60 seconds. - Validation. Determine the MIME type from the bytes at the start of the file, not from the client's
Content-Type; make an antivirus scan an asynchronous step for malicious files.
Sign up to mark studied questions and save your progress.