Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Build a customer-facing chatbot endpoint in Spring Boot with Spring AI that remembers the last messages of a conversation. How do you store memory and keep the prompt within token limits?

We build the endpoint on a ChatClient with a chat memory advisor, such as MessageChatMemoryAdvisor, backed by a ChatMemory keyed by a conversation id for each user session, and we store the messages in a persistent repository such as JDBC or Redis when conversations must survive restarts or be shared across pods. To stay within the context limit we keep a window of the last N messages or summarise older turns, we stream the answer with stream().content() as a Flux<String> or server-sent events, and we key memory by an authenticated session so users never see each other's history.

Why this question is asked

A model has no memory of its own: every call starts from nothing, and whatever we send is all it knows. A chatbot that 'remembers' is really an application that stores the conversation and resends the relevant part each time. Interviewers ask this coding question because it covers Spring AI's memory support, storage choices, token limits and a security mistake that is easy to make. In this answer, we will recap why memory is needed, build the endpoint, choose the storage, keep the prompt within limits, add streaming and make sure memory stays private.

1A Quick Recap: Why the Bot Forgets

LLM APIs are stateless. If the user says 'my order is A-1001' and then 'when will it arrive?', the second call contains only the second message unless we include the first. So we store each conversation's messages and add the recent ones to every new prompt. The context window, the maximum number of tokens a model can read in one call, limits how much history we can include, and every token we resend also costs money and adds latency.

2Building the Endpoint With a Memory Advisor

In Spring AI, an advisor is a component that wraps each ChatClient call and can change the request or the response. MessageChatMemoryAdvisor loads the stored messages for a conversation id, adds them to the prompt, and saves the new user message and the reply afterwards. MessageWindowChatMemory is a ChatMemory that keeps only the most recent messages. The class names and the conversation id constant below are those of Spring AI 1.x; check your version, as they changed before 1.0.

Java
@Configuration
class ChatConfig {
@Bean
ChatMemory chatMemory(ChatMemoryRepository repository) { // JDBC repository auto-configured
return MessageWindowChatMemory.builder()
.chatMemoryRepository(repository)
.maxMessages(20) // keep the last 20 messages
.build();
}
@Bean
ChatClient chatClient(ChatClient.Builder builder, ChatMemory chatMemory) {
return builder
.defaultSystem("You are the support assistant for Acme. Be brief and polite.")
.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
.build();
}
}
@RestController
class ChatController {
private final ChatClient chatClient;
ChatController(ChatClient chatClient) { this.chatClient = chatClient; }
@PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> chat(@RequestBody String message, HttpSession session) {
String conversationId = session.getId(); // tied to the logged-in session
return chatClient.prompt()
.user(message) // "When will it arrive?"
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
.stream()
.content(); // "Your order A-1001 should arrive ..."
}
}
Step throughOne chat turn with memory
BrowserChatControllerMemory advisorRepositoryModel
POST /chat 'When will it arrive?'
prompt with conversation id = session id
load last 20 messages
'my order is A-1001' and reply
system + history + new message
streamed tokens
save user message and full reply

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

Notice that the conversation id comes from the server-side session, not from the request body. The advisor uses it to load and save the right history, so the second question is answered with the order id from the first.

3Choosing Where Memory Lives

The simplest ChatMemoryRepository keeps messages in memory inside the application. That is fine for a demo, but conversations disappear on restart, and with three pods behind a load balancer the user's next message may reach a pod that has never seen the conversation. For a real chatbot we use a persistent repository. Spring AI provides a JDBC repository, with a starter that creates the table for PostgreSQL, MySQL and others, and other stores such as Cassandra; Redis-backed memory is available in newer versions or through community modules, so check your version. A shared store makes every pod see the same history, and we also set a retention period, for example deleting conversations after 30 days, in line with the privacy policy.

4Keeping the Prompt Within the Token Limit

A message window is the first protection: with maxMessages(20) the prompt contains at most the last 20 messages, so a conversation of 200 messages costs the same per turn as one of 20. The catch is that facts from early in the conversation fall out of the window. If the user gave their order number in message 3, the bot forgets it by message 25.

Summarisation solves that. When the history grows past a threshold, we ask a cheap model to summarise the older turns into a short paragraph, such as 'Customer asked about order A-1001, delivery delayed, prefers email', store the summary, and send it with the recent window. We can also keep important facts, like an order id the user confirmed, in structured fields that are always included. Whatever we choose, we should count tokens rather than messages when messages can be long, and also cap the size of a single user message.

Ways to keep history within limits
ApproachTokens per turnRemembers early facts?
Send everythinggrows without limityes, until the limit breaks the call
Window of last 20 messagesboundedno, early facts drop out
Window plus summary of older turnsbounded, slightly highermostly, in condensed form
Window plus stored key factsboundedyes, for the facts we chose

5Streaming the Answer

Waiting several seconds for a full answer feels slow. With stream().content(), Spring AI returns a Flux<String>, a reactive stream that emits pieces of the answer as the model produces them. Returning it from a controller with the text/event-stream media type sends them to the browser as server-sent events, so the user sees the answer appear word by word. The memory advisor still saves the complete reply once the stream finishes. This works in Spring MVC as well as WebFlux, because Spring MVC can return a Flux for streaming responses.

6Never Mixing Memory Between Users

The worst bug a chatbot can have is showing one customer another customer's conversation. It happens when the conversation id comes from the client, for example a field in the request body or a predictable number, because anyone can then send someone else's id. The rule is to key memory by something the server controls and ties to the authenticated user: the server-side session id as above, or the user id combined with a server-generated conversation id that we check belongs to that user. And when a user logs out, their session id stops being valid, so the old conversation cannot be reached through it.

7Follow-up questions

How do you let a user have several separate conversations?

Generate a conversation id on the server when the user starts a new chat, store it with the user id, and accept it from the client only after checking it belongs to the logged-in user. The memory key is then that verified conversation id.

Does the system prompt count against the window?

With MessageWindowChatMemory, system messages are treated specially and kept rather than evicted, but they still use tokens in every call, so keep the system prompt short. Check your version for the exact eviction rules.

What happens if the client disconnects in the middle of a stream?

The Flux is cancelled, so the model call may stop and the reply may be incomplete. Decide whether to save partial replies; many applications save them marked as incomplete so the next turn has accurate history.

8Conclusion

In this answer, we built a chatbot endpoint with Spring AI that remembers the conversation. A ChatClient with MessageChatMemoryAdvisor and a MessageWindowChatMemory loads and saves messages by conversation id, a JDBC or Redis repository keeps them across restarts and pods, a window plus summaries keeps the prompt within the token limit, stream().content() streams the answer as server-sent events, and the conversation id comes from the authenticated session so memory is never shared between users.

What to say in the interviewAbout 80 seconds aloud

Open with

Models are stateless, so memory means storing the conversation and resending the relevant part. In Spring AI I would build a ChatClient with a default MessageChatMemoryAdvisor wrapping a ChatMemory, for example MessageWindowChatMemory with maxMessages of 20, and on each request pass the conversation id as an advisor parameter.

Then, if they want more

The advisor loads that conversation's recent messages into the prompt and saves the new turn afterwards. I would check the exact class names for our Spring AI version.

For storage, the in-memory repository is only for demos, because restarts lose it and other pods cannot see it, so I would use the JDBC chat memory repository on our database, or Redis if our version supports it, with a retention period.

To stay within the context limit, the window bounds the cost per turn, and to avoid forgetting early facts I would summarise older turns with a cheap model and keep key facts like the confirmed order id in structured fields. For the user experience I return stream().content(), a Flux of strings, as server-sent events.

And the conversation id must come from the server side, the authenticated session or a server-generated id checked against the user, never from a field the client can change, so one user can never load another user's history.

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 "Build a customer-facing chatbot endpoint in Spring Boot with Spring AI that remembers...": https://scrivio-interview-library.netlify.app/spring-boot/ai-agents-and-mcp/4e8556a37a/