Spring › Spring-AI

Persisting Gemini chat sessions with Spring AI and Redis

Persist multi-turn Gemini chat sessions in Redis with Spring AI 2.0.1 MessageChatMemoryAdvisor, sliding windows, and a RediSearch metadata fix.

Persisting Gemini chat sessions with Spring AI and Redis

Google Gemini’s API is stateless, so every turn in a multi-turn conversation requires re-sending prior messages in the prompt. This post shows how to combine Spring AI 2.0.1’s MessageChatMemoryAdvisor with RedisChatMemoryRepository to persist chat sessions across instances, cap token growth with a sliding window, and fix a RediSearch metadata indexing bug with Gemini responses.

Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, Redis 7 (Redis Stack with RediSearch), and gemini-3.5-flash-lite.


Why in-memory chat history breaks in production

In my earlier setup for SSE streaming chat with Gemini, InMemoryChatMemoryRepository worked fine for local testing. It stores conversation lists directly in the JVM heap, which breaks down as soon as you deploy behind a load balancer:

  1. Restarts wipe every session: Rolling deployments, OOM kills, or pod evictions erase active conversation context.
  2. Multi-instance routing loses context: If a user’s second request hits a different backend instance behind an L4 or L7 load balancer, that instance has no record of the first turn.
  3. Unbounded history inflates token bills: Appending every turn forever drives input token counts up linearly per message and quadratically across a long session.

Moving memory into Redis fixes the first two issues, while MessageWindowChatMemory caps the window size to control token spend. Here is how a request flows through the advisor and Redis:

flowchart TD
    User["Client request (conversationId)"] --> Client["Spring Boot ChatClient"]
    Client --> Advisor["MessageChatMemoryAdvisor"]
    Advisor <--> Redis[("Redis 7 with RediSearch")]
    Advisor --> Gemini["Google Gemini 3.5 Flash Lite"]
    Gemini --> Advisor
    Advisor --> Reply["JSON reply to client"]

Choosing a ChatMemory backend

Before adding Redis Stack to your infrastructure, check whether it actually fits your workload.

BackendPersistence across restartsMulti-instance sharingExtra infrastructureBest fit
InMemoryChatMemoryRepositoryNoNoNoneLocal demos, single-node prototypes
RedisChatMemoryRepositoryYes (TTL-backed)YesRedis with RediSearch + JSONActive chat sessions with automatic expiry
JdbcChatMemoryRepositoryYesYesExisting RDBMSAudit trails, long-term searchable transcripts

When not to use RedisChatMemoryRepository: Skip it if your Redis deployment doesn’t load the RediSearch and RedisJSON modules (for example, plain ElastiCache or vanilla Redis OSS without Stack modules). The Spring AI repository relies on FT.CREATE and JSON path queries under the hood, so it will fail at startup on standard Redis. In that case, use JdbcChatMemoryRepository or implement a custom ChatMemoryRepository backed by Redis Lists.


Project setup and dependencies

The full runnable module is available in spring-ai-examples (chat-memory-redis).

build.gradle.kts

Add spring-ai-starter-model-chat-memory-repository-redis along with Spring Boot’s Docker Compose support so local runs start Redis automatically:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
plugins {
    kotlin("jvm") version "2.3.21"
    kotlin("plugin.spring") version "2.3.21"
    id("org.springframework.boot") version "4.1.1"
    id("io.spring.dependency-management") version "1.1.7"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
    implementation("org.springframework.ai:spring-ai-starter-model-chat-memory-repository-redis")

    // Auto-start Redis via Docker Compose during local development
    developmentOnly("org.springframework.boot:spring-boot-docker-compose")

    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.springframework.boot:spring-boot-testcontainers")
    testImplementation("org.testcontainers:junit-jupiter")
}

application.yaml

Configure the Redis connection, key prefix, RediSearch index name, 24-hour TTL, and the sliding window limit (max-messages: 10):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
server:
  port: 8083

spring:
  application:
    name: chat-memory-redis
  ai:
    google:
      genai:
        api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY}
        chat:
          options:
            model: gemini-3.5-flash-lite
            temperature: 0.7
    chat:
      memory:
        repository:
          redis:
            host: ${SPRING_DATA_REDIS_HOST:localhost}
            port: ${SPRING_DATA_REDIS_PORT:6379}
            key-prefix: "spring:ai:chat:memory:"
            index-name: "spring-ai-chat-memory-idx"
            initialize-schema: true
            time-to-live: 24h

app:
  chat-memory:
    max-messages: 10

Fixing the RediSearch metadata indexing bug with Gemini

Wiring up RedisChatMemoryRepository with Google Gemini hit a subtle failure in Spring AI 2.0.1 that looks like a silent data loss bug at first glance.

RedisChatMemoryRepository indexes stored JSON documents through RediSearch. If you don’t specify metadataFields, it defaults to indexing $.metadata.* as TEXT. Because Google Gemini ASSISTANT messages include non-string metadata values (such as nested objects or booleans for finishReason and tokenUsage), RediSearch rejects the document from the index. The key still exists in Redis, but findByConversationId returns an empty list.

The fix is to register your own RedisChatMemoryRepository bean and restrict metadataFields to messageType as a tag field. That keeps RediSearch indexing clean without touching the rest of the message payload:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package io.github.cmsong111.chat_memory_redis.config

import org.springframework.ai.chat.client.ChatClient
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor
import org.springframework.ai.chat.memory.ChatMemory
import org.springframework.ai.chat.memory.MessageWindowChatMemory
import org.springframework.ai.chat.memory.repository.redis.RedisChatMemoryRepository
import org.springframework.ai.model.chat.memory.repository.redis.autoconfigure.RedisChatMemoryRepositoryProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import redis.clients.jedis.RedisClient

@Configuration
class ChatMemoryConfig {

    @Bean
    fun redisChatMemoryRepository(
        jedisClient: RedisClient,
        properties: RedisChatMemoryRepositoryProperties
    ): RedisChatMemoryRepository {
        val builder = RedisChatMemoryRepository.builder()
            .jedisClient(jedisClient)
            .indexName(properties.indexName)
            .keyPrefix(properties.keyPrefix)
            .initializeSchema(properties.initializeSchema)
            // Limit indexed metadata to messageType to avoid Gemini non-string indexing errors
            .metadataFields(listOf(mapOf("name" to "messageType", "type" to "tag")))

        properties.timeToLive?.let { builder.timeToLive(it) }

        return builder.build()
    }

    @Bean
    fun chatMemory(
        redisChatMemoryRepository: RedisChatMemoryRepository,
        chatMemoryProperties: ChatMemoryProperties
    ): ChatMemory {
        return MessageWindowChatMemory.builder()
            .chatMemoryRepository(redisChatMemoryRepository)
            .maxMessages(chatMemoryProperties.maxMessages)
            .build()
    }

    @Bean
    fun chatClient(builder: ChatClient.Builder, chatMemory: ChatMemory): ChatClient {
        return builder
            .defaultSystem("You are a helpful AI assistant that remembers prior turns in the conversation and answers in context.")
            .defaultAdvisors(
                MessageChatMemoryAdvisor.builder(chatMemory).build(),
                SimpleLoggerAdvisor()
            )
            .build()
    }
}

With MessageWindowChatMemory wrapped inside MessageChatMemoryAdvisor, Spring AI loads the latest N messages before calling Gemini and appends the new user/assistant pair right after the call completes.


Implementing the chat memory service

Pass the session key through the advisor parameter chat_memory_conversation_id on every call. The service also exposes helper methods to inspect or clear a conversation’s stored history:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package io.github.cmsong111.chat_memory_redis.service

import io.github.cmsong111.chat_memory_redis.dto.ChatReply
import io.github.cmsong111.chat_memory_redis.dto.HistoryMessage
import org.slf4j.LoggerFactory
import org.springframework.ai.chat.client.ChatClient
import org.springframework.ai.chat.memory.ChatMemory
import org.springframework.stereotype.Service

@Service
class ChatMemoryService(
    private val chatClient: ChatClient,
    private val chatMemory: ChatMemory
) {
    private val log = LoggerFactory.getLogger(javaClass)

    fun chat(conversationId: String, message: String): ChatReply {
        val response = chatClient.prompt()
            .user(message)
            .advisors { it.param("chat_memory_conversation_id", conversationId) }
            .call()
            .content() ?: ""

        val totalStored = chatMemory.get(conversationId, 100).size
        log.debug("[{}] Stored messages: {}", conversationId, totalStored)

        return ChatReply(
            conversationId = conversationId,
            reply = response,
            storedMessages = totalStored
        )
    }

    fun getHistory(conversationId: String): List<HistoryMessage> {
        return chatMemory.get(conversationId, 100).map {
            HistoryMessage(messageType = it.messageType.name, content = it.text ?: "")
        }
    }

    fun clearHistory(conversationId: String) {
        chatMemory.clear(conversationId)
        log.debug("[{}] Cleared conversation history", conversationId)
    }
}

Because MessageChatMemoryAdvisor handles both reading and writing, the service code stays free of manual prompt assembly.


Integration tests and Redis verification

I verified the pipeline against a live Redis instance and Gemini API across three scenarios:

  1. Multi-turn recall: Introduce a name in turn 1 and confirm the model recalls it in turn 2.
  2. Session isolation: Verify that a secret stored under session-a never leaks into session-b.
  3. Sliding window eviction: Confirm that exceeding maxMessages drops the oldest pair first.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@SpringBootTest
class ChatMemoryRedisIntegrationTests {

    @Autowired
    private lateinit var chatMemoryService: ChatMemoryService

    @Test
    fun `recalls prior conversation turns within the same session`() {
        val conversationId = "it-session-1"

        // Turn 1: provide a fact to remember
        chatMemoryService.chat(conversationId, "My name is Namju Kim. Please remember it.")

        // Turn 2: ask the model to recall it
        val reply = chatMemoryService.chat(conversationId, "What did I say my name is?")

        println("=== [ChatMemoryRedis] Multi-turn Recall ===")
        println("Answer: ${reply.reply}")
        println("Stored messages: ${reply.storedMessages}")

        assertThat(reply.reply).contains("Namju")
        assertThat(reply.storedMessages).isEqualTo(4)
    }

    @Test
    fun `isolates conversation history across different session IDs`() {
        chatMemoryService.chat("session-a", "My secret code is APPLE-123.")
        val isolatedReply = chatMemoryService.chat("session-b", "What is my secret code?")

        assertThat(isolatedReply.reply).doesNotContain("APPLE-123")
    }
}

Test execution output

Integration test console output showing Redis-backed multi-turn chat memory passing Figure 1. JUnit 5 integration tests confirming multi-turn recall and strict session isolation.

A typical debug trace from the multi-turn test shows the stored message counter incrementing by two (user + assistant) per turn:

1
2
3
4
5
6
DEBUG [chat-memory-redis] : [it-session-1] Stored messages: 2/10
DEBUG [chat-memory-redis] : [it-session-1] Stored messages: 4/10
=== [ChatMemoryRedis] Multi-turn Recall ===
Answer: Your name is Namju Kim—you just asked me to remember it.
Stored messages: 4/10 (Redis keyPrefix: spring:ai:chat:memory:)
===========================================

Inspecting keys in redis-cli

Checking spring:ai:chat:memory:* directly in redis-cli confirms that each message is stored as JSON with the configured 24-hour TTL:

Redis CLI output inspecting stored chat memory JSON keys and TTL Figure 2. redis-cli inspection showing serialized USER and ASSISTANT payloads with a 24-hour TTL.

Sliding window eviction log

When maxMessages is set to 4 and a third turn arrives, MessageWindowChatMemory evicts the oldest turn (Q1/A1) before saving the new turn, keeping only the latest four messages in both Redis and the outbound Gemini prompt:

Debug log showing MessageWindowChatMemory evicting oldest messages when exceeding maxMessages Figure 3. Spring Boot debug log confirming oldest-message eviction once the sliding window fills.


Production caveats and checklist

A few operational details are easy to miss until traffic scales up:

  • Never trust raw client-supplied conversationId values: Derive or scope the key with the authenticated user ID (for example, userId:sessionId) so one user can’t read another user’s history by guessing an ID.
  • Watch index schema changes: If you change metadataFields on an existing Redis instance, initialize-schema: true won’t automatically drop and recreate an old RediSearch index. Drop the old index explicitly during migration.
  • Set a finite TTL: Without time-to-live, abandoned sessions accumulate in Redis memory indefinitely. Pick a window that matches your product’s session timeout (such as 24 hours).
  • Tune maxMessages by average turn size: Counting messages isn’t the same as counting tokens. If users paste large stack traces or documents, keep maxMessages conservative (6–10) or add a token-budget check before sending.

Pre-deploy checklist

  • Confirm your target Redis server runs RediSearch and RedisJSON modules.
  • Override RedisChatMemoryRepository with metadataFields restricted to messageType (tag) when using Gemini.
  • Scope chat_memory_conversation_id by authenticated principal to prevent cross-session access.
  • Configure both time-to-live and max-messages so neither Redis memory nor Gemini token bills grow without bound.

The complete source code for this walkthrough is in cmsong111/spring-ai-examples/chat-memory-redis.

This post is licensed under CC BY 4.0 by the author.