Scrivio Interview library
ScenarioAdvanced6 min read · updated 12 November 2026

Your file download service streams large files through Spring MVC and CPU is high. What options for reducing copies would you evaluate, across the stack?

First we measure where the CPU goes, then we remove copies from the outside in: serve the files from a CDN, object storage or a reverse proxy that uses sendfile, so the JVM never touches the bytes; if the JVM must serve them, stream a Resource or use transferTo instead of loading byte arrays, let Tomcat use sendfile where it can, avoid compressing already-compressed files, and terminate TLS at a proxy, because TLS inside the JVM rules out zero copy.

Why this question is asked

Large downloads are one of the few workloads where a Java service is mostly a very expensive copying machine. Every byte travels from disk or storage into the JVM, through several buffers, maybe through gzip and TLS, and out to the network. When CPU is high, adding pods works but costs money every month. Interviewers ask this scenario to see whether we think across the whole stack, from the code to the proxy to the CDN, and whether we measure before we change things. In this answer, we will first find out where the CPU is spent, then go through the options layer by layer, from moving the traffic off the JVM entirely to fixing the code, and finish with how we would prove the improvement.

1Start by Measuring Where the CPU Goes

High CPU in a download service can come from very different places, and each has a different fix. So the first step is a CPU profile under realistic load, for example with async-profiler or a JFR recording, turned into a flame graph. We look for the widest stacks: SSLEngine and AES code means TLS, Deflater means response compression, arraycopy and byte array allocation with high GC time means buffering whole files, and socket write frames with small sizes mean too many tiny writes.

Next to the profile we record the numbers we will compare later: CPU seconds per gigabyte served, throughput per pod, p99 time to first byte, GC time, and network bytes out. Without a baseline, we cannot tell whether a change helped.

Reading the flame graph
Widest framesLikely causeFirst fix to try
SSLEngine, AES/GCMTLS encryption in the JVMterminate TLS at a proxy or load balancer
Deflater, GZIPOutputStreamcompressing PDFs, ZIPs, videoexclude those content types
Arrays.copyOf, readAllBytes, GCwhole files loaded into byte arraysstream a Resource or InputStream
Many small socketWrite callstiny buffers or flush per chunklarger buffers, transferTo

2Option 1: Keep the Bytes Off the JVM

The cheapest copy is the one the JVM never makes. If the files are public or can be served with a short-lived signature, put them behind a CDN, or return a redirect to a pre-signed object storage URL, so the client downloads directly from storage and our service only authorises the request.

If the files sit on local or mounted disks behind nginx, the service can authorise the request and then hand the actual transfer to nginx with the X-Accel-Redirect response header (Apache has X-Sendfile). nginx then serves the file from an internal location with sendfile on, which moves bytes from the page cache to the socket inside the kernel.

Java
@GetMapping("/files/{id}")
ResponseEntity<Void> download(@PathVariable String id, Principal user) {
FileMeta f = files.authorise(id, user); // our business logic stays here
return ResponseEntity.ok()
.header("X-Accel-Redirect", "/protected/" + f.storagePath()) // nginx serves the bytes
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + f.name() + "\"")
.build();
}

Notice that the controller still decides who may download what; only the copying moves. This is usually the largest single win, because the JVM goes from handling gigabytes to handling a few hundred bytes per request.

3Option 2: Stream Instead of Buffering Whole Files

When the JVM must serve the bytes, the most common mistake is loading the file into memory. The broken version below allocates a byte array as big as the file for every request, which is both a copy and a lot of garbage collection work.

Java
// Before: every 500 MB download allocates 500 MB
byte[] data = Files.readAllBytes(path);
return ResponseEntity.ok().body(data);
// After: Spring streams the file in chunks and supports Range requests
Resource file = new FileSystemResource(path);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(Files.size(path))
.body(file);

Returning a Resource lets Spring copy it to the response with a small buffer, and it answers Range headers, so a resumed download does not restart from byte zero. For hand-written code, stream with in.transferTo(out) or, where we hold a FileChannel and a socket, FileChannel.transferTo, which can use sendfile.

Tomcat can also use sendfile for static files when its connector supports it, typically through its own static resource handling for files above a size threshold; whether Spring's resource handling takes that path depends on the server and its configuration, so check the server documentation for your version before relying on it.

4Option 3: Stop Paying for Compression and TLS in the JVM

Response compression is often switched on globally. PDFs, ZIP archives, images and video are already compressed, so gzipping them burns CPU and saves almost nothing. With server.compression in Spring Boot we list only text types in server.compression.mime-types and leave binaries out.

TLS is the other big cost and the one that blocks zero copy, because SSLEngine has to read every byte into user space to encrypt it. Terminating TLS at the load balancer or an ingress proxy moves that work to components built for it, and leaves the JVM to send plain bytes on the private network, which is also what lets sendfile work. Where policy requires encryption all the way to the pod, a sidecar or kernel TLS may help, but that is a platform decision to weigh, not a code change.

Step throughWhere each copy can be removed
  1. CDN or pre-signed storage URLthe JVM never sees the bytes
  2. Reverse proxy with sendfileX-Accel-Redirect; kernel moves the file
  3. Load balancer TLS terminationencryption off the JVM, zero copy possible
  4. Spring MVC responseResource streaming, no gzip for binaries
  5. Java I/OtransferTo instead of byte arrays

5 layers, from the top down. Step through them one at a time.

Work from the top: each layer that takes over removes all the copies below it.

5Proving the Improvement

We change one thing at a time and rerun the same load test. Suppose the baseline was 6 pods at 80% CPU serving 2 GB/s. Excluding PDFs from gzip might bring CPU per gigabyte down by a third; moving TLS to the load balancer might halve what is left; moving downloads to X-Accel-Redirect might take the service to a handful of cores in total. The numbers will differ for every system, which is exactly why we measure each step, along with p99 time to first byte and error rates, so a faster but broken download path is caught before it reaches users.

We also watch the network side: bytes out per pod and retransmits. If CPU drops but throughput does not rise, the bottleneck has moved to the network or the disk, and adding CPU would not help.

6Follow-up questions

Why not simply scale out with more pods?

It works, but the cost grows linearly with traffic forever. Removing copies changes the cost per gigabyte, so the saving compounds as traffic grows. Scaling out is the right short-term relief while we profile.

How do we keep authorisation if a CDN or proxy serves the file?

The service still checks the request, then issues something that only works once or briefly: a pre-signed URL that expires in minutes, a signed CDN cookie, or an internal X-Accel-Redirect location that nginx refuses to serve to the outside world. The decision stays in our code, the copying does not.

Does virtual threads or WebFlux fix the CPU problem?

No. They change how many requests can wait at once, not how many times each byte is copied. A download service with high CPU is usually limited by copying, TLS or compression, which no thread model removes.

7Conclusion

In this answer, we started by profiling, because TLS, compression, byte array buffering and tiny writes each need a different fix. Then we removed copies from the outside in: CDN or pre-signed URLs, a reverse proxy using sendfile through X-Accel-Redirect, TLS termination at the load balancer, no gzip for compressed files, and streaming with Resource or transferTo instead of byte arrays. Finally we proved each step with the same load test and CPU-per-gigabyte metric.

What to say in the interviewAbout 90 seconds aloud

Open with

Before changing anything I would profile the service under load with async-profiler or JFR, because high CPU in a download service has a few distinct causes: TLS encryption in the JVM, gzipping files that are already compressed, loading whole files into byte arrays, or lots of tiny writes.

Then, if they want more

I would also record CPU seconds per gigabyte and p99 time to first byte as a baseline. Then I would work from the outside in.

The biggest win is not serving the bytes from the JVM at all: a CDN, or a redirect to a pre-signed object storage URL, or letting nginx serve the file with sendfile via X-Accel-Redirect after our service has authorised the request.

If the JVM must serve them, I make sure we stream: return a FileSystemResource so Spring copies it in chunks and handles Range requests, or use transferTo, never readAllBytes. Tomcat can use sendfile for static files in some setups, but I would check the server docs rather than assume.

I would exclude PDFs, ZIPs and media from response compression, and terminate TLS at the load balancer, because TLS inside the JVM means every byte is copied and encrypted in user space and zero copy is impossible. After each change I rerun the same load test and compare CPU per gigabyte, latency and error rates.

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 "Your file download service streams large files through Spring MVC and CPU is high. What...": https://scrivio-interview-library.netlify.app/java/io-and-nio/3808407e28/