Streaming AI Responses with Spring AI – Real-Time LLM Interaction

In Spring AI, streaming enables applications to deliver Large Language Model (LLM) responses incrementally—token by token or chunk by chunk—as they are generated, rather than forcing users to wait for the entire completion to finish. Built natively on Project Reactor (Flux), Spring AI’s streaming architecture drastically reduces perceived latency (Time-To-First-Token) and mirrors modern conversational interfaces like ChatGPT and Claude.

1. End-to-End Streaming Architecture

Streaming in Spring AI operates as an asynchronous, non-blocking reactive pipeline from the external LLM provider all the way to the client interface:
  1. Provider Stream Connection: When a streaming request is initiated, the underlying StreamingChatModel opens a persistent HTTP connection to the LLM vendor (typically consuming Server-Sent Events or chunked JSON streams from Gemini, Claude, OpenAI, or Ollama).

  2. Reactive Normalization (Flux<ChatResponse>): As raw byte chunks arrive from the vendor API, Spring AI deserializes and normalizes them into a reactive stream (Flux) of ChatResponse objects.

  3. Advisor Pipeline Interception: Streaming-capable Advisors (StreamAroundAdvisor) wrap the reactive stream, allowing cross-cutting concerns—such as logging, RAG context injection, and conversation memory persistence—to observe or aggregate chunks as they flow through.

  4. Controller & Transport Delivery: Spring WebFlux or Spring MVC exposes the Flux<String> or Flux<ChatResponse> over HTTP using Server-Sent Events (text/event-stream), NDJSON, or WebSockets so frontend applications render text in real time.

2. Synchronous (.call()) vs. Streaming (.stream())

Dimension Synchronous Execution (.call()) Streaming Execution (.stream())
Return Type String, ChatResponse, or mapped Java T (.entity()) Flux<String> (.content()) or Flux<ChatResponse> (.chatResponse())
Perceived Latency High; user waits until the full response is generated Ultra-low; first tokens appear within milliseconds
Execution Model Blocking until completion Non-blocking, event-driven reactive stream
Structured Output Native automatic parsing into Java POJOs (.entity()) Chunked text; structured JSON must be aggregated before deserialization
Token & Metadata Access Immediately available in ChatResponseMetadata Delivered progressively (often in the final chunk of the Flux)
Ideal Use Cases Background batch jobs, strict JSON extraction, short classifications Interactive chatbots, long-form content generation, live code assistants

3. Core Streaming Components & Mechanics

  • StreamingChatModel & ChatClient.stream(): Every modern ChatModel implementation in Spring AI implements StreamingChatModel. Calling .stream() on ChatClient switches execution into reactive mode:

    • .content(): Extracts and emits only the incremental text fragments (Flux<String>), filtering out empty metadata frames for clean UI rendering.

    • .chatResponse(): Emits the full Flux<ChatResponse> stream, preserving granular metadata, finish reasons, and cumulative token usage statistics on the final chunk.

  • Stream Aggregation (MessageAggregator): Because streaming breaks a single response into dozens or hundreds of tiny fragments, components like conversation memory need the complete message once streaming finishes. Spring AI provides MessageAggregator utilities that transparently reassemble streamed ChatResponse chunks into a single unified response without interrupting the real-time flow to the user.

  • Tool / Function Calling During Streams: When an LLM decides to invoke a Java @Tool mid-stream, Spring AI intercepts the tool-call chunk, executes the local Java method, feeds the ToolResponseMessage back to the LLM, and seamlessly resumes streaming the final answer to the client.

4. Transport Protocols for Real-Time Delivery

To push streamed tokens from a Spring Boot backend to web or mobile clients, Spring AI integrates with standard web transport mechanisms:
  • Server-Sent Events (SSE): The most common approach for unidirectional AI text streaming. Returning a Flux<String> from a REST endpoint with MediaType.TEXT_EVENT_STREAM_VALUE automatically formats each token as an SSE data: frame over standard HTTP.

  • Reactive WebFlux vs. Servlet MVC:

    • Spring WebFlux provides end-to-end non-blocking backpressure from the Netty event loop down to the LLM HTTP client.

    • Spring MVC also supports returning Flux streams natively via Servlet asynchronous request processing, allowing traditional blocking Spring Boot apps to stream AI responses without migrating the entire stack.

  • WebSockets / RSocket: Used when bidirectional real-time communication is required, such as allowing users to interrupt or cancel an active generation mid-stream.

5. Production Considerations & Best Practices

  • Stream Cancellation & Resource Cleanup: If a user closes their browser tab or clicks “Stop Generating,” the reactive subscription cancels (doOnCancel), immediately closing the upstream connection to the LLM provider to save compute and token costs.

  • Handling Partial & Empty Chunks: LLM providers frequently emit initial role-setup chunks or trailing metadata chunks with null/empty text content. Using ChatClient.stream().content() automatically guards against null text emissions, whereas consuming Flux<ChatResponse> requires explicit null checks.

  • Error Handling Mid-Stream: Network timeouts or rate limits can occur halfway through a stream. Reactive operators (onErrorResume, retryWhen) allow gracefully emitting a fallback error message frame to the client rather than abruptly dropping the HTTP connection.

  • Structured Output Workarounds: Because partial JSON fragments cannot be parsed into Java objects mid-stream, applications needing both real-time UI feedback and structured objects either stream markdown/text for display or accumulate the Flux<String> via Collectors.joining() before passing the complete string to a BeanOutputConverter.


Hands-on Experiment: Real-Time AI Chat Application using Spring AI Streaming

Aim: To build a Spring Boot chat application that streams LLM responses in real time using Spring AI and stores the conversations in MySQL.

Description: Streaming delivers the model’s answer token by token as it is generated, instead of waiting for the full response. Spring AI supports it through the stream() method, which returns a reactive Flux that can be sent to clients over Server-Sent Events. It is used to make chat applications feel fast and responsive, especially for long answers. Streaming also lets users start reading immediately and stop a response early.

Software / Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE (IntelliJ/Eclipse/VS Code), Postman, and an OpenAI API key.

Step-by-Step Application Development

Step 1: Generate the Project via Spring Initializr

  • Project: Maven | Language: Java | Packaging: Jar | Java: 17
  • Spring Boot: 3.4.x (Spring AI 1.0 needs 3.4 or higher)
  • Group: com.example | Artifact: streaming-chat
  • Dependencies: Spring Web, Spring Data JPA, MySQL Driver, OpenAI, Reactive Web (WebFlux)

Step 2: Project Structure

streaming-chat
├── pom.xml
└── src/main
    ├── java/com/example/streamingchat
    │   ├── StreamingChatApplication.java
    │   ├── entity       (ChatSession, ChatMessage)
    │   ├── repository   (ChatSessionRepository, ChatMessageRepository)
    │   ├── service      (ChatService)
    │   └── controller   (ChatController)
    └── resources
        ├── application.properties
        └── static/index.html

Step 3: Create files according to the project structure

package com.example.streamingchat.entity;

import jakarta.persistence.*;
import java.time.LocalDateTime;

@Entity
@Table(name = "chat_messages")
public class ChatMessage {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long sessionId;

    // USER or ASSISTANT
    private String role;

    @Column(columnDefinition = "TEXT")
    private String content;

    private LocalDateTime createdAt = LocalDateTime.now();

    public ChatMessage() {
    }

    public ChatMessage(Long sessionId, String role, String content) {
        this.sessionId = sessionId;
        this.role = role;
        this.content = content;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public Long getSessionId() { return sessionId; }
    public void setSessionId(Long sessionId) { this.sessionId = sessionId; }
    public String getRole() { return role; }
    public void setRole(String role) { this.role = role; }
    public String getContent() { return content; }
    public void setContent(String content) { this.content = content; }
    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
}
package com.example.streamingchat.entity;

import jakarta.persistence.*;
import java.time.LocalDateTime;

@Entity
@Table(name = "chat_sessions")
public class ChatSession {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    private LocalDateTime createdAt = LocalDateTime.now();

    public ChatSession() {
    }

    public ChatSession(String title) {
        this.title = title;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
}
package com.example.streamingchat.repository;

import com.example.streamingchat.entity.ChatMessage;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ChatMessageRepository extends JpaRepository<ChatMessage, Long> {

    List<ChatMessage> findBySessionIdOrderByIdAsc(Long sessionId);
}
package com.example.streamingchat.repository;

import com.example.streamingchat.entity.ChatSession;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ChatSessionRepository extends JpaRepository<ChatSession, Long> {
}
package com.example.streamingchat.service;

import com.example.streamingchat.entity.ChatMessage;
import com.example.streamingchat.entity.ChatSession;
import com.example.streamingchat.repository.ChatMessageRepository;
import com.example.streamingchat.repository.ChatSessionRepository;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChatService {

    private static final String SYSTEM_PROMPT =
            "You are a helpful assistant in a real-time chat application. Keep answers clear and friendly.";

    private final ChatClient chatClient;
    private final ChatSessionRepository sessionRepository;
    private final ChatMessageRepository messageRepository;

    public ChatService(ChatClient.Builder builder,
                       ChatSessionRepository sessionRepository,
                       ChatMessageRepository messageRepository) {
        this.chatClient = builder.defaultSystem(SYSTEM_PROMPT).build();
        this.sessionRepository = sessionRepository;
        this.messageRepository = messageRepository;
    }

    public ChatSession createSession(String title) {
        return sessionRepository.save(new ChatSession(title));
    }

    public List<ChatSession> getSessions() {
        return sessionRepository.findAll();
    }

    public List<ChatMessage> getMessages(Long sessionId) {
        return messageRepository.findBySessionIdOrderByIdAsc(sessionId);
    }

    // Normal (blocking) call: waits for the complete answer
    public String ask(Long sessionId, String userText) {
        List<Message> prompt = buildPrompt(sessionId, userText);
        messageRepository.save(new ChatMessage(sessionId, "USER", userText));

        String answer = chatClient.prompt().messages(prompt).call().content();

        messageRepository.save(new ChatMessage(sessionId, "ASSISTANT", answer));
        return answer;
    }

    // Streaming call: returns tokens as they are generated
    public Flux<String> stream(Long sessionId, String userText) {
        List<Message> prompt = buildPrompt(sessionId, userText);
        messageRepository.save(new ChatMessage(sessionId, "USER", userText));

        StringBuilder fullAnswer = new StringBuilder();

        return chatClient.prompt()
                .messages(prompt)
                .stream()
                .content()
                .doOnNext(fullAnswer::append)
                .doOnComplete(() ->
                        messageRepository.save(new ChatMessage(sessionId, "ASSISTANT", fullAnswer.toString())));
    }

    // Past messages + the new user message, so the AI remembers the conversation.
    // Messages are passed as objects (not .user(text)) so { } in user text is never treated as a template.
    private List<Message> buildPrompt(Long sessionId, String userText) {
        sessionRepository.findById(sessionId)
                .orElseThrow(() -> new IllegalArgumentException("Session not found: " + sessionId));

        List<Message> messages = new ArrayList<>();
        for (ChatMessage saved : messageRepository.findBySessionIdOrderByIdAsc(sessionId)) {
            if ("USER".equals(saved.getRole())) {
                messages.add(new UserMessage(saved.getContent()));
            } else {
                messages.add(new AssistantMessage(saved.getContent()));
            }
        }
        messages.add(new UserMessage(userText));
        return messages;
    }
}
package com.example.streamingchat.controller;

import com.example.streamingchat.entity.ChatMessage;
import com.example.streamingchat.entity.ChatSession;
import com.example.streamingchat.service.ChatService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/chat")
public class ChatController {

    private final ChatService service;

    public ChatController(ChatService service) {
        this.service = service;
    }

    // Request bodies kept as small records so no extra dto package is needed
    public record SessionRequest(String title) {}

    public record MessageRequest(String message) {}

    @PostMapping("/sessions")
    public ChatSession createSession(@RequestBody SessionRequest request) {
        return service.createSession(request.title());
    }

    @GetMapping("/sessions")
    public List<ChatSession> sessions() {
        return service.getSessions();
    }

    @GetMapping("/sessions/{id}/messages")
    public List<ChatMessage> messages(@PathVariable Long id) {
        return service.getMessages(id);
    }

    // Normal response: the full answer arrives at once
    @PostMapping("/sessions/{id}/ask")
    public Map<String, String> ask(@PathVariable Long id, @RequestBody MessageRequest request) {
        return Map.of("response", service.ask(id, request.message()));
    }

    // Streaming response: Server-Sent Events, tokens arrive one by one
    @PostMapping(value = "/sessions/{id}/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> stream(@PathVariable Long id, @RequestBody MessageRequest request) {
        return service.stream(id, request.message());
    }
}
package com.example.streamingchat;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class StreamingChatApplication {

    public static void main(String[] args) {
        SpringApplication.run(StreamingChatApplication.class, args);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Real-Time AI Chat</title>
<style>
  body { font-family: Arial, sans-serif; max-width: 700px; margin: 30px auto; padding: 0 12px; }
  #chat { border: 1px solid #ccc; border-radius: 8px; height: 380px; overflow-y: auto; padding: 10px; background: #fafafa; }
  .user { color: #0b5; margin: 8px 0; }
  .ai { color: #222; margin: 8px 0; white-space: pre-wrap; }
  #row { display: flex; gap: 8px; margin-top: 10px; }
  #msg { flex: 1; padding: 8px; }
  button { padding: 8px 14px; }
</style>
</head>
<body>
<h2>Real-Time AI Chat (Streaming)</h2>
<div id="chat"></div>
<div id="row">
  <input id="msg" placeholder="Type a message and press Enter">
  <button id="send">Send</button>
</div>
<script>
let sessionId = null;
const chat = document.getElementById('chat');
const msg = document.getElementById('msg');

async function ensureSession() {
  if (sessionId) return;
  const res = await fetch('/api/chat/sessions', {
    method: 'POST', headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({title: 'Browser chat'})
  });
  sessionId = (await res.json()).id;
}

function addLine(cls, text) {
  const div = document.createElement('div');
  div.className = cls; div.textContent = text;
  chat.appendChild(div); chat.scrollTop = chat.scrollHeight;
  return div;
}

async function send() {
  const text = msg.value.trim();
  if (!text) return;
  msg.value = '';
  await ensureSession();
  addLine('user', 'You: ' + text);
  const aiLine = addLine('ai', 'AI: ');

  const res = await fetch('/api/chat/sessions/' + sessionId + '/stream', {
    method: 'POST', headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({message: text})
  });

  const reader = res.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';
  while (true) {
    const {done, value} = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, {stream: true});
    let idx;
    while ((idx = buffer.indexOf('\n\n')) >= 0) {
      const event = buffer.slice(0, idx);
      buffer = buffer.slice(idx + 2);
      const data = event.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5)).join('\n');
      aiLine.textContent += data;
      chat.scrollTop = chat.scrollHeight;
    }
  }
}

document.getElementById('send').onclick = send;
msg.addEventListener('keydown', e => { if (e.key === 'Enter') send(); });
</script>
</body>
</html>

Step 4: Run the Application and test the below the CURD operations

POST Payloads and URLs

1. Create a chat session
POST http://localhost:8080/api/chat/sessions

json
{ "title": "My first chat" }

2. Normal response (full answer at once)
POST http://localhost:8080/api/chat/sessions/1/ask

json
{ "message": "Explain Spring Boot in 5 lines" }

3. Streaming response (tokens arrive live)
POST http://localhost:8080/api/chat/sessions/1/stream

json
{ "message": "Write a short story about a robot" }

4. List sessions: GET http://localhost:8080/api/chat/sessions
5. View a conversation: GET http://localhost:8080/api/chat/sessions/1/messages
6. Browser demo: http://localhost:8080/index.html

below is the sample post payload from postman,

Scroll to Top