Kest

Search

Search the documentation

HTTP

Streaming responses

Send a big file or a long export without loading it into memory.

Reading a 2 GB file into memory to return it would exhaust the server. Streaming sends it piece by piece: read a chunk, send a chunk. Return a StreamableFile:

@Get("/report.csv")
fun report(): StreamableFile = StreamableFile(File("/data/report.csv").inputStream(), contentType = "text/csv", filename = "report.csv")   // attachment
 
@Get("/logo") fun logo() = StreamableFile(bytes, contentType = "image/png", inline = true)          // shown in the browser
ParameterMeaning
contentTypethe file's type (text/csv, application/pdf, image/png)
filenamethe browser offers it as a download with this name
inline = trueshow it in the page (an image, a PDF) instead of downloading

The body is copied in 16 KB chunks. A handler runs on its own virtual thread, so writing slowly (a long export, a slow client) does not block anyone else.

A generated export

class OrdersCsv(private val orders: OrderRepository) : ResponseStream {
    override val contentType = "text/csv"
    override val headers = mapOf("content-disposition" to "attachment; filename="orders.csv"")
 
    override fun writeTo(sink: StreamSink) {                          // runs on the request's virtual thread; may block between writes
        sink.write("id,total
".toByteArray())
        var page = 1
        do {
            val batch = orders.findAll(PageRequest.of(page++, 1000))      // one page at a time: never holds all the rows
            batch.items.forEach { sink.write("${it.id},${it.total}
".toByteArray()) }
        } while (batch.hasNext)
    }
}
 
@Get("/orders.csv") fun export() = OrdersCsv(orders)               // a ResponseStream is a valid return value

Implement ResponseStream (contentType, optional headers, writeTo(sink)) for any body produced over time; or take @Response res: RawResponse and call res.stream(yourStream).

Good practice

  • Read the database in batches (cursor or pagination), not findAll().
  • Set a correct contentType and a filename; check the user may access the file before streaming.
  • Behind a proxy, make sure response buffering is off for streams.
  • Large uploads are the opposite direction and are held in memory: see File upload and streaming.

For events pushed to a browser use Server-Sent Events.

Read more