Quick revision
The short answer
The pods run out of memory because the endpoint builds the whole archive in a byte array before sending it. We redesign it to stream: a StreamingResponseBody writes a ZipOutputStream straight onto the servlet output stream, and each PDF is copied from object storage into its entry as a stream, so memory stays at the size of a buffer. Because PDFs are already compressed, we store them with little or no compression to save CPU, and for very large archives we build them asynchronously into object storage and send a download link.
What to remember
In this answer, we saw that the endpoint ran out of memory because memory grew with the archive: a ByteArrayOutputStream, a second copy, and whole PDFs loaded at once. We streamed instead, with a ZipOutputStream over a StreamingResponseBody and each PDF copied from object storage as a stream, so memory stays at a buffer. We used DEFLATED with level 0 because STORED needs sizes and CRCs up front, handled errors and timeouts after the response has started, and moved very large archives to an asynchronous build with a pre-signed link.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The pods run out of memory because the endpoint builds the whole archive in a byte array before sending it. We redesign it to stream: a StreamingResponseBody writes a ZipOutputStream straight onto the servlet output stream, and each PDF is copied from object storage into its entry as a stream, so memory stays at the size of a buffer. Because PDFs are already compressed, we store them with little or no compression to save CPU, and for very large archives we build them asynchronously into object storage and send a download link.
Why this question is asked
Bulk download is a feature every document system eventually adds, and it is a textbook case of code that works in testing with ten files and falls over in production with two thousand. Interviewers ask this scenario because the fix touches several layers at once: Java streams, the Spring MVC response model, the ZIP format and the choice between synchronous and asynchronous work. In this answer, we will see exactly why the current endpoint runs out of memory, rewrite it to stream end to end, pick the right compression for PDFs, deal with errors and timeouts once the response has started, and decide when to move to an asynchronous build with a link.
1Why the Current Endpoint Runs Out of Memory
The typical first version collects everything in memory and returns a byte array.
With 2,000 PDFs of 2 MB each, the archive is about 4 GB. ByteArrayOutputStream grows by copying into ever larger arrays, toByteArray() makes another full copy, and each PDF is also loaded whole. A pod with a 2 GB heap fails long before the end, and a Java array cannot exceed about 2 GB anyway. Two users downloading at once double the problem. The memory needed grows with the size of the archive, and that is the real design flaw.
2Streaming the Archive Straight to the Response
The fix is to make memory independent of the archive size. Spring MVC's StreamingResponseBody gives us the response's OutputStream and lets us write to it as we go. We wrap that in a ZipOutputStream, and for each document we open a stream from object storage and copy it into the entry with a small buffer.
7 messages in order. Play them, or step through them one at a time.
Memory holds a buffer, not the archive. The client receives bytes while later files are still being fetched.
Now each download holds one copy buffer, the ZIP deflater's small state and the output buffer, well under a megabyte, whether the archive has 20 files or 20,000. The bytes flow from storage through the pod to the client, and the client starts receiving data within the first second instead of waiting for the whole build. ZipOutputStream switches to the Zip64 extensions automatically when the archive passes 4 GB or 65,535 entries, so size limits of the old format are handled for us.
3Choosing Compression for PDFs
A PDF is already compressed internally, so deflating it again usually saves a percent or two at a real CPU cost. There are two ways to avoid that cost, and the ZIP format makes one of them awkward when streaming.
ZipEntry.STORED writes the bytes with no compression at all. But for a STORED entry, ZipOutputStream needs the size, the compressed size and the CRC-32 checksum before the entry's data is written, because they go into the entry header. We only know the CRC after reading the whole file, so we would have to read each PDF twice or have the storage system give us the checksum. The practical choice is to keep the default DEFLATED method with level 0, Deflater.NO_COMPRESSION, or level 1: the data passes through almost untouched, the CRC is computed while streaming, and the sizes go into a data descriptor written after the entry.
| Method | CPU | Needs size and CRC first? |
|---|---|---|
| DEFLATED, default level 6 | high, for almost no gain on PDFs | no |
| DEFLATED, level 0 or 1 | very low | no: written in a data descriptor |
| STORED | lowest | yes: must know them before writing |
4Errors, Timeouts and Threads Once Streaming Has Started
Streaming changes error handling. Once the first bytes are sent, the status 200 is already on the wire, so if file 1,500 fails to load we cannot turn the response into a 500. The usual approach is to log the failure with the case id, abort the stream so the client sees a broken download rather than a silently incomplete archive, and let the user retry. Some teams instead add a small errors.txt entry listing the files that could not be included, which is friendlier when partial results are acceptable.
StreamingResponseBody runs on a separate task executor through Spring MVC's async support, not on the request thread. We configure that executor explicitly with a bounded size, because each download now holds a thread for its whole duration, and we set spring.mvc.async.request-timeout high enough: 4 GB at 50 MB/s takes 80 seconds, longer than many default timeouts in proxies and load balancers, which also need checking.
5When to Build the Archive Asynchronously Instead
Streaming fixes memory, but some archives are simply too big or too slow to build while the user waits: tens of gigabytes, slow storage, clients on unreliable connections that cannot resume a streamed download. For those we switch to an asynchronous design. The request creates a job and returns 202 Accepted with a job id; a worker streams the archive into object storage using a multipart upload; when it finishes, the user gets a notification with a pre-signed link that expires after, say, 24 hours. Object storage then serves the download with Range support and the pods are no longer involved at all.
A reasonable rule is to stream directly below a size or file-count threshold, for example 1 GB or 500 files, and use the job above it. Repeated requests for the same case can reuse a recent archive instead of building it again.
- Estimate total size and file countfrom storage metadata, without reading files
- Under 1 GB and 500 files?Yesstream it now with StreamingResponseBodyNocreate a background job
- Job streams the ZIP into object storagemultipart upload, bounded memory
- Notify the user with a pre-signed linkstorage serves the bytes and handles resume
4 steps in order. Play them, or step through them one at a time.
6Why Not the Zip File System?
Java's zip file system provider, opened with FileSystems.newFileSystem, lets us treat an archive as a directory and copy files into it with Files.copy. It is convenient for editing an existing archive, but it is the wrong tool here: it writes to a file on disk, or works in memory, and only writes the central directory when the file system is closed, so it cannot stream an archive onto an HTTP response as it is built. ZipOutputStream is built for exactly that.
7Follow-up questions
Can we set Content-Length on the streamed response?
Only if we can compute the exact archive size in advance, which is possible with STORED entries and known sizes but not with deflated ones. Without it, the server uses chunked transfer encoding and the browser shows progress without a total, which is usually acceptable.
What if two thousand users click download at the same time?
Memory is no longer the limit, but threads, storage bandwidth and network are. The async executor should be bounded, excess requests should queue or be told to try later, and very large or popular archives should go through the background job and object storage.
Why add a BufferedOutputStream around the response stream?
ZipOutputStream writes many small pieces such as headers and descriptors. A buffer groups them into larger writes to the socket, which reduces system calls and CPU.
8Conclusion
In this answer, we saw that the endpoint ran out of memory because memory grew with the archive: a ByteArrayOutputStream, a second copy, and whole PDFs loaded at once. We streamed instead, with a ZipOutputStream over a StreamingResponseBody and each PDF copied from object storage as a stream, so memory stays at a buffer. We used DEFLATED with level 0 because STORED needs sizes and CRCs up front, handled errors and timeouts after the response has started, and moved very large archives to an asynchronous build with a pre-signed link.
Open with
The pods die because the endpoint builds the whole archive in memory: a ByteArrayOutputStream that keeps growing, a copy from toByteArray, and each PDF read fully into a byte array.
Then, if they want more
Two thousand PDFs of a couple of megabytes is about 4 GB, so memory scales with the archive, which can never work. I would make memory independent of size by streaming. The controller returns a StreamingResponseBody, and inside it I wrap the response OutputStream in a buffered stream and a ZipOutputStream.
For each document I open an InputStream from object storage, put a new entry, transferTo into the zip and close the entry. Memory is then a few buffers per download, and the user starts receiving bytes immediately. PDFs are already compressed, so I would not spend CPU deflating them.
STORED would be ideal but ZipOutputStream needs the size and CRC before writing a stored entry, which I do not know while streaming, so I keep DEFLATED with level zero or one, where the CRC is computed on the fly.
I would bound the async executor and check timeouts in Spring and in the load balancer, and decide how to handle a failure mid-stream, since the 200 is already sent. For really large archives I would switch to a background job that streams the zip into object storage and sends the user a pre-signed link.
The zip file system is handy for editing archives but cannot stream to a response.
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.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 Spring Boot endpoint builds a ZIP of 2,000 PDFs from object storage for download and...": https://scrivio-interview-library.netlify.app/java/io-and-nio/c56c3ea52b/