Streaming Gemini chat responses with Spring AI and SSE
Combine Spring AI 2.0.1 streaming, Project Reactor Flux, and Server-Sent Events to cut time to first token to 0.3s while keeping multi-turn ChatMemory.
The biggest UX bottleneck in an LLM chat app isn’t total generation time—it’s Time to First Token (TTFT). This post shows how I combine Spring AI 2.0.1’s
chatClient.prompt().stream(), Project ReactorFlux<String>, and Server-Sent Events (SSE) to render the first token in about 0.3 seconds while preserving multi-turn context withChatMemory.
Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, and
gemini-3.5-flash-lite.
Blocking calls vs reactive SSE streaming
With a synchronous call(), the HTTP connection stays idle for 3–7 seconds until Gemini finishes generating the entire response. Switching to stream() backed by Flux<String> and text/event-stream pushes each token chunk to the browser the moment it arrives.
sequenceDiagram
autonumber
actor User as Browser
participant Server as Spring Boot (ChatClient)
participant Gemini as Google Gemini API
Note over User,Gemini: 1. Sync Blocking (call) — 4 to 8s wait
User->>Server: POST /api/chat (prompt)
Server->>Gemini: generateContent (sync)
Note over Server: Thread blocks until full response completes
Gemini-->>Server: Complete JSON response
Server-->>User: 200 OK (entire text at once)
Note over User,Gemini: 2. Reactive Streaming (stream + SSE) — ~0.3s TTFT
User->>Server: GET /api/chat/stream (SSE)
Server->>Gemini: streamGenerateContent (Flux chunks)
Gemini-->>Server: Chunk 1 ("Hello")
Server-->>User: data: Hello\n\n (live render)
Gemini-->>Server: Chunk 2 (", world!")
Server-->>User: data: , world!\n\n
| Protocol | Direction | Proxy/HTTP compatibility | Best fit |
|---|---|---|---|
| Sync HTTP | Request/Response | Universal | Short outputs, batch jobs, strict DTO parsing |
SSE (text/event-stream) | Server → Client | Standard HTTP/1.1 & HTTP/2 | LLM token streaming, live status feeds |
| WebSocket | Full-duplex | Requires Upgrade & sticky sessions | Real-time voice, collaborative editing, bidirectional chat |
When not to use SSE: Avoid SSE if you need binary frames, bidirectional audio streaming, or strict end-to-end JSON Schema validation before showing any output to the user. Also watch out for HTTP/1.1 browser limits (6 concurrent connections per origin)—serve SSE over HTTP/2 in production.
Project setup and ChatMemory configuration
All code below comes from the chat-sse module in spring-ai-examples.
1. Gradle dependencies (build.gradle.kts)
Add spring-ai-starter-model-google-genai, reactor-core for Flux, and reactor-test for StepVerifier:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
plugins {
kotlin("jvm") version "2.3.21"
kotlin("plugin.spring") version "2.3.21"
id("org.springframework.boot") version "4.1.1"
id("io.spring.dependency-management") version "1.1.7"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
implementation("io.projectreactor:reactor-core")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("io.projectreactor:reactor-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}
2. Configuring ChatMemory and ChatClient
To keep multi-turn context across streamed replies, register a sliding-window MessageWindowChatMemory (retaining the latest 20 messages) and attach MessageChatMemoryAdvisor to ChatClient.Builder:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package io.github.cmsong111.chat_sse
import org.springframework.ai.chat.client.ChatClient
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor
import org.springframework.ai.chat.memory.ChatMemory
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository
import org.springframework.ai.chat.memory.MessageWindowChatMemory
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
@SpringBootApplication
class ChatSseApplication {
@Bean
fun chatMemory(): ChatMemory {
return MessageWindowChatMemory.builder()
.chatMemoryRepository(InMemoryChatMemoryRepository())
.maxMessages(20)
.build()
}
@Bean
fun chatClient(builder: ChatClient.Builder, chatMemory: ChatMemory): ChatClient {
return builder
.defaultSystem("You are a helpful, responsive AI assistant replying in real time.")
.defaultAdvisors(
MessageChatMemoryAdvisor.builder(chatMemory).build(),
SimpleLoggerAdvisor()
)
.build()
}
}
fun main(args: Array<String>) {
runApplication<ChatSseApplication>(*args)
}
Under the hood, MessageChatMemoryAdvisor loads prior messages for the given conversationId before sending the prompt, aggregates the streamed assistant chunks as they complete, and writes the final assistant turn back into ChatMemory.
Building the streaming service and SSE controller
1. Streaming service (ChatSseService)
Calling .stream().content() returns a Flux<String> immediately. Pass conversationId through the advisor parameters so each user session gets its own isolated history:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package io.github.cmsong111.chat_sse.service
import org.springframework.ai.chat.client.ChatClient
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
@Service
class ChatSseService(
private val chatClient: ChatClient
) {
// Streams a reply using the fallback "default" conversation session
fun streamChat(message: String): Flux<String> {
return streamChatWithConversation("default", message)
}
// Streams a reply while preserving multi-turn history for conversationId
fun streamChatWithConversation(conversationId: String, message: String): Flux<String> {
return chatClient.prompt()
.user(message)
.advisors { advisorSpec ->
advisorSpec.param("chat_memory_conversation_id", conversationId)
}
.stream()
.content()
}
}
When
MessageChatMemoryAdvisoris registered globally, omittingchat_memory_conversation_idthrowsIllegalArgumentException: conversationId cannot be null. Always default to a fallback ID in the service or controller.
2. SSE controller (ChatSseController)
Returning Flux<String> with produces = [MediaType.TEXT_EVENT_STREAM_VALUE] tells Spring MVC/WebFlux to keep the response open and frame each emitted string as data: <token>\n\n:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package io.github.cmsong111.chat_sse.controller
import io.github.cmsong111.chat_sse.service.ChatSseService
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Flux
@RestController
@RequestMapping("/api/chat")
class ChatSseController(
private val chatSseService: ChatSseService
) {
/**
* Real-time Server-Sent Events (SSE) streaming endpoint
* GET /api/chat/stream?message=Hello&conversationId=session-1
*/
@GetMapping(value = ["/stream"], produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
fun streamChat(
@RequestParam message: String,
@RequestParam(required = false, defaultValue = "default") conversationId: String
): Flux<String> {
return chatSseService.streamChatWithConversation(conversationId, message)
}
}
Consuming the SSE stream in the browser
Instead of EventSource (which only supports GET and lacks custom auth headers), I used fetch with response.body.getReader() so the same pattern extends easily to POST requests and bearer tokens:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
async function sendStreamMessage(userMessage, conversationId) {
const url = `/api/chat/stream?message=${encodeURIComponent(userMessage)}&conversationId=${conversationId}`;
const response = await fetch(url);
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
const messageBubble = document.createElement("div");
messageBubble.className = "ai-message";
chatContainer.appendChild(messageBubble);
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
// Parse SSE 'data:' lines
const lines = chunk.split("\n");
for (const line of lines) {
if (line.startsWith("data:")) {
const token = line.substring(5);
messageBubble.textContent += token;
chatContainer.scrollTop = chatContainer.scrollHeight;
}
}
}
}
Figure 1. Browser chat UI streaming tokens in real time while retaining context for session-user-1.
Testing reactive streams with StepVerifier and curl
Standard JUnit assertions can’t wait on asynchronous Flux emissions cleanly. Use Project Reactor’s StepVerifier to subscribe, collect each emitted token, and verify stream completion (onComplete) alongside multi-turn memory recall:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package io.github.cmsong111.chat_sse
import io.github.cmsong111.chat_sse.service.ChatSseService
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import reactor.test.StepVerifier
@SpringBootTest
class ChatSseIntegrationTests {
@Autowired
private lateinit var chatSseService: ChatSseService
@Test
fun `streams tokens in real time from Gemini`() {
val message = "Describe the difference between Java and Kotlin in three short words."
val tokenFlux = chatSseService.streamChat(message)
val receivedTokens = mutableListOf<String>()
StepVerifier.create(
tokenFlux.doOnNext { token ->
receivedTokens.add(token)
print(token)
}
)
.thenConsumeWhile { true }
.verifyComplete()
println("\n=== [ChatSSE] Total Tokens Received: ${receivedTokens.size} ===")
val fullResponse = receivedTokens.joinToString("")
assertThat(receivedTokens).isNotEmpty
assertThat(fullResponse).isNotBlank()
}
@Test
fun `retains multi-turn context per conversationId`() {
val conversationId = "test-session-123"
// First turn: introduce user information
val firstFlux = chatSseService.streamChatWithConversation(conversationId, "My name is Namju Kim. Please remember it.")
StepVerifier.create(firstFlux).thenConsumeWhile { true }.verifyComplete()
// Second turn: verify memory recall in the same session
val secondFlux = chatSseService.streamChatWithConversation(conversationId, "What is my name?")
val secondTokens = mutableListOf<String>()
StepVerifier.create(secondFlux.doOnNext { secondTokens.add(it) })
.thenConsumeWhile { true }
.verifyComplete()
val answer = secondTokens.joinToString("")
println("=== [ChatSSE] Multi-turn Memory Recall ===")
println("Answer: $answer")
assertThat(answer).contains("Namju")
}
}
Running the Gradle test suite verifies both live chunk streaming and memory recall across turns:
Figure 2. StepVerifier integration test passing with live token emissions and multi-turn recall.
You can also inspect raw SSE frames directly from the terminal using curl -N (which disables output buffering):
Figure 3. Terminal output from curl -N showing incremental data: frames arriving as tokens generate.
Production caveats and checklist
Before deploying SSE chat streaming behind a load balancer, check these four points:
- Disable reverse-proxy buffering: Nginx buffers responses by default, which turns SSE back into a blocking wait. Add
proxy_buffering off;or return theX-Accel-Buffering: noresponse header. - Buffer partial lines on the client: A single
reader.read()chunk can split adata:line across two TCP packets; keep a trailing line buffer in production frontend code instead of splitting each chunk in isolation. - Raise async request timeouts: Spring MVC’s default async timeout (
spring.mvc.async.request-timeout) is 30 seconds, which can cut off long reasoning responses mid-stream. - Replace
InMemoryChatMemoryRepositorybefore scaling out: In-memory history disappears on pod restarts and breaks under multi-instance load balancing. To persist sessions across instances, move to Redis—see Persisting Spring AI ChatMemory in Redis with Gemini.
Full source code is available in cmsong111/spring-ai-examples/chat-sse.