Get ahead
VMware offers training and certification to turbo-charge your progress.
Learn moreSpring AI: Session API | Migrating to Session Memory | Demo
With Spring AI 2.1, the ChatMemory API, its repositories and the MessageChatMemoryAdvisor are deprecated, and they will be removed in Spring AI 3.0.0. The deprecated types keep working until then. Their replacement is the Session API, which records a conversation as an append-only event log and builds the model's context from a view of that log.
We introduced the Session API in April as a Spring AI Community project. It is now part of Spring AI, and the move introduced several API and behaviour changes.
In this article we migrate a small chat application from ChatMemory to session memory, look at context compaction and recall, and go through the behaviour changes to check before switching. If you already use the community project, see Migrating from the Community Project.
đź’ˇ Demo: The
spring-ai-chat-memory-to-session-demoproject runs the same conversation withChatMemoryand with session memory. The output quoted in this article is from live runs of it.
ChatMemory stores a list of messages for each conversation id, and MessageWindowChatMemory limits the size of this list by discarding the oldest messages. Once discarded, a message is no longer available to the model or to the application. In addition, because MessageChatMemoryAdvisor runs outside the tool calling loop, the intermediate tool calls and their results are not recorded.
With the Session API we wanted to address a broader problem than conversation memory: state management for agent harnesses. It is a general-purpose state API, in which a session is an append-only log of SessionEvents with an extensible set of event types. A harness, such as a ChatClient with the session advisors, keeps no state of its own between calls, because its state is in the session. Conversation memory is the first application of this abstraction, and the subject of this article.
The key idea is that the session is not the model's context. The session retains the complete event history, including the tool calls and their results, and an event is never changed after it has been appended. The model receives a view of that history. Windowing and compaction determine which events are in the view, without modifying the underlying log.
Here are the five turns of the demo, stored both ways:
This design is not new. Event sourcing has stored state as a sequence of events for two decades, and durable execution engines recover a workflow by replaying an append-only event history. Agent systems have arrived at the same place. Anthropic describes the session of its Managed Agents as "the append-only log of everything that happened", and notes that "the session is not Claude's context window". OpenHands builds its agent memory on an append-only event log and derives a view from it. These systems share one principle: the persistent session state is kept apart from the harness that executes a turn and from the model's context. As a result the harness can be stateless, the context can be compacted without losing history, and the log becomes a foundation for durable execution.
1. Dependencies. Replace the chat memory repository starter with the session one:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-session-jdbc</artifactId>
</dependency>
The starter auto-configures a SessionService on the application's DataSource. PostgreSQL, MySQL, MariaDB, Microsoft SQL Server and H2 are supported. For an embedded database the schema is created at startup. For the other databases, set spring.ai.session.repository.jdbc.initialize-schema=always during development, or apply the schema with your migration tool.
2. Advisors. Replace the memory advisor with the session advisors:
// Before
ChatMemory chatMemory = MessageWindowChatMemory.builder().maxMessages(20).build();
ChatClient chatClient = ChatClient.builder(chatModel)
.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
.build();
// After
ChatClient chatClient = ChatClient.builder(chatModel)
.defaultAdvisors(SessionAdvisors.builder(sessionService).build())
.build();
SessionAdvisors builds two advisors. The turn advisor runs once per call, around the tool calling loop, and the memory advisor runs inside the loop, once per round:
3. The session id. Pass the session id with every call:
String answer = chatClient.prompt()
.user("What did we decide about the invoice?")
.advisors(SessionAdvisors.session(sessionId))
.call()
.content();
The context key is the same as ChatMemory.CONVERSATION_ID, so calls that already set this parameter work unchanged. A session is created on first use. There is deliberately no default session: a request without an id fails with an IllegalStateException, because a shared default would silently merge the histories of different users.
The ChatMemory types map to their session counterparts as follows:
| Chat memory | Session memory |
|---|---|
MessageChatMemoryAdvisor.builder(chatMemory) |
SessionAdvisors.builder(sessionService) |
ChatMemory.CONVERSATION_ID |
the same key, or SessionAdvisors.session(id) |
MessageWindowChatMemory, maxMessages |
EventFilter.lastN on the memory advisor, or a compaction |
chatMemory.get(id), add(id, messages), clear(id) |
sessionService.getActiveMessages(id), appendMessage(id, message), delete(id) |
ChatMemoryRepository, InMemoryChatMemoryRepository |
SessionRepository, InMemorySessionRepository |
JdbcChatMemoryRepository and its starter |
JdbcSessionRepository, spring-ai-starter-model-session-jdbc |
| The Cassandra, Neo4j, MongoDB and Redis repositories | no counterpart yet, planned before 3.0.0; they will come first to the session repositories of Spring AI Session Extensions |
The direct counterpart of maxMessages(20) is a window on the memory advisor:
SessionAdvisors.builder(sessionService)
.memory(memory -> memory.eventFilter(EventFilter.lastN(20)))
.build()
VectorStoreChatMemoryAdvisor is not deprecated. Despite its name, it is not built on the ChatMemory API: it stores the messages directly in a VectorStore and retrieves them by similarity search. Sessions do not have a semantic recall counterpart yet, so it remains the option for that.
The demo sends the same five messages to several ChatClients. The first two keep two turns of history: the first uses a ChatMemory window of four messages, and the second a session that is compacted to its last two turns. The fifth message asks for something that was said in the first:
=== BEFORE: ChatMemory, a window of 4 messages
USER: Remember this for later: my order number is A-1042.
ASSISTANT: Got it, your order number is A-1042.
...
USER: What was my order number?
ASSISTANT: You haven't mentioned an order number in this conversation.
With ChatMemory, the first turn has left the window and the order number is lost. Here is the same question with session memory, followed by the session log:
=== AFTER: session memory, compacted to the last 2 turns
USER: What was my order number?
ASSISTANT: Your order number is A-1042.
The session log: 19 events in 5 turns. The view holds turns 4 and 5.
turn 1 USER Remember this for later: my order number is A-1042.
ASSISTANT Got it, your order number is A-1042.
turn 2 USER What is the weather in Amsterdam?
ASSISTANT calls weather{"city":"Amsterdam"}
TOOL 12°C and rainy
ASSISTANT It's 12°C and rainy in Amsterdam.
turn 3 USER And in Barcelona?
ASSISTANT calls weather{"city":"Barcelona"}
TOOL 21°C and sunny
ASSISTANT It's 21°C and sunny in Barcelona.
COMPACTION the view now starts at turn 2
turn 4 view USER Which of the two cities is warmer?
view ASSISTANT Barcelona is warmer, at 21°C compared with Amsterdam's 12°C.
COMPACTION the view now starts at turn 3
turn 5 view USER What was my order number?
view ASSISTANT calls conversation_search{"query":"order number, order"}
view TOOL found: "Remember this for later: my order number is A-1042."
view ASSISTANT Your order number is A-1042.
COMPACTION the view now starts at turn 4
The log contains all five turns, including the tool calls and their results, while the view holds only turns 4 and 5. A compaction ran after each of the last three turns. Each one is itself an event, which records where the view starts from then on. In the fifth turn the order number was no longer in the view, so the model called conversation_search and found it in the first message.
The next two sections explain how the second ChatClient is configured.
Compaction is configured with a trigger, which determines when compaction is required, and a strategy, which determines which events remain in the view:
ChatClient chatClient = ChatClient.builder(chatModel)
.defaultAdvisors(SessionAdvisors.builder(sessionService)
.compaction(new TurnCountTrigger(20),
WindowCompactionStrategy.builder()
.lastTurns(10)
.summarizer(ChatModelSummarizer.builder(chatModel).build())
.build())
.build())
.build();
Spring AI 2.1 provides the following building blocks:
| Part | Available in 2.1 |
|---|---|
| Trigger | TurnCountTrigger, TokenCountTrigger, and CompositeCompactionTrigger.anyOf(...) to combine them |
| Strategy | WindowCompactionStrategy, which keeps the last events, the last turns or a token budget |
| Summary | optional: ChatModelSummarizer summarizes the events that are removed from the view |
Every compaction keeps the newest turn and starts the retained window at a turn boundary. This guarantees that a compacted view never contains a tool result without its call. Compaction runs after a turn has completed and is best effort: if it fails, the failure is logged and the reply is still returned. With asyncCompaction(true) it runs after the reply has been returned.
Summarization is the part of compaction that has no counterpart in ChatMemory. Without a summarizer, compaction only advances the view to a later turn, and the earlier turns are available through recall. With a ChatModelSummarizer, an additional model call condenses the events that are removed from the view into a summary turn, which is placed at the front of the view. The summary is rolling: each compaction receives the previous summary and builds on it.
The third run of the demo uses the summarizer and has no recall tool. The model answers the last question from the summary:
=== AFTER, WITH A SUMMARY: session memory, compacted to a summary and the last 2 turns
USER: What was my order number?
ASSISTANT: Your order number is A-1042.
The session log: 23 events in 5 turns. The view holds a summary and turns 4 and 5.
... turns 1 to 4, as in the log above ...
COMPACTION the view now starts at turn 3
summary USER Summarize the conversation we had so far.
summary ASSISTANT The user first asked the assistant to remember their order number, A-1042, and the assista…
turn 5 view USER What was my order number?
view ASSISTANT Your order number is A-1042.
... one more compaction and its summary ...
The summary in the view:
The user first asked the assistant to remember their order number, A-1042, and the assistant confirmed it
had noted it. The user then asked about the weather in Amsterdam, and the assistant used the weather tool to
report 12°C and rainy. The user next asked about Barcelona, and the assistant used the weather tool again
and reported 21°C and sunny. No pending actions or unresolved questions remain. The order number A-1042
should still be retained for later use.
A few implementation details:
ChatModel directly, bypassing the advisor chain. It can use a different model than the conversation: pass another ChatModel to the builder, or set its chatOptions(...).Events that are no longer in the view remain available for retrieval. SessionService.searchEvents searches the message text of the whole session log by keyword, and SessionRecallTools exposes the same search to the model as the conversation_search tool:
ChatClient chatClient = ChatClient.builder(chatModel)
.defaultAdvisors(SessionAdvisors.builder(sessionService)
.sessionIdInToolContext(true)
.build())
.defaultTools(SessionRecallTools.builder(sessionService).build())
.build();
The tool reads the session id from the tool context, and sessionIdInToolContext(true) puts it there. This setting is off by default, because every tool of the call can then read the id.
The search is keyword based and limited to a single session. It does not cover tool results, and it is not a semantic search.
JdbcSessionRepository supports the five databases listed above, with idempotent, version-checked appends.ChatMemory for now.SessionRepository and can be verified with the AbstractSessionRepositoryContractTests from spring-ai-test.The session advisors keep no state of their own between calls. With a shared store such as the JDBC repository, any instance of the application can therefore run any turn of a session, as long as the calls of that session are serialized.
The API maps closely, but the behaviour differs in a few places that are worth checking before the switch:
Existing conversations are not migrated. The two stores do not share their tables, and there is no conversion tool. Old conversations either start fresh or have to be copied by the application, for example:
sessionService.findOrCreate(CreateSessionRequest.builder().id(conversationId).build());
chatMemory.get(conversationId).stream()
.filter(message -> !(message instanceof SystemMessage))
.forEach(message -> sessionService.appendMessage(conversationId, message));
Tool calls are stored. The memory advisor runs inside the tool calling loop, once per round, and the history now includes the tool calls and their results. Consequently, an advisor that is ordered around the memory advisor may see different messages than before. The decision models article discusses two examples, a guardrail and a self-refine advisor.
System messages are not stored. A system prompt is treated as configuration and has to be supplied with every request, using defaultSystem(...) or .system(...).
Sessions expire. By default a session lives for 60 days (spring.ai.session.time-to-live). Expired sessions are not removed automatically, so call sessionService.deleteExpiredSessions(Instant.now()) from a scheduler.
One call per session at a time. Calls on the same session have to be serialized by the application.
The community Spring AI Session project has moved into Spring AI. Version 0.10.0 is its last release, and the repository will be archived on December 1, 2026.
The package names did not change, only the Maven coordinates: org.springaicommunity:spring-ai-session becomes org.springframework.ai:spring-ai-session, and the advisors are now in spring-ai-session-advisor. Make sure that only one of the two is on the classpath. The main API changes are that the user id became session metadata (SessionAttributes.PRINCIPAL_NAME), the four compaction strategies became WindowCompactionStrategy, and the JDBC schema is new, with no conversion script. The migration guide of the community project lists every change.
Branch isolation for sub-agents, described in the April article, was removed in 0.10.0 and is not part of Spring AI. The recommended alternative is a separate session for each sub-agent. Spring AI Agent Utils follows this approach in its next release, 0.15, where each sub-agent run gets a child session that names its caller in its metadata.
The Session API is not limited to conversation memory. Because the set of event types is extensible, an application or a library can append events of its own type to the log. Such events are never sent to the model. Here is an example of such a log:
Two community projects already build on this:
TURN.STATUS, TURN.QUESTION, TURN.ANSWER and TURN.INTERRUPT. A tool call that waits for a person's confirmation is recorded as such a question, which is why it survives a restart. See Human in the Loop with Spring AI 2.1 for details.The Session API separates the conversation history from the model's context. It records an append-only event history, and windowing, compaction and recall manage the context without losing that history. Because its event model is extensible, the same log also holds the state of an agent harness.
For existing ChatMemory applications the migration is small: a different starter, the session advisors and a session id on every call. The main considerations are the behaviour changes, the existing conversations and the removal of expired sessions. ChatMemory remains available until Spring AI 3.0.0, which leaves time to migrate as the remaining session repositories become available.
Spring AI
Demo
spring-ai-chat-memory-to-session-demo — the same conversation with ChatMemory and with session memoryCommunity projects
Background
Related articles