Streaming Spring AI Answers to the Browser: stream(), a Flux of Server-Sent Events and the Cancel
The blocking call shows a blank screen for 3.13 s; a Flux of server-sent events puts the first word on screen after 0.44 s. Along the way: why plain-text chunks turn into AnHTTP502status, why a Flux without text/event-stream still waits 3.16 s, and the log line that proves the model call stops when the user leaves.
What you will learn
- Stream a Spring AI answer with stream().content() and a Flux
- Send each chunk as a named server-sent event with ServerSentEvent
- Avoid the two traps: a missing text/event-stream and lost spaces in plain-text chunks
- See the model call cancelled when the browser closes the connection
Before you start
- Spring AI ChatClient basics
- Basic JavaScript in the browser
The model takes about the same time whether you stream or not. Streaming changes when the user sees the first word. This article follows one question, "What does an HTTP 502 status mean?", through four endpoints of a small app, StreamDesk, and measures each one.
The blocking call: a blank screen
@GetMapping("/answer")
public String answer(@RequestParam String question) {
return chat.prompt()
.user(u -> u.text(explainPrompt).param("question", question))
.call()
.content();
}
curl -s -G localhost:8105/answer \
--data-urlencode "question=What does an HTTP 502 status mean?" \
-w "\n[%{time_starttransfer}s to the first byte, %{time_total}s in total]"
An HTTP 502 status code indicates a "Bad Gateway" error, which means the server received an invalid response from an upstream server or proxy. This error typically occurs when there's a problem with the server's connection to another server, and the request cannot be fulfilled.
[3.133976s to the first byte, 3.134050s in total]
call() returns only when the last word is written, so the first byte arrives with the last one, after 3.13 seconds. For the user that is 3 seconds of nothing.
stream() and a Flux
@GetMapping(value = "/stream/text", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> text(@RequestParam String question) {
return chat.prompt()
.user(u -> u.text(explainPrompt).param("question", question))
.stream()
.content();
}
stream() instead of call() hands over the answer in small chunks, a word or less each. The method returns a Flux, and with the content type text/event-stream Spring Boot writes each element to the browser the moment it is emitted.
data:An
data: HTTP
data:
data:502
Each chunk is one event: the word data, a colon and the text. The space in front of HTTP belongs to the chunk, and that is about to cause trouble.
The lost-space bug
The SSE format says a reader strips one space after data:. A chunk that starts with a space loses it. Here is what an EventSource client gets from /stream/text:
AnHTTP502statuscodeindicatesa"BadGateway"error,whichmeanstheserver
receivedaninvalidresponsefromanupstreamserverorproxy...
The fix is a record around each chunk, so the text travels as JSON and keeps its spaces:
// One piece of the answer, sent as JSON: {"text":" HTTP"}
// The SSE format drops one leading space after "data:", so plain text loses it
public record Chunk(String text) {
}
Named events, and a last "done" event
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<Chunk>> stream(@RequestParam String question) {
AtomicInteger sent = new AtomicInteger();
Flux<ServerSentEvent<Chunk>> tokens = chat.prompt()
.user(u -> u.text(explainPrompt).param("question", question))
.stream()
.content()
.map(text -> ServerSentEvent.builder(new Chunk(text))
.id(String.valueOf(sent.incrementAndGet()))
.event("token")
.build());
ServerSentEvent<Chunk> done = ServerSentEvent.<Chunk>builder()
.event("done").data(new Chunk("")).build();
return tokens.concatWith(Flux.just(done))
.doOnCancel(() -> log.info("Client left after {} chunks", sent.get()))
.doOnComplete(() -> log.info("Finished after {} chunks", sent.get()))
.doOnError(e -> log.warn("Failed after {} chunks", sent.get(), e));
}
id:1
event:token
data:{"text":"An"}
id:2
event:token
data:{"text":" HTTP"}
id:3
ServerSentEvent sets all the event fields, not just the data. The page listens for token events, a counter fills id, and a final done event tells the page the answer is complete. Read through the same client, the sentence comes back exactly as the model wrote it.
The trap that still looks reactive
// Common mistake: no produces = text/event-stream, so one JSON array at the end
@GetMapping("/stream/buffered")
public Flux<Chunk> buffered(@RequestParam String question) {
return chat.prompt()
.user(u -> u.text(explainPrompt).param("question", question))
.stream()
.content()
.map(Chunk::new);
}
[{"text":"An"},{"text":" HTTP"},{"text":" "},{"text":"502"},{"te ...
[3.155585s to the first byte, 3.155657s in total]
Without the event-stream content type, Spring waits for the whole Flux and sends one JSON array. It compiles, it returns a Flux, and nothing warns you. The user is back to a blank screen for 3.16 seconds.
When the user leaves
curl -s -N -G localhost:8105/stream \
--data-urlencode "question=What does an HTTP 502 status mean?" --max-time 2 | tail -3
event:token
data:{"text":" response"}
... in the app log ...
Client left after 24 chunks
curl stopped reading after two seconds. When the connection drops, Reactor cancels the stream, the call to the model is cancelled with it, and doOnCancel logs how far the answer got. A finished answer logs through doOnComplete instead, so the two endings can be told apart. A cancelled call stops spending tokens.
The browser side
document.getElementById('ask').onclick = () => {
answer.textContent = '';
source = new EventSource('/stream?question=' + encodeURIComponent(question.value));
source.addEventListener('token', e => {
answer.textContent += JSON.parse(e.data).text;
});
source.addEventListener('done', () => source.close());
source.onerror = () => source.close();
};
// Closing the EventSource drops the connection, so the server cancels
document.getElementById('stop').onclick = () => source && source.close();
EventSource opens the stream, each token event appends its text, and the Stop button closes the connection, which the server sees as a cancel. A React component uses the same three calls inside an effect. For the transport choice between SSE and WebSockets, see streaming LLM answers with SSE and WebSockets.
Recap
| Endpoint | What the browser gets | First byte |
|---|---|---|
call().content() | One String, once the model has finished | 3.13 s |
Flux without text/event-stream | One JSON array, once the Flux completes | 3.16 s |
Flux of ServerSentEvent | One event per chunk, then a done event | 0.44 s |
Use server-sent events for answers a person reads, wrap each chunk in a record, and watch for the cancel when they leave.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
What Spring AI 2 Is, and Why a Java Team Wants It
Spring AI 2 is one Spring-style API for AI models: your code talks to a ChatClient, and the provider is a dependency and a setting. Follow one 'I was charged twice' call through advisors and the model to a Java record, see why 20,000 tickets a day is more than one HTTP call, and what the library leaves to you.
Spring AI ChatClient: One API for Any Model, and the Model Is a Property
A small Spring Boot chat service asks llama3.2:3b in Docker through one ChatClient chain, reads 43 tokens in and 60 out from the response, gets the same answer twice at temperature 0 with seed 42, then moves to llama3.2:1b with one environment variable and no code change.
Spring AI Prompt Templates: Placeholders, Few-Shot Messages and Versioned Prompt Files
PromptDesk keeps its prompts in .st files with {customer} and {ticket} placeholders, picks ticket-summary-v1 or v2 with one property, turns a chatty 'I would classify this as BUG' into plain BUG with two example messages, and refuses to send a prompt with a hole in it.
Spring AI Structured Output: From Model JSON to a Java Record, and a Real Ticket Triage Feature
A Triage record with two enums becomes the contract with the model. On llama3.2:3b only native structured output returned a valid record; format text alone left the JSON unclosed and the validation advisor tried three times for the same broken answer. Then Relay's triage: the model picks a category and priority, a config table picks the agent, and a dead model costs the customer one second, not seventy.
