Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a JAX-RS endpoint that streams 2 million rows as CSV from a database without building the whole file in memory. What happens if the client disconnects halfway?

We return Response.ok((StreamingOutput) out -> {...}).type("text/csv") and, inside, read rows with a forward-only cursor and a fetch size and write each one through a BufferedWriter as it arrives, so memory stays flat whatever the row count. If the client disconnects halfway, the next write throws an IOException; we catch it, stop reading, release the connection and log it as a client abort, not a server error. Because the 200 status is already sent, a later failure cannot become a 500, so very large exports may be better as a background job with a download link.

Why this question is asked

Exports are where many services first meet out-of-memory errors. Building 2 million rows into a list, then into a string, can take gigabytes, and the user waits for the whole file before the first byte arrives. Interviewers ask this question because streaming touches the HTTP layer, the database driver and error handling at once, and the disconnect case shows whether we understand what happens after the response has started. In this answer, we will recap why building the file fails, write the streaming endpoint, make the database side stream too, handle a client disconnect, and discuss what to do about errors once the status is committed.

1Why Building the Whole File Fails

The naive version loads every row into a List, formats it into a String or byte array, and returns it. For 2 million rows of about 120 bytes each, the CSV alone is around 240 MB, the Java objects behind it are several times larger, and all of it must exist at once before the first byte is sent. Under a few concurrent exports, the heap is gone. Streaming changes the shape of the work: read one row, write one row, forget it. Memory then depends on the buffer size, not on the number of rows.

2Writing the Streaming Endpoint

JAX-RS gives us StreamingOutput, a callback with a single write(OutputStream) method. The runtime calls it after the response headers are sent, with the stream that goes to the client.

Java
@GET
@Path("/orders/export")
@Produces("text/csv")
public Response export(@QueryParam("from") LocalDate from) {
StreamingOutput body = out -> {
try (Writer w = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8), 64 * 1024)) {
w.write("id,customer,total,created\n");
exporter.forEachOrder(from, o -> { // rows arrive one at a time
try {
w.write(csvLine(o)); // e.g. 42,"Smith, Ann",19.90,2026-10-01
} catch (IOException e) {
throw new UncheckedIOException(e); // lambda cannot throw IOException directly
}
});
} catch (UncheckedIOException e) {
throw e.getCause(); // let the disconnect handling below see it
}
};
return Response.ok(body)
.type("text/csv; charset=UTF-8")
.header("Content-Disposition", "attachment; filename=\"orders-" + from + ".csv\"")
.build();
}
// Memory: about 64 KB of buffer per export, whether it has 2 thousand or 2 million rows

Notice that csvLine must quote fields containing commas, quotes or newlines, as in "Smith, Ann", and double any quote inside them, or the file breaks in a spreadsheet. A field that starts with =, + or @ should also be neutralised, because spreadsheets treat it as a formula, a problem known as CSV injection. Content-Disposition tells the browser to save the response as a file with that name.

3Streaming From the Database Too

Streaming the HTTP side is not enough if the database side still loads everything. Many JDBC drivers read the whole result set into memory by default; the PostgreSQL driver, for example, only uses a cursor when autocommit is off and a fetch size is set. So we read forward-only with a fetch size, inside a transaction that lasts only as long as the stream.

Java
public void forEachOrder(LocalDate from, Consumer<OrderRow> sink) {
try (Connection c = dataSource.getConnection()) {
c.setAutoCommit(false); // PostgreSQL needs this for a cursor
c.setReadOnly(true);
try (PreparedStatement ps = c.prepareStatement(
"SELECT id, customer, total, created FROM orders WHERE created >= ? ORDER BY id",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
ps.setFetchSize(1000); // 1000 rows per round trip, not 2 million at once
ps.setObject(1, from);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) sink.accept(OrderRow.from(rs));
}
} finally {
c.rollback(); // read-only: nothing to commit
}
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
Step throughOne streamed export
ClientJAX-RS runtimeStreamingOutputDatabase
GET /orders/export
200 headers sent: status now committed
write(out)
fetch 1000 rows
rows 1-1000
write CSV lines, flush buffer
fetch next 1000 rows
rows 1001-2000
... until the last row
return: response complete

10 messages in order. Play them, or step through them one at a time.

With JPA or Spring Data, a Stream<Order> query with a fetch size hint does the same job, but the entity manager must not keep 2 million entities in its persistence context, so we detach or clear as we go, or use a projection. A plain SELECT at READ COMMITTED takes no locks that block writers, while SELECT ... FOR UPDATE would block order processing for the whole download.

4What Happens When the Client Disconnects

Suppose the user closes the browser tab at row 800,000. The server does not know immediately; it finds out the next time it tries to write. The write, or the flush of the buffer, throws an IOException, which in Tomcat appears as a ClientAbortException, a subclass of IOException, and in other containers as a broken pipe or connection reset. Our code must then stop reading, so the database is not asked for 1.2 million rows that nobody will receive, and release the connection, which the try-with-resources blocks do as the exception propagates.

What we should not do is log a stack trace at ERROR level and count it as a server failure. A client leaving is normal. We log it at INFO or DEBUG with the row count reached and the request id, and keep a metric of aborted exports, which is useful in itself: many aborts may mean the export is too slow.

Java
} catch (IOException e) {
if (isClientAbort(e)) {
log.info("export aborted by client after {} rows", count); // not an error
return; // connection released by try-with-resources
}
throw e;
}

5Errors After the Status Is Committed

There is a subtle consequence of streaming. The status line and headers went out before the first row. If the database fails at row 1.5 million, we cannot change the response to a 500; the client has already been told 200. The best the server can do is stop writing and close the connection abruptly, so the client sees a truncated download rather than a file that looks complete. Without a Content-Length, the client can only detect that truncation if the response is chunked and the final chunk never arrives, which browsers and HTTP clients do report as an error.

Two designs make this explicit. A trailer row, such as #end,rows=2000000, lets the consumer verify the file is complete. And for very large or slow exports, a job is often better: POST /exports creates a background job that writes the file to object storage, the client polls or is notified, and downloads it from a link. That survives disconnects, can resume, and keeps request threads free.

6Follow-up questions

Does a StreamingOutput hold a request thread for the whole download?

With a classic servlet container, yes: the write callback runs on a request thread until the last byte is written, so 50 concurrent exports use 50 threads. That is usually fine for exports, and with virtual threads in Java 21 and later the cost of a blocked thread is small. For very many concurrent downloads, the background job design is better.

Why not return a Stream or a List and let JSON or CSV providers handle it?

A List must be complete in memory before writing, which defeats the purpose. Some implementations support streaming collections, but StreamingOutput is portable and makes the streaming obvious to the next reader.

7Conclusion

In this answer, we streamed 2 million rows as CSV with StreamingOutput and a buffered writer, so memory stays at the buffer size instead of the file size. We made the database side stream as well with a forward-only cursor and a fetch size, without holding locks, and kept the connection open only while streaming. A client disconnect shows up as an IOException on write, which we treat as a normal abort: stop reading, release the connection, log it quietly. Because the status is committed before the first row, later failures cannot become a 500, so a trailer row or a background job with a download link is the safer design for very large exports.

What to say in the interviewAbout 90 seconds aloud

Open with

I would return a Response wrapping a StreamingOutput with type text/csv and a Content-Disposition header so the browser saves it as a file. Inside the callback I wrap the output stream in a BufferedWriter with UTF-8 and write the header line, then each row as it comes from the database, with proper CSV quoting.

Then, if they want more

The database side must stream too: a forward-only result set with a fetch size of about 1000, and for PostgreSQL autocommit off, otherwise the driver loads everything into memory. With JPA I would use a Stream query and keep the persistence context from growing.

The connection is held only for the duration of the stream, and the query is a plain read so it does not hold locks that block writers. Memory then stays at the buffer size whether there are two thousand or two million rows.

If the client disconnects, the server notices on the next write, which throws an IOException, in Tomcat a ClientAbortException. I catch that, stop reading, let try-with-resources release the connection, and log it at info level, not as a server error.

And one thing to know: once the first bytes are sent the 200 is committed, so a failure midway cannot become a 500. For very large exports I would add a trailer row or move to a background job with a download link.

About this answer

Last updated
12 November 2026
Versions it names
Java 21
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
Jakarta EE specifications
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 "Write a JAX-RS endpoint that streams 2 million rows as CSV from a database without...": https://scrivio-interview-library.netlify.app/java/jax-rs/43b9fd4974/