Spring streaming response made easy
In this short article, we'll get into stream large size of data through stream as an alternative to the traditional endpoints.


In this short article, we'll get into stream large size of data through stream as an alternative to the traditional endpoints.


Written by
Software engineer passionate about building scalable systems, exploring new technologies, and sharing knowledge through writing.
Get in touchWhat if you could get full distributed tracing on a plain Java HTTP server without adding any SDK, agent, or instrumentation code? This article walks through using Grafana Beyla and eBPF to automatically capture OpenTelemetry traces from a pure Java application, exporting them straight to Jaeger.
Is reactive programming still necessary in Java? This article explores the limitations of platform threads, the cost of reactive programming, and how Java Virtual Threads (Project Loom) offer a simpler path to scalable concurrency — without the complexity tax.
In certain scenarios, we need to retrieve large volumes of data, yet we often experience delays before the first pieces of the response are displayed. Fortunately, this is a well-known problem, and an effective solution exists.
This project is built using:
Simply, we need 1 million products (json objects) in the GET endpoint.
this is a simple SQL script to create and fill the products table:
Next the entity and JPA repository:
Nothing fancy for our traditional endpoint, a simple find all GET:
While using this endpoint, the client needs to wait before exploiting the first returned product, or even worse, the response size is too big to be handled properly:

Using StreamingResponseBody, we can stream our products one by one and save some time :)

You may already noticed that we loop over the products and write one by one to the output stream, this can be improved even more by streaming data end-2-end from the data source to the client; For that purpose solutions like Spring Webflux and JPA streams exist.
Stream<T>