Computer scienceProgramming languagesKotlinAI engineering with KotlinAI tools & frameworks

Chat memory in Spring AI

21 minutes read

In the previous topic, you used ChatClient to send prompts to a model. There is one catch: every .call() is independent. Ask "My name is Alice" and then "What's my name?", and the model has no idea, because LLMs are stateless. As you've seen, the application has to resend the earlier conversation with every request.

Spring AI does this for you with chat memory. In this topic, you'll learn how it is organized, how to attach it to a ChatClient, and what to watch out for in a real application. As before, this code runs in your backend service, not in your shared client code.

ChatMemory and ChatMemoryRepository

Spring AI splits memory into two parts:

  • ChatMemory decides which messages to keep and when to drop old ones. For example, it might keep the last N messages.

  • ChatMemoryRepository only stores and retrieves messages. The default one, InMemoryChatMemoryRepository, keeps them in a map in your application's memory.

Everything is keyed by a conversation ID, so one application can hold many separate conversations.

Note that chat memory is not the same as chat history. Memory holds what the model should see, and it gets trimmed. If you need a complete record of everything that was said, store it separately, for example with Spring Data.

The message window

The standard ChatMemory implementation is MessageWindowChatMemory. It keeps a sliding window of recent messages, which is the strategy from the previous memory topic:

  • The default window size is 20 messages, which is 10 question and answer pairs.

  • Old messages are evicted in whole turns, starting from a user message, so the window never begins with an answer whose question was cut off. This means maxMessages is an upper bound, and the actual number can be lower.

  • System messages are never evicted, and if a new system message is added, it replaces the old one.

  • Trimming happens when messages are added, not when they are read.

Spring Boot auto-configures a ChatMemory bean, so you can inject it right away. To change the window size, define your own:

@Configuration
class ChatMemoryConfig {

    @Bean
    fun chatMemory(): ChatMemory =
        MessageWindowChatMemory.builder()
            .maxMessages(20)
            .build()
}

Defining your own ChatMemory bean normally replaces the default one.

Adding memory to ChatClient

You connect memory to a ChatClient with an advisor, the middleware mechanism from the previous topic. MessageChatMemoryAdvisor loads the conversation's history into each prompt and saves the new messages afterwards:

@Service
class AssistantService(
    chatClientBuilder: ChatClient.Builder,
    private val chatMemory: ChatMemory,
) {
    private val chatClient = chatClientBuilder
        .defaultSystem("You are a helpful assistant. Keep your replies short.")
        .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
        .build()

    fun ask(conversationId: String, question: String): String? =
        chatClient.prompt()
            .user(question)
            .advisors { it.param(ChatMemory.CONVERSATION_ID, conversationId) }
            .call()
            .content()

    fun forget(conversationId: String) = chatMemory.clear(conversationId)
}

A few points about this code:

  • The conversation ID is passed with every call as an advisor parameter. There is no default conversation ID: a call without one throws an IllegalArgumentException.

  • The system prompt set with defaultSystem is sent with each request. It isn't part of the stored history, so it doesn't count against the window.

  • chatMemory.clear(conversationId) deletes one conversation.

Choosing the conversation ID

Every conversation ID must be unique to one user or session. If two users share an ID, they read each other's messages. In a multi-user application, derive the ID on the server, for example from the authenticated user or the session. If the ID comes from a request header instead, treat it like a password: anyone who knows it can continue that conversation.

Where messages are stored

By default, messages live in the memory of your application. This is fast and needs no setup, but they disappear when the server restarts, and several instances of the server would each have their own copy. For persistence, Spring AI provides other ChatMemoryRepository implementations, including JDBC for relational databases, and others for Cassandra, MongoDB, Neo4j and Redis. You configure one, and ChatMemory uses it without changes to your service code.

Two limits are worth knowing. The current implementation doesn't store the intermediate tool-call messages that appear when a model uses tools, and some persistent repositories filter them out as well. Also, VectorStoreChatMemoryAdvisor exists for a different kind of memory: it searches a vector store for relevant past information and adds it to the system message. That is closer to the long-term memory discussed earlier.

When a model call fails

Look carefully at when MessageChatMemoryAdvisor saves things. In the current implementation, it stores the user's message before the model is called and the model's reply after the call returns. If the call throws, for example because the provider is down, the reply is never saved, but the user's message already is.

The history now contains a question that was never answered. The model will see it on every later request, and the user may ask the same thing again. Whether this matters depends on your application. If it does, take control of the order yourself. Spring AI's documentation shows how to use ChatMemory directly with a ChatModel, and you can adapt it so that nothing is saved until the call succeeds:

@Service
class ManualAssistantService(
    private val chatModel: ChatModel,
    private val chatMemory: ChatMemory,
) {
    fun ask(conversationId: String, question: String): String? {
        val userMessage = UserMessage(question)
        val prompt = Prompt(chatMemory.get(conversationId) + userMessage)

        val reply = chatModel.call(prompt).result.output // throws if the call fails

        chatMemory.add(conversationId, listOf(userMessage, reply))
        return reply.text
    }
}

Here, the history is read, the model is called, and only then are both messages added. A failed call leaves the memory untouched. You give up the convenience of the advisor, but you gain precise control. Check how your Spring AI version behaves, since this is an implementation detail that can change.

Practical notes

  • Concurrent requests. Adding messages reads the stored ones, merges the new ones, and saves the result. Two simultaneous requests in the same conversation can therefore overwrite each other's changes. If this can happen in your application, handle one request per conversation at a time.

  • Window size. A larger window gives the model more context but costs more and slows down every call. Choose the smallest size that serves your use case.

  • Test the behavior. Send a message, ask about it in a follow-up, then clear the conversation and ask again. Tests of memory should check that the follow-up works, that the cleared conversation forgets, and that a second conversation sees none of it.

Conclusion

Spring AI separates deciding what to remember (ChatMemory) from storing it (ChatMemoryRepository). MessageWindowChatMemory keeps the last 20 messages by default, drops whole turns, and never evicts system messages. You attach memory to a ChatClient with MessageChatMemoryAdvisor and pass a server-derived conversation ID with every call. The default storage is in-memory, so use a persistent repository if conversations must survive a restart.

The advisor saves the user's message before the model call, so a failed call leaves an unanswered question in the history. If that is not acceptable, call the model yourself and add both messages only after it succeeds.

How did you like the theory?
Report a typo