Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Return a streaming answer from a Spring MVC endpoint so the browser shows tokens as they arrive. Show the Spring AI call and the controller method, and say what happens when the user closes the tab.

We return the Flux from Spring AI straight from the controller: @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE) Flux<String> chat(@RequestParam String q) { return chatClient.prompt().user(q).stream().content(); }. Spring MVC writes a Flux as server-sent events when Reactor is on the classpath, and WebFlux does so natively. When the user closes the tab, the subscription is cancelled, and we should verify that this also cancels the provider HTTP call so we stop paying for tokens; stream().chatResponse() gives metadata such as finish reason and usage, and proxies must not buffer the response.

Why this question is asked

A model can take ten or twenty seconds to write a long answer. Waiting for all of it before showing anything feels broken; seeing words appear after half a second feels fast, even though the total time is the same. That is why almost every chat interface streams. Interviewers ask this question to see whether we can wire streaming end to end in Spring and whether we think about what happens when the user leaves. In this answer, we will recap streaming and server-sent events, write the endpoint, see how Spring MVC handles a Flux, deal with the closed tab, get metadata from the stream, and check the network path.

1A Quick Recap of Streaming and Server-Sent Events

Models generate text token by token, and providers can send each piece as soon as it is ready instead of waiting for the end. Spring AI exposes this with stream(), which returns a Flux, a Reactor type for a sequence of values that arrive over time.

To get those pieces to a browser over plain HTTP, the standard tool is server-sent events, or SSE. The server keeps the response open with the content type text/event-stream and writes small messages, each starting with data: and ending with a blank line. The browser's EventSource API, or fetch with a reader, receives them one by one.

Text
data:Hello
data: there
data:, here is
data: your answer

That is all SSE is on the wire: text messages separated by blank lines, on a response that stays open until the server finishes.

2Writing the Endpoint

In Spring AI, the only difference from a normal call is stream() in place of call(). We return the resulting Flux<String> directly.

Java
@RestController
class ChatController {
private final ChatClient chatClient;
ChatController(ChatClient.Builder builder) { this.chatClient = builder.build(); }
@GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> chat(@RequestParam String q) {
return chatClient.prompt().user(q).stream().content();
}
}
// curl -N "http://localhost:8080/chat?q=Explain%20HTTP%20caching"
// data:HTTP
// data: caching
// data: lets clients
// ... <- pieces arrive over several seconds

Notice the produces attribute. It tells Spring to write the Flux as an event stream, one SSE message per element, instead of collecting everything into one JSON array. In the browser, a few lines of JavaScript append each message to the page as it arrives.

3How Spring MVC Handles a Flux

Spring MVC is built on the servlet API and normally writes one response per request. But it supports reactive return types when Project Reactor is on the classpath, which it is because Spring AI depends on it. When a controller returns a Flux with an event stream media type, Spring MVC starts asynchronous request processing: the servlet thread is released, and each element is written and flushed to the response as the Flux emits it. In WebFlux, the reactive web stack, this is native and works the same way from our code's point of view.

Because the MVC version uses asynchronous request processing, the async request timeout applies to the whole stream. If it is shorter than the longest answer, the stream is cut off, so we set spring.mvc.async.request-timeout deliberately, for example to two minutes.

Step throughStreaming one answer to the browser
BrowserControllerChatClientProvider
GET /chat?q=...
stream().content()
streaming HTTP request
token chunks
Flux elements
SSE data: messages, flushed one by one
tab closed: connection dropped
cancel subscription
close provider connection

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

4What Happens When the User Closes the Tab

When the browser closes the connection, the server notices the next time it tries to write, or through the container's async listener, and Spring cancels the subscription to the Flux. Cancellation travels upstream through Reactor, so Spring AI's streaming call should close its HTTP connection to the provider, and the provider stops generating.

That last part is what saves money: providers charge for the tokens they generate, and an abandoned 2,000-token answer that keeps running still costs the full amount. So we verify it rather than assume it, by logging cancellation and watching the provider connection close.

Java
Flux<String> chat(@RequestParam String q) {
return chatClient.prompt().user(q).stream().content()
.doOnCancel(() -> log.info("client went away, stream cancelled"))
.doOnComplete(() -> log.info("stream completed"));
}
// close the tab mid-answer:
// client went away, stream cancelled

If the log shows the cancel but the provider usage still reports the full answer, something in between is not propagating cancellation, for example an HTTP client configuration or a custom operator that subscribes again, and that is worth fixing.

5Getting Metadata From the Stream

content() gives us only the text. When we need the finish reason (did the model stop naturally or hit the token limit) or token usage, we use stream().chatResponse(), which emits ChatResponse objects. Usage typically arrives in the last element, after the text, and some providers only send it when asked (check your provider's streaming options).

Java
Flux<ChatResponse> responses = chatClient.prompt().user(q).stream().chatResponse();
responses
.doOnNext(r -> {
if (r.getMetadata().getUsage() != null && r.getMetadata().getUsage().getTotalTokens() > 0) {
log.info("tokens={}", r.getMetadata().getUsage().getTotalTokens()); // tokens=812, on the last element
}
})
.map(r -> r.getResult() == null ? "" : r.getResult().getOutput().getText())
.subscribe();

6The Network Path Must Not Buffer

Streaming only works if every hop forwards bytes immediately. A reverse proxy such as nginx buffers responses by default, an API gateway may collect the whole response, and a compression filter may wait for enough data to compress. Any of them turns a stream into one late answer. So for the event-stream route we turn off proxy buffering (in nginx, proxy_buffering off, or the X-Accel-Buffering: no response header), avoid gzip on that route, and set idle and response timeouts at load balancers long enough for the longest answer, or send periodic comment lines as heartbeats.

7Follow-up questions

How would you send structured events (for example citations) with the text?

Return Flux<ServerSentEvent<?>> instead of Flux<String>, and give each event a name: token events carry text pieces, a citations event carries a JSON list of sources, and a done event carries the finish reason and usage. The browser listens for each event name separately. We can build them by mapping stream().chatResponse() to token events and concatenating a final Flux with the citations collected from the retrieval step.

Is WebFlux required for streaming?

No. Spring MVC handles Flux return types with asynchronous request processing. WebFlux is a good choice when the whole application is reactive or must hold very many concurrent streams, but it is not required for an MVC application to stream.

Why does curl need -N?

curl buffers output by default; -N turns that off so we see the events as they arrive, which is also a quick way to test whether a proxy is buffering.

8Conclusion

In this answer, we streamed a Spring AI answer by returning chatClient.prompt().user(q).stream().content() from a controller that produces text/event-stream. Spring MVC writes a Flux as server-sent events through asynchronous request processing when Reactor is present, and WebFlux does it natively. Closing the tab cancels the subscription, which should cancel the provider call so we stop paying, stream().chatResponse() gives finish reason and usage, and every proxy on the path must forward the stream without buffering.

What to say in the interviewAbout 70 seconds aloud

Open with

I would write a controller method with @GetMapping, produces MediaType.TEXT_EVENT_STREAM_VALUE, that returns Flux<String>, and inside it return chatClient.prompt().user(q).stream().content(). The produces attribute makes Spring write each element as a server-sent event and flush it, so the browser shows tokens as they arrive.

Then, if they want more

In Spring MVC this works because Reactor is on the classpath, which Spring AI brings in, and MVC uses asynchronous request processing, so I set spring.mvc.async.request-timeout long enough. In WebFlux it is native.

When the user closes the tab, the container sees the dropped connection and Spring cancels the subscription; the cancellation should propagate to Spring AI's HTTP call to the provider so generation stops and we stop paying for tokens. I would verify that with a doOnCancel log and the provider's usage.

If I need the finish reason or token usage, I use stream().chatResponse(), where usage usually arrives on the last element. Finally, I make sure proxies, gateways and compression do not buffer the event stream, for example proxy_buffering off in nginx, and that load balancer timeouts are long enough.

About this answer

Last updated
12 November 2026
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
Spring AI reference
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 "Return a streaming answer from a Spring MVC endpoint so the browser shows tokens as they...": https://scrivio-interview-library.netlify.app/spring-boot/spring-ai/100dcc6b8f/