From ChatMemory to the Session API in Spring AI 2.1

Engineering | Christian Tzolov | November 30, 2026 | 12 min read | ...

Spring 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-demo project runs the same conversation with ChatMemory and with session memory. The output quoted in this article is from live runs of it.

From a Message List to an Event Log

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:

The same conversation of five turns stored in two ways. With ChatMemory, a window keeps the last four messages and the first three turns are dropped and gone. With a session, a log of events holds every turn with its tool calls and results; compaction events move the start of the view to the last two turns, the earlier turns stay in the log, and the model finds the order number of the first turn with conversation_search

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.

Migrating in Three Steps

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:

The session advisors around the tool calling loop: the SessionTurnAdvisor runs once per ChatClient call and finds or creates the session, the ToolCallingAdvisor loops until there are no tool calls, and the SessionMemoryAdvisor runs once per round, where it loads the active view, builds the prompt and stores the user message or tool results and the reply

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.

API Mapping

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 Same Conversation, Before and After

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.

Context Compaction

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.

Compaction with Summarization

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:

  • The summary turn is stored as two synthetic events, a user prompt and the assistant's summary, so that the model keeps seeing alternating user and assistant messages.
  • The summarization call invokes the 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(...).
  • If the call fails or returns an empty reply, the failure is logged and the view remains unchanged, so no history is lost.
  • Summarization is lossy and adds a model call to each compaction. The summarized events remain in the log, and recall still finds them.

Recalling Conversation History

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.

Session Repositories

  • JDBC. JdbcSessionRepository supports the five databases listed above, with idempotent, version-checked appends.
  • Other stores. Session repositories for Cassandra, Neo4j, MongoDB and Redis, as well as the HSQLDB, Oracle and SQLite dialects, are planned before 3.0.0, as the mapping table above notes. If your application depends on one of them, you can stay on ChatMemory for now.
  • Custom stores. A custom store implements SessionRepository and can be verified with the AbstractSessionRepositoryContractTests from spring-ai-test.
  • Community. Spring AI Session Extensions already provides an experimental Kafka repository.

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.

Behaviour Changes

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.

Migrating from the Community Project

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.

Beyond Conversation Memory

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:

An example session log with events of several types, coloured by who writes them: MESSAGE and COMPACTION events from Spring AI, TURN.STATUS, TURN.QUESTION and TURN.ANSWER events from Spring AI Session Extensions, a SUBAGENT event from Spring AI Agent Utils and an ACME.AUDIT event from an application. Only the messages in the view are sent to the model; every other event is state, read by whoever writes it

Two community projects already build on this:

  • Spring AI Session Extensions stores the state of a turn in the log, using its own event types: 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.
  • Spring AI Agent Utils 0.14 implements its recall across sessions on top of the session search.

Conclusion

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.

Resources

Spring AI

Demo

Community projects

Background

Related articles

Get the Spring newsletter

Stay connected with the Spring newsletter

Subscribe

Get ahead

VMware offers training and certification to turbo-charge your progress.

Learn more

Get support

TrueSource Spring Enterprise offers support and binaries for OpenJDK™, Spring, and Apache Tomcat® in one simple subscription.

Learn more

Upcoming events

Check out all the upcoming events in the Spring community.

View all