Overview
Thememory_db module provides database-backed persistent storage for chat history with Redis caching. It implements a dual-layer storage pattern:
- Redis: Fast cache with TTL-based expiration
- Database: Permanent storage for searchability and analytics
Protocols
DatabaseAdapter
Protocol defining the interface for database adapters.Implementing DatabaseAdapter
Any ORM (SQLAlchemy, Django, etc.) can implement this protocol: SQLAlchemy Example:Classes
DatabaseChatHistory
Database-backed chat history with Redis caching layer.Constructor
| Name | Type | Default | Description |
|---|---|---|---|
session_id | str | - | Session identifier |
db_adapter | DatabaseAdapter | - | Database adapter implementing the protocol |
redis_client | Any | None | None | Redis client (if None, DB-only mode) |
workspace_id | str | None | None | Workspace ID for multi-tenancy |
redis_key_prefix | str | "chat_history:" | Redis key prefix |
redis_ttl | int | None | 3600 | Redis TTL in seconds (None = no expiration) |
Methods
get_messages
Get messages with Redis → DB fallback.- Try Redis cache (fast)
- If cache miss, query DB
- Cache DB results to Redis
- Return messages
list[Message]- List of messages in chronological order
add_message
Add single message (DB + Redis).- Save to DB (permanent)
- Append to Redis cache (fast access)
- Set TTL on Redis key
message- Message to add
add_messages
Add multiple messages in batch.- Batch save to DB
- Batch cache to Redis
messages- List of messages to add
clear
Clear all messages for session (DB + Redis).- Delete from DB
- Delete from Redis cache
Factory Functions
create_database_history_manager
Create SessionHistoryManager with database backend.Signature
db_adapter- Database adapter instanceredis_client- Redis client (optional)redis_ttl- Default Redis TTLdefault_workspace_id- Default workspace ID
SessionHistoryManager- Manager instance
Usage Patterns
Basic Usage (DB Only)
With Redis Caching
Multi-Tenancy
Batch Operations
Session Management
Custom TTL per Session
Database Schema Example
SQLAlchemy Model:Best Practices
Set Appropriate Redis TTL
Set Appropriate Redis TTL
Match TTL to usage patterns:
Use Batch Operations
Use Batch Operations
Reduce DB round-trips with batch inserts:
Handle Redis Failures Gracefully
Handle Redis Failures Gracefully
The system automatically falls back to DB:
Use Workspace Isolation
Use Workspace Isolation
Always use workspace_id for multi-tenant apps:
Index Database Properly
Index Database Properly
Create indexes for fast queries:
Clean Up Old Data
Clean Up Old Data
Implement data retention policies:
Monitor Cache Hit Rate
Monitor Cache Hit Rate
Track Redis cache performance:
Redis Key Format
Key Structure
Key Management
Performance Characteristics
Read Performance
| Scenario | Performance |
|---|---|
| Redis cache hit | ~1ms (instant) |
| Redis cache miss → DB | ~10-100ms (depends on DB) |
| DB only (no Redis) | ~10-100ms |
Write Performance
| Operation | Performance |
|---|---|
| Single message | ~10-50ms (DB write) |
| Batch messages | ~20-100ms (depends on batch size) |
| Redis cache | ~1ms (async, non-blocking) |
Recommendations
- High traffic: Use Redis with TTL
- Historical data: DB only (no cache)
- Real-time chat: Short TTL (5-15 minutes)
- Async analysis: Long TTL or no cache