Quick revision
The short answer
XSSFWorkbook builds the whole spreadsheet in memory as a tree of XML objects, so 500,000 rows can need several gigabytes of heap before a single byte is written. The fix is to stream: switch to SXSSFWorkbook, which keeps only a small window of rows in memory and flushes the rest to temporary files, and read the rows from the database with a cursor instead of a List. For very large or frequent exports, generate the file in the background, store it in object storage, send a link, and consider CSV when nobody needs formatting.
What to remember
In this answer, we saw that XSSFWorkbook holds the whole workbook as XML objects in memory, so a 500,000 row export needs far more heap than the file size suggests. We fixed the output side with SXSSFWorkbook, which keeps a window of rows and flushes the rest to temporary files that we must dispose of, and the input side with a forward-only cursor and a fetch size instead of a List. For the largest exports we moved the work to a background job that writes to object storage and sends a link, considered CSV when formatting is not needed, and limited concurrent exports and temporary disk use.
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.
XSSFWorkbook builds the whole spreadsheet in memory as a tree of XML objects, so 500,000 rows can need several gigabytes of heap before a single byte is written. The fix is to stream: switch to SXSSFWorkbook, which keeps only a small window of rows in memory and flushes the rest to temporary files, and read the rows from the database with a cursor instead of a List. For very large or frequent exports, generate the file in the background, store it in object storage, send a link, and consider CSV when nobody needs formatting.
Why this question is asked
Exports are one of those features that work perfectly in testing with 2,000 rows and then take down a production service on the first day a finance user asks for a full year. Interviewers ask this question because the fix touches several layers at once: how a library represents a file in memory, how a database driver returns rows, and how an HTTP endpoint should behave when work takes minutes. In this answer, we will see why XSSFWorkbook runs out of memory, fix it with SXSSFWorkbook, stream the rows from the database, and then look at asynchronous exports, CSV, and the operational limits that keep the fix safe.
1A Quick Recap of How POI Represents a Workbook
Apache POI is the Java library most teams use to read and write Microsoft Office files. A modern .xlsx file is really a zip archive of XML documents, one per sheet plus a few for styles and shared strings. POI's XSSFWorkbook class gives us an object model of that file: a workbook holds sheets, a sheet holds rows, and a row holds cells, each one a Java object backed by an XML bean.
That object model is convenient because we can go back to any cell, change it, or read the whole sheet again. The price is memory. Every cell carries the Java object, the XML bean behind it, and often a String, so the workbook in memory is commonly ten times or more the size of the finished file. A 60 MB export of 500,000 rows by 20 columns is 10 million cells, and at a few hundred bytes per cell the heap needs several gigabytes. Nothing is written until we call write() at the very end, so all of it has to fit at once.
2Reproducing the Problem
The typical first version loads every row into a List and then fills an XSSFWorkbook. Both steps hold the full data set in memory.
Notice that there are two copies of the data here: the entities from findAll() and the cell objects of the workbook. Even if we fixed only one of them, the other could still exhaust the heap, so a real fix has to stream at both ends.
3Fix 1: Switch to SXSSFWorkbook
SXSSFWorkbook is POI's streaming version of XSSFWorkbook. It keeps a sliding window of rows in memory, 100 by default. When we create row 101, row 1 is written to a temporary XML file on disk and dropped from the heap. At the end, POI zips those temporary files into the final .xlsx. Memory use is now proportional to the window size, not to the number of rows.
There is a catch: rows that have been flushed are gone from memory, so we cannot go back and change them, and features that need the whole sheet, such as autoSizeColumn(), only work for columns we ask POI to track before writing. We should also create cell styles once and reuse them, because a workbook has a limit of about 64,000 styles and a style per cell is a second, quieter memory leak.
Always clean up the temporary files. In older POI versions dispose() is the call that deletes them, and close() alone did not; recent versions have changed how close() and dispose() relate, so check your version and keep the cleanup in a finally block either way. A service that forgets this slowly fills its temporary directory until exports start failing with disk errors instead of memory errors.
4Fix 2: Stream the Rows From the Database
SXSSFWorkbook fixes the output side, but findAll() still loads 500,000 entities. We want the database to hand us rows a few hundred at a time, and to process each one and let it go. JDBC drivers do this with a fetch size, which asks the driver to pull rows from the server in batches through a cursor that only moves forward.
- Open a read-only transactionthe driver can now use a cursor
- Fetch 500 rowsone round trip to the database
- Write each row to SXSSFonly 100 rows stay on the heap
- Window full?YesFlush the oldest rows to a temp fileNoKeep writing
- More rows in the cursor?YesFetch the next 500NoZip the temp files into the response
- Dispose the workbooktemporary files are deleted
6 steps in order. Play them, or step through them one at a time.
Memory stays flat because neither the rows nor the cells are ever all in memory at once.
The reason for the transaction is a driver detail: the PostgreSQL driver ignores the fetch size and reads everything when autocommit is on, while MySQL needs useCursorFetch=true or its own streaming mode. With Spring Data JPA, the same idea is a repository method returning Stream<Order> with a fetch size hint, and we should detach or clear entities as we go so the persistence context does not keep all of them. Projecting only the columns we need, instead of full entities, saves more memory still.
In the controller, we write straight to the response with StreamingResponseBody, so the file goes to the client as it is produced instead of being built in a byte array first.
5Other Options for Very Large Exports
Streaming keeps memory flat, but a 500,000 row export can still take a minute or more, and an HTTP request that long is fragile: proxies time out, users click again, and each click starts another export. For large exports the better shape is asynchronous. The endpoint records an export job and returns 202 Accepted with a job id; a worker builds the file and uploads it to object storage such as S3; the user gets a notification or polls the job, and downloads the file through a link that expires after, say, 24 hours.
We should also ask whether the user needs a spreadsheet at all. A CSV file has no styles, no formulas and no zip step, can be written row by row with almost no memory, and opens in Excel. When people only want the data, CSV is faster for everyone. Some teams also use lighter streaming writers built only for writing xlsx; they trade POI's features for speed and memory, and are worth evaluating when POI is the bottleneck. Remember too that one Excel sheet holds at most 1,048,576 rows, so a growing export may need several sheets anyway.
6Keeping the Fix Safe in Production
Moving data from the heap to temporary files moves the risk to the disk. Ten concurrent exports of 60 MB each, plus their compressed copies, can fill a small container's temporary volume, so we size it, point POI's temp directory at a volume we monitor, and alert on free space.
We also limit how many exports can run at once, for example with a small dedicated thread pool or a semaphore of two or three permits per instance, and queue or reject the rest with a clear message. Without that limit, the same OutOfMemoryError comes back as soon as five people press Export together, because each export still has its window, its buffers and its database connection.
7Follow-up questions
Why not just give the service a bigger heap?
Because the memory needed grows with the size of the export, so a bigger heap only moves the limit. Next quarter's export is larger, or two users export at once, and the service fails again. Streaming makes memory use constant per export, which is the only kind of limit we can plan capacity around.
Can SXSSFWorkbook read files too?
No. SXSSF is only for writing. To read very large xlsx files, POI offers an event-based reader built on the XSSF event API with a SAX parser, which delivers cells as callbacks without building the object model. Reading a large file with XSSFWorkbook has the same memory problem as writing one.
How do we handle a user who closes the browser during a long synchronous export?
The servlet container usually notices when it next tries to write and throws an exception such as a client abort. Our code should treat that as a normal outcome, stop reading from the cursor, dispose the workbook and release the connection. That is another reason to prefer asynchronous exports for anything that takes more than a few seconds.
8Conclusion
In this answer, we saw that XSSFWorkbook holds the whole workbook as XML objects in memory, so a 500,000 row export needs far more heap than the file size suggests. We fixed the output side with SXSSFWorkbook, which keeps a window of rows and flushes the rest to temporary files that we must dispose of, and the input side with a forward-only cursor and a fetch size instead of a List. For the largest exports we moved the work to a background job that writes to object storage and sends a link, considered CSV when formatting is not needed, and limited concurrent exports and temporary disk use.
Open with
The root cause is that XSSFWorkbook keeps the entire workbook in memory as XML-backed objects, so memory grows with the number of cells and is often ten times the file size or more.
Then, if they want more
On top of that, the code usually loads all the rows with findAll first, so there are two full copies of the data. I would fix both ends.
On the output side I switch to SXSSFWorkbook with a window of about a hundred rows; older rows are flushed to temporary files, and I make sure dispose or close runs in a finally block so those files are deleted. I also reuse cell styles instead of creating one per cell.
On the input side I stream from the database with a fetch size, inside a read-only transaction because PostgreSQL needs that to use a cursor, using queryForStream or a Stream repository method, and I write straight to the response with StreamingResponseBody.
For really big exports I would not keep the HTTP request open at all: I would accept a job, build the file in a worker, put it in object storage and send the user an expiring link. If the users only need the data, CSV is simpler and cheaper.
Finally I would watch temporary disk space and cap concurrent exports per instance, because otherwise five simultaneous exports bring the same problem back.
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
- Spring Framework reference, Spring Web MVC
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 "An Excel export built with Apache POI's XSSFWorkbook for 500,000 rows makes the service...": https://scrivio-interview-library.netlify.app/spring-boot/web-other/bd72308b3a/