A streaming response shifts output to an executor; close its cursor and end production when a write fails.
Spring MVC streaming response: stop work when the client disconnects
Stream from a bounded source
A receipt CSV export may contain enough rows that building one byte array would consume excessive heap. StreamingResponseBody writes chunks directly to the response, but it does not give the export unlimited time or free threads. Use the configured MVC async executor and a database cursor or paged reader with an explicit resource lifetime. Executor capacity sets the concurrency ceiling; upload limits protect the opposite direction.
Treat write failure as cancellation
A browser that closes its download may cause a write or flush to throw IOException. Stop reading further rows and let try-with-resources close the cursor. Do not catch the exception and keep generating receipts; doing so burns database work for a socket that no longer exists. If the export is a durable business job rather than an interactive download, persist its progress and let the client fetch a completed artifact instead of holding one HTTP connection open.
Prove cleanup under a broken connection
Start an export of 47 rows, close the client after the first chunk, and assert the cursor closes promptly while later rows are not fetched. Repeat with a slow reader and a server shutdown. Once headers or bytes have been written, an error handler often cannot replace the response with a clean JSON problem body; record the failure server-side without leaking receipt contents. Shutdown draining needs an explicit deadline for these long responses.
Implementation contract
@GetMapping(value = "/receipts/export", produces = "text/csv")
StreamingResponseBody exportReceipts() {
return output -> {
try (ReceiptCursor cursor = receipts.openExportCursor()) {
while (cursor.hasNext()) {
output.write(cursor.nextCsvRow());
}
output.flush();
}
};
}Cost and verification
Streaming reduces peak heap from the full export size to a row and output buffer, but every active download still holds a worker, cursor and connection until completion or failure.
Common Mistakes
- Do not retain an open database cursor after a client disconnect.
- Do not catch IOException and continue generating the rest of the export.
- Do not promise a structured error body after response bytes have already been sent.
Read next
Spring MVC async executor: bound Callable work before requests pile up, Spring Boot graceful shutdown: finish accepted requests within a deadline, Spring multipart size limits: enforce parser and application budgets, Spring API pagination: bounded requests and immutable snapshots, Spring task executors: capacity, rejection and lost context.
Related delivery contract
Spring MVC byte ranges: resume an authorized receipt download.
