Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

A Spring AI chatbot forgets what the user said in the previous message. Show how to add chat memory per user conversation with ChatClient, and explain where the messages are stored and how many are sent to the model.

The model itself remembers nothing between calls, so we add a ChatMemory, for example MessageWindowChatMemory with a maxMessages limit, and register MessageChatMemoryAdvisor on the ChatClient. On each request we pass the user's conversation id with advisors(a -> a.param(ChatMemory.CONVERSATION_ID, id)). The messages are stored by a ChatMemoryRepository, in memory by default or in JDBC, Cassandra or Neo4j for persistence, and only the last N messages of that conversation are sent to the model on each call.

Why this question is asked

Almost every chatbot bug report starts the same way: I told it my order number and two messages later it asked me again. The cause is not a broken model; it is that chat models are stateless. Interviewers ask this question to see whether we understand that memory is something the application sends, and whether we think about where it is stored and how much it costs. In this answer, we will recap why the model forgets, add memory with ChatClient step by step, see where the messages are stored, look at how many messages go to the model, and avoid the shared-conversation mistake.

1Why the Chatbot Forgets

A chat model API is stateless: each call is independent, and the model only sees what is in that request. When a chat app seems to remember, it is because the application sends the earlier messages again with every new question. So if our code sends only the latest user message, the model truly has no idea what was said before.

Java
String a1 = chatClient.prompt().user("My order number is 4711.").call().content();
// "Thanks! How can I help with order 4711?"
String a2 = chatClient.prompt().user("When will it arrive?").call().content();
// "Could you tell me your order number?" <- the second call never saw the first message

Notice that the second request contains only the text When will it arrive?. Nothing is wrong with the model; we simply did not send the history.

2Adding Memory to ChatClient

Spring AI separates three ideas. A ChatMemory decides which messages to keep and return. A ChatMemoryRepository stores them. An advisor, which is a piece of code that runs around every ChatClient call, reads the history before the call, adds it to the prompt, and saves the new user message and the model's reply afterwards. MessageChatMemoryAdvisor is the advisor that does this and adds the history as real chat messages.

Java
@Configuration
class ChatConfig {
@Bean
ChatMemory chatMemory(ChatMemoryRepository repository) { // repository auto-configured by Spring Boot
return MessageWindowChatMemory.builder()
.chatMemoryRepository(repository)
.maxMessages(20) // keep the last 20 messages per conversation
.build();
}
@Bean
ChatClient chatClient(ChatClient.Builder builder, ChatMemory chatMemory) {
return builder
.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
.build();
}
}

Registering the advisor with defaultAdvisors means every call through this ChatClient gets memory. The only thing the advisor still needs per call is which conversation the message belongs to.

3Passing the Conversation Id Per Request

The conversation id is the key under which the messages are stored. We pass it as an advisor parameter on each request. It should come from our own session or chat record, for example a UUID created when the user starts a chat, never from something every user shares.

Java
@PostMapping("/chats/{chatId}/messages")
String send(@PathVariable String chatId, @RequestBody String question, Principal user) {
chats.checkOwner(chatId, user.getName()); // the chat must belong to this user
return chatClient.prompt()
.user(question)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
.call()
.content();
}
// POST /chats/7f3c.../messages "My order number is 4711." -> "Thanks! ..."
// POST /chats/7f3c.../messages "When will it arrive?" -> "Order 4711 should arrive on Friday.
Step throughOne call with memory
ControllerMemory advisorRepositoryModel
prompt with question and conversation id
load messages for this id
last 20 messages
history plus new question
answer
save question and answer
answer

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

Now the second call works. Notice the owner check: the conversation id comes from the URL, so we must verify that the logged-in user owns that chat, or one user could read another's history by guessing ids.

4Where the Messages Are Stored

The storage comes from the ChatMemoryRepository. If we add nothing, Spring Boot's auto-configuration gives us an in-memory repository: fast and fine for a demo, but every conversation is lost when the application restarts, and with two instances behind a load balancer each instance has its own separate memory, so a user's second message may land on an instance that never saw the first.

For production we add a persistent repository. Spring AI provides a JDBC repository (with schema scripts for databases such as PostgreSQL and MySQL), plus Cassandra and Neo4j repositories, each through its own starter; the exact starter names are in the reference documentation, so check your version. With the JDBC starter on the classpath, the auto-configured repository changes and our ChatConfig above does not need to change at all.

Properties
# application.properties with the JDBC chat memory starter added
spring.ai.chat.memory.repository.jdbc.initialize-schema=always # creates the table on startup (property name: check your version)

5How Many Messages Are Sent to the Model

MessageWindowChatMemory keeps a sliding window. With maxMessages(20), the advisor sends at most the 20 most recent messages of that conversation, counting both user and assistant messages, so roughly the last ten exchanges. When a new message pushes the count over 20, the oldest ones drop out of the window (system messages are treated specially and kept). This bounds the size of every prompt: if an average message is 80 tokens, history adds at most about 1,600 input tokens per call, however long the conversation runs.

The cost of the bound is that anything older is forgotten. If the user gave their order number in message 3 and we are at message 40, the model no longer sees it. We can raise the window, which costs tokens on every call, or summarise older turns into a short note that stays in the prompt, which the FAQ below covers.

6The Shared Conversation Id Mistake

A common bug in first versions is to use a constant id, or to leave the parameter out so a default id is used. Then every user's messages go into one conversation. User B asks a question and the model answers using user A's order number and address. That is a privacy incident, not just a bug. The conversation id must be unique per user conversation, and the code that receives it must check that the current user is allowed to use it.

7Follow-up questions

How would you summarize long conversations instead of dropping them?

Keep the last few messages verbatim and replace older ones with a short summary. When the window is about to drop messages, a background step asks a small, cheap model to fold them into a running summary such as: customer is asking about order 4711, delivery address in Berlin, already offered a refund. We store the summary with the conversation and add it as a system message on each call. This keeps important facts at a fixed small cost, and we can write a custom ChatMemory or advisor for it, since the window memory alone only drops.

What is the difference between MessageChatMemoryAdvisor and PromptChatMemoryAdvisor?

MessageChatMemoryAdvisor adds the history as separate user and assistant messages, which is what chat models are trained on. PromptChatMemoryAdvisor appends the history as text inside the system prompt, which works with models or templates that need plain text.

Should I keep memory in the HTTP session instead?

It works for one instance with sticky sessions, but it is lost on restart, it grows the session, and it does not work across instances. A persistent ChatMemoryRepository keyed by conversation id is simpler and survives both.

8Conclusion

In this answer, we saw that chat models are stateless, so the application must send the history. With Spring AI we build a MessageWindowChatMemory on a ChatMemoryRepository, register MessageChatMemoryAdvisor on the ChatClient, and pass a per-conversation id on each request. The repository decides where messages live, in memory by default or in JDBC, Cassandra or Neo4j for persistence, and the window limits how many messages go into each prompt, which bounds tokens and cost while older context is dropped or summarised.

What to say in the interviewAbout 80 seconds aloud

Open with

The model is stateless, so it only knows what we send in each request. To add memory in Spring AI I create a ChatMemory, usually MessageWindowChatMemory built with a ChatMemoryRepository and maxMessages, say 20, and I register MessageChatMemoryAdvisor built from that memory as a default advisor on the ChatClient.

Then, if they want more

On each request I pass the conversation id with advisors, a dot param ChatMemory.CONVERSATION_ID and the id. The advisor loads that conversation's recent messages, adds them to the prompt, and after the call saves the user message and the reply. Storage comes from the repository.

By default it is in memory, which is lost on restart and not shared between instances, so for production I add the JDBC repository, or Cassandra or Neo4j, and my configuration does not change.

The window means at most the last 20 messages go to the model, which caps tokens and cost per call, but older facts drop out, so for long chats I would add a running summary of older turns.

And I make sure the conversation id is unique per user conversation and checked against the logged-in user, because a shared id would mix users' histories.

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 "A Spring AI chatbot forgets what the user said in the previous message. Show how to add...": https://scrivio-interview-library.netlify.app/spring-boot/spring-ai/60eb86eb22/