Video in progress

Strong Middle 🌱 Spring

How do you return a 1 GB file or a large CSV report through a controller without filling up memory?

You stream the response instead of assembling it as a byte[]: a Resource (FileSystemResource) for a ready-made file, and StreamingResponseBody for generated data. And you read the data from the database in pages or as a Stream, and write it to the output right away.

📖 Answer

The wrong approach is byte[] data = Files.readAllBytes(path) or building the report in a StringBuilder. If 10 users download at once, that's 10 GB of heap.

A ready-made file:

@GetMapping("/api/files/{id}")
ResponseEntity<Resource> download(@PathVariable UUID id) {
    StoredFile f = files.find(id);
    return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .contentLength(f.size())
            .header(HttpHeaders.CONTENT_DISPOSITION,
                    ContentDisposition.attachment().filename(f.name(), StandardCharsets.UTF_8).build().toString())
            .body(new FileSystemResource(f.path()));
}

ResourceHttpMessageConverter reads and writes the file with a buffer, and it also understands the Range header, so an interrupted download can be resumed.

A generated report:

@GetMapping(value = "/api/reports/orders.csv", produces = "text/csv")
StreamingResponseBody export(@RequestParam LocalDate from) {
    return out -> {
        try (Writer w = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) {
            w.write("id,sana,summa\n");
            reportDao.forEachOrder(from, row -> {   // with JdbcTemplate + fetchSize
                w.write(row.id() + "," + row.date() + "," + row.total() + "\n");
            });
        }
    };
}

Subtle points here:

  • StreamingResponseBody runs in async mode, on the MVC executor, so spring.mvc.async.request-timeout must not cut off a long export.
  • Reading from the database should be a stream too: in PostgreSQL fetchSize works only in a transaction with autocommit off; otherwise the driver pulls all the rows into memory.
  • If you read with JPA, the persistence context holds on to every row, so detach or using JDBC is better.
  • For very big, frequently requested reports, prepare the file in the background and hand it out through a signed link from object storage; then this load leaves the application entirely.