Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

How do you stream a large CSV export from a Spring MVC endpoint without loading all rows into memory?

We return a StreamingResponseBody, which Spring MVC calls on an async thread with the response OutputStream, and we write each row as soon as we read it. Rows come in incrementally, through JdbcTemplate with a RowCallbackHandler and a fetch size, or a Stream from a Spring Data repository inside a read-only transaction. We set Content-Type text/csv and a Content-Disposition filename, configure spring.mvc.async.request-timeout and a task executor, and with JPA we use projections or clear the persistence context so memory stays flat.

Why this question is asked

The usual first version of a CSV export calls findAll(), builds a List of a million entities, turns it into one big String and returns it. It works with 1,000 test rows and fails in production with an OutOfMemoryError or a garbage-collection storm that slows every other request. Interviewers ask this question because streaming touches several layers at once: the web layer, the database driver, transactions and the persistence context. In this answer, we will recap what streaming means here, write the endpoint with JdbcTemplate, look at the async settings it depends on, do the same with a Spring Data Stream, and see the JPA memory trap.

1A Quick Recap of Streaming a Response

Streaming means that at any moment only a small window of the data is in memory: we read a row, write it to the response, and let it be garbage collected before reading the next one. Memory use is then constant, a few megabytes, whether the export has 10,000 rows or 10 million. For this to work, every stage must stream: the database must send rows in batches instead of all at once, our code must not collect them in a list, and the web layer must write to the socket as we go.

StreamingResponseBody is Spring MVC's tool for the last part. It is a functional interface with one method, writeTo(OutputStream). When a controller returns it, Spring starts asynchronous request processing, releases the servlet container thread, and calls writeTo on a thread from its task executor, where we write directly to the response.

Step throughOne row's journey through the export
  1. Driver fetches a batch1,000 rows per round trip, set by fetch size
  2. RowCallbackHandler gets one rowno List is built
  3. Format as a CSV linequote fields that contain commas or quotes
  4. Write to the buffered OutputStreambytes flushed to the client in chunks
  5. Row becomes garbagememory stays flat

5 steps in order. Play them, or step through them one at a time.

2Writing the Endpoint With JdbcTemplate

Here is a complete endpoint. Notice that the query runs inside writeTo, so it runs on the async thread, and that we open a read-only transaction there with TransactionTemplate.

Java
@GetMapping("/orders/export")
ResponseEntity<StreamingResponseBody> export() {
StreamingResponseBody body = out -> {
Writer w = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
w.write("id,customer,total\n");
readOnlyTx.executeWithoutResult(status ->
jdbc.query(con -> {
PreparedStatement ps = con.prepareStatement(
"select id, customer, total from orders order by id");
ps.setFetchSize(1000); // 1,000 rows per round trip
return ps;
}, (RowCallbackHandler) rs -> {
try {
w.write(rs.getLong(1) + "," + csv(rs.getString(2)) + "," + rs.getBigDecimal(3) + "\n");
} catch (IOException e) {
throw new UncheckedIOException(e); // client went away
}
}));
w.flush();
};
return ResponseEntity.ok()
.contentType(new MediaType("text", "csv", StandardCharsets.UTF_8))
.header(HttpHeaders.CONTENT_DISPOSITION,
ContentDisposition.attachment().filename("orders.csv").build().toString())
.body(body);
}
// response: 200, Content-Type: text/csv;charset=UTF-8,
// Content-Disposition: attachment; filename="orders.csv"

A RowCallbackHandler receives one row at a time and returns nothing, which is exactly why it streams: JdbcTemplate never builds a result list. The fetch size tells the driver how many rows to pull per round trip. But there is a catch: drivers differ. The PostgreSQL driver only uses a cursor, and honours the fetch size, when auto-commit is off, which is why we run the query inside a transaction; MySQL Connector/J needs useCursorFetch=true or its own streaming mode. Check your driver's documentation, because without this the driver silently loads every row into memory before our handler sees the first one.

The headers make the browser treat the response as a file download named orders.csv. The csv() helper wraps values in quotes and doubles embedded quotes, so a customer called "Smith, Jones" does not break the column layout.

3Configuring the Async Side

Because StreamingResponseBody runs as async processing, two settings apply. The first is the async request timeout. If we set nothing, the servlet container's default is used, 30 seconds in Tomcat, and an export that takes longer fails with AsyncRequestTimeoutException even while it is still writing. The second is the executor that runs writeTo. Spring Boot uses its application task executor, a bounded thread pool, or virtual threads when spring.threads.virtual.enabled is true.

Properties
# application.properties
spring.mvc.async.request-timeout=10m # whole export may take up to 10 minutes
spring.task.execution.pool.max-size=16 # at most 16 exports writing at once
spring.task.execution.pool.queue-capacity=100

The reason the pool size matters is that each running export holds a database connection for its whole duration. With a connection pool of 20 and unlimited concurrent exports, a burst of downloads can take every connection and stall normal requests, so we keep export concurrency below the pool size.

4Streaming With a Spring Data Repository

With Spring Data JPA, a repository method can return Stream<T>. The stream is backed by an open JDBC result set, so it must be consumed inside a transaction and closed when done.

Java
public interface OrderRepository extends JpaRepository<Order, Long> {
@QueryHints(@QueryHint(name = "org.hibernate.fetchSize", value = "1000"))
@Query("select new com.shop.OrderRow(o.id, o.customer, o.total) from Order o order by o.id")
Stream<OrderRow> streamRows(); // record projection, not entities
}
StreamingResponseBody body = out -> readOnlyTx.executeWithoutResult(s -> {
try (Stream<OrderRow> rows = orders.streamRows()) { // closes the result set
rows.forEach(r -> writeLine(out, r));
}
});

Notice two choices here. We use a record projection (OrderRow) instead of the Order entity, and we open the transaction inside writeTo. A @Transactional on the controller method would not help, because that transaction would end when the method returns the StreamingResponseBody, before writeTo ever runs on the other thread.

5The JPA Persistence Context Trap

If we stream entities rather than projections, there is a second memory problem. The persistence context, the first-level cache in which Hibernate keeps every entity it has loaded in the current transaction so it can detect changes, holds a reference to each entity. Streaming a million Order entities therefore keeps a million entities alive, and the export runs out of memory just as if we had used a List.

There are two fixes. The simplest is to use projections, records or interfaces, which are not managed and are not stored in the persistence context. If we really need entities, we call entityManager.detach(order) after writing each one, or entityManager.clear() every 1,000 rows, so the context stays small.

6Follow-up questions

Why does a Spring Data Stream<T> need an open transaction?

Because the stream is lazy: rows are read from an open JDBC result set while we consume it, and that result set needs its connection to stay open. In Spring, the connection is bound to the transaction; when the transaction ends, the connection goes back to the pool and the result set is closed. Spring Data therefore refuses to run a streaming query without a surrounding transaction and throws InvalidDataAccessApiUsageException. We also close the stream with try-with-resources so the cursor is released as soon as we finish.

What happens if the user cancels the download halfway?

The next write to the OutputStream fails with an IOException, often a ClientAbortException in Tomcat. We let it propagate, wrapped as UncheckedIOException inside the row handler, so the query stops, the transaction rolls back and the connection returns to the pool. Catching and ignoring it would keep reading rows that nobody will receive.

Can I set Content-Length on a streamed CSV?

Usually not, because we do not know the size until the last row is written. Without it, the server uses chunked transfer encoding on HTTP/1.1, and the browser shows progress without a total. That is normal for streamed exports.

7Conclusion

In this answer, we streamed a CSV export by returning StreamingResponseBody, which Spring MVC calls on an async thread with the response OutputStream. We read rows incrementally with JdbcTemplate, a RowCallbackHandler and a fetch size inside a read-only transaction, or with a Spring Data Stream of projections, and set text/csv and a Content-Disposition filename. We configured spring.mvc.async.request-timeout and the task executor, and saw that JPA entities must be detached or replaced by projections so the persistence context does not grow.

What to say in the interviewAbout 80 seconds aloud

Open with

I would return a StreamingResponseBody. Spring MVC treats it as asynchronous processing: it releases the container thread and calls writeTo on a task executor thread with the response's OutputStream, so I can write each row as I read it and memory stays constant.

Then, if they want more

Inside writeTo I open a read-only transaction with TransactionTemplate and run a JdbcTemplate query with a RowCallbackHandler, which handles one row at a time without building a list, and I set a fetch size of around a thousand so the driver uses a cursor; with PostgreSQL that only works inside a transaction, so the transaction matters.

I set Content-Type to text/csv and a Content-Disposition attachment header with the filename using ContentDisposition. Because it is async, I set spring.mvc.async.request-timeout, otherwise Tomcat's default of 30 seconds applies, and I size the task executor so concurrent exports cannot take all the database connections.

If I use Spring Data, a Stream of projections from the repository works too, but it must be consumed inside a transaction and closed, and the transaction has to start inside writeTo, not on the controller method, because writeTo runs later on another thread. With entities I would clear or detach the persistence context regularly, but projections avoid that problem.

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 "How do you stream a large CSV export from a Spring MVC endpoint without loading all rows...": https://scrivio-interview-library.netlify.app/spring-boot/web-other/347db9c1b2/