CtrlK
CommunityDocumentationLog inGet started
Tessl Logo

tessl/maven-org-springframework-ai--spring-ai-autoconfigure-model-chat-memory

Spring Boot auto-configuration for chat memory functionality in Spring AI applications

Overview
Eval results
Files

troubleshooting.mddocs/reference/

Troubleshooting Guide

Common issues and solutions for Spring AI Chat Memory.

Installation Issues

Dependency Not Found

Problem: Maven/Gradle cannot find the artifact.

Solution:

  1. Verify version number is correct (1.1.2)
  2. Check repository configuration
  3. Clear local Maven cache: mvn clean install -U

Class Not Found Exception

Problem: ClassNotFoundException for ChatMemory or related classes.

Solution:

<!-- Ensure correct dependency -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-autoconfigure-model-chat-memory</artifactId>
    <version>1.1.2</version>
</dependency>

Configuration Issues

Auto-Configuration Not Working

Problem: Beans not created automatically.

Symptoms:

  • NoSuchBeanDefinitionException for ChatMemory
  • Application fails to start

Solution:

  1. Verify dependency is on classpath

  2. Check Spring Boot version compatibility

  3. Ensure auto-configuration is not disabled:

    // Don't exclude ChatMemoryAutoConfiguration
    @SpringBootApplication(exclude = {})
  4. Check logs for auto-configuration report:

    logging.level.org.springframework.boot.autoconfigure=DEBUG

Multiple Bean Definitions

Problem: BeanDefinitionOverrideException or unexpected bean used.

Solution:

// Use @Primary to specify default bean
@Configuration
public class ChatMemoryConfig {
    
    @Bean
    @Primary
    public ChatMemory primaryChatMemory() {
        return MessageWindowChatMemory.builder()
            .maxMessages(50)
            .build();
    }
}

Runtime Issues

IllegalArgumentException: Conversation ID Cannot Be Null

Problem: Null or empty conversation ID passed to ChatMemory methods.

Solution:

public void addMessage(String conversationId, Message message) {
    if (conversationId == null || conversationId.trim().isEmpty()) {
        throw new IllegalArgumentException("Conversation ID must not be null or empty");
    }
    chatMemory.add(conversationId, message);
}

Messages Not Persisting Across Restarts

Problem: All messages lost when application restarts.

Cause: Using default InMemoryChatMemoryRepository.

Solution: Add persistent repository dependency:

<!-- For JDBC -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-autoconfigure-model-chat-memory-repository-jdbc</artifactId>
    <version>1.1.2</version>
</dependency>

Messages Being Evicted Too Quickly

Problem: Older messages disappear before expected.

Cause: Default window size is 20 messages.

Solution:

@Bean
public ChatMemory chatMemory(ChatMemoryRepository repository) {
    return MessageWindowChatMemory.builder()
        .chatMemoryRepository(repository)
        .maxMessages(100)  // Increase window size
        .build();
}

System Messages Not Preserved

Problem: System messages being evicted.

Cause: Not using MessageWindowChatMemory or custom implementation without special handling.

Solution: Use MessageWindowChatMemory which automatically preserves system messages:

MessageWindowChatMemory memory = MessageWindowChatMemory.builder()
    .maxMessages(50)
    .build();

Database Issues

JDBC: Schema Not Initialized

Problem: Table does not exist error.

Solution:

spring.ai.chat.memory.repository.jdbc.initialize-schema=always

For Production: Use migration tools (Flyway/Liquibase) instead:

spring.ai.chat.memory.repository.jdbc.initialize-schema=never

JDBC: Wrong Dialect Detected

Problem: SQL syntax errors due to incorrect dialect.

Solution: Explicitly set platform:

spring.ai.chat.memory.repository.jdbc.platform=postgresql

MongoDB: Connection Refused

Problem: Cannot connect to MongoDB.

Solution:

  1. Verify MongoDB is running: mongosh
  2. Check connection string:
    spring.data.mongodb.uri=mongodb://localhost:27017/chatmemory
  3. Check firewall/network settings

MongoDB: Index Creation Failed

Problem: Indices not created automatically.

Solution:

spring.ai.chat.memory.repository.mongo.create-indices=true

Manual Creation:

db.chat_memory.createIndex({ "conversationId": 1 })

Cassandra: Keyspace Does Not Exist

Problem: InvalidQueryException: Keyspace does not exist.

Solution: Create keyspace manually or enable auto-creation:

spring.ai.chat.memory.repository.cassandra.initialize-schema=true

Manual Creation:

CREATE KEYSPACE IF NOT EXISTS my_keyspace 
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};

Neo4j: Authentication Failed

Problem: Cannot authenticate to Neo4j.

Solution: Check credentials:

spring.neo4j.uri=bolt://localhost:7687
spring.neo4j.authentication.username=neo4j
spring.neo4j.authentication.password=your-password

Cosmos DB: Request Rate Too Large

Problem: 429 Too Many Requests errors.

Solution:

  1. Increase provisioned RUs in Azure Portal
  2. Implement retry logic:
    @Retryable(
        value = {CosmosException.class},
        maxAttempts = 3,
        backoff = @Backoff(delay = 1000)
    )
    public void addMessage(String conversationId, Message message) {
        chatMemory.add(conversationId, message);
    }

Performance Issues

High Memory Usage

Problem: Application consuming too much memory.

Causes:

  1. Using InMemoryChatMemoryRepository with many conversations
  2. Window size too large
  3. No cleanup strategy

Solutions:

  1. Switch to persistent repository
  2. Reduce window size:
    .maxMessages(20)  // Smaller window
  3. Implement cleanup:
    @Scheduled(cron = "0 0 2 * * *")
    public void cleanup() {
        cleanupOldConversations(Duration.ofDays(7));
    }

Slow Database Queries

Problem: High latency for ChatMemory operations.

Solutions:

  1. Add Indexes:

    CREATE INDEX idx_conversation_id ON chat_memory(conversation_id);
  2. Connection Pooling:

    spring.datasource.hikari.maximum-pool-size=20
  3. Batch Operations:

    // Instead of multiple adds
    chatMemory.add(conversationId, messagesList);

OutOfMemoryError

Problem: Application crashes with OOM error.

Solutions:

  1. Increase heap size: -Xmx2g
  2. Use persistent repository
  3. Implement aggressive cleanup
  4. Reduce window size
  5. Monitor with profiler

Concurrency Issues

ConcurrentModificationException

Problem: Exception when accessing messages concurrently.

Solution: Repository implementations should be thread-safe. If using custom implementation:

private final ConcurrentHashMap<String, List<Message>> store = new ConcurrentHashMap<>();

public List<Message> findByConversationId(String conversationId) {
    // Return defensive copy
    return new ArrayList<>(store.getOrDefault(conversationId, Collections.emptyList()));
}

Race Conditions

Problem: Messages appear in wrong order or get lost.

Solution: Implement conversation-level locking:

private final ConcurrentHashMap<String, ReentrantLock> locks = new ConcurrentHashMap<>();

public void addMessageSafely(String conversationId, Message message) {
    ReentrantLock lock = locks.computeIfAbsent(conversationId, k -> new ReentrantLock());
    lock.lock();
    try {
        chatMemory.add(conversationId, message);
    } finally {
        lock.unlock();
    }
}

Serialization Issues

Message Serialization Failed

Problem: Cannot serialize/deserialize messages.

Causes:

  • Custom message types without proper serialization
  • Large binary data in messages

Solutions:

  1. Ensure message classes are serializable
  2. Store large media externally:
    if (mediaData.length > 10_000_000) {
        String url = storeExternally(mediaData);
        message = new UserMessage("See media at: " + url);
    }

Migration Issues

Data Loss During Migration

Problem: Messages lost when switching repositories.

Solution: Implement migration service:

@Service
public class MigrationService {
    
    @Autowired
    @Qualifier("sourceRepository")
    private ChatMemoryRepository source;
    
    @Autowired
    @Qualifier("targetRepository")
    private ChatMemoryRepository target;
    
    public void migrate() {
        List<String> ids = source.findConversationIds();
        for (String id : ids) {
            List<Message> messages = source.findByConversationId(id);
            target.saveAll(id, messages);
        }
    }
}

Incompatible Schema Changes

Problem: Schema changes break existing data.

Solution: Use database migration tools:

  • Flyway: Version-controlled schema migrations
  • Liquibase: Database-independent migrations

Debugging Tips

Enable Debug Logging

logging.level.org.springframework.ai.chat.memory=DEBUG
logging.level.org.springframework.ai.model.chat.memory=DEBUG

Health Check

@Component
public class ChatMemoryHealthIndicator implements HealthIndicator {
    
    @Autowired
    private ChatMemoryRepository repository;
    
    @Override
    public Health health() {
        try {
            repository.findConversationIds();
            return Health.up()
                .withDetail("repository", repository.getClass().getSimpleName())
                .build();
        } catch (Exception e) {
            return Health.down(e)
                .withDetail("error", e.getMessage())
                .build();
        }
    }
}

Verify Configuration

@Component
public class ConfigurationVerifier implements CommandLineRunner {
    
    @Autowired
    private ChatMemory chatMemory;
    
    @Autowired
    private ChatMemoryRepository repository;
    
    @Override
    public void run(String... args) {
        logger.info("ChatMemory implementation: {}", chatMemory.getClass().getName());
        logger.info("Repository implementation: {}", repository.getClass().getName());
        
        // Test basic operations
        String testId = "test-" + UUID.randomUUID();
        chatMemory.add(testId, new UserMessage("test"));
        List<Message> messages = chatMemory.get(testId);
        chatMemory.clear(testId);
        
        logger.info("Chat memory verification: SUCCESS");
    }
}

Common Error Messages

"No qualifying bean of type 'ChatMemory'"

Cause: Auto-configuration not triggered or dependency missing.

Solution: Add dependency and verify classpath.

"Table 'chat_memory' doesn't exist"

Cause: Schema not initialized.

Solution: Enable schema initialization or create table manually.

"conversationId must not be null"

Cause: Null conversation ID passed to method.

Solution: Validate inputs before calling ChatMemory methods.

"Message list cannot contain null elements"

Cause: Null message in list passed to batch add.

Solution: Filter nulls before adding:

messages = messages.stream()
    .filter(Objects::nonNull)
    .collect(Collectors.toList());
chatMemory.add(conversationId, messages);

Getting Help

If issues persist:

  1. Check Logs: Enable DEBUG logging
  2. Verify Configuration: Use health checks
  3. Test Isolation: Create minimal reproduction
  4. Check Documentation: Review API Reference
  5. Community: Spring AI GitHub Issues

Next Steps

tessl i tessl/maven-org-springframework-ai--spring-ai-autoconfigure-model-chat-memory@1.1.0

docs

index.md

tile.json