0Pricing
AI Engineering Academy · Lesson

Persisting Chat History in Redis and PostgreSQL

Store conversation history externally using RedisChatMessageHistory and PostgresChatMessageHistory so memory survives application restarts and scales across multiple instances.

Why Persist Chat History Externally?

In-memory conversation history vanishes when your application restarts or scales to multiple instances. External persistence solves three problems: history survives crashes, multiple server instances share the same history, and you can load past sessions for returning users. Redis and PostgreSQL are the two most popular backends for this.

LangChain Chat Message History Interface

LangChain defines a BaseChatMessageHistory interface with two methods: add_message(message) and messages (property). Any storage backend that implements this interface can drop in as memory for any LangChain chain. Both Redis and PostgreSQL implementations follow this interface.

from langchain_community.chat_message_histories import RedisChatMessageHistory

# Each unique session_id gets its own history namespace
history = RedisChatMessageHistory(
    session_id='user:alice:session:42',
    url='redis://localhost:6379'
)

# Add messages
history.add_user_message('What is RAG?')
history.add_ai_message('RAG stands for Retrieval-Augmented Generation...')

# Retrieve stored messages
for msg in history.messages:
    print(msg.type, ':', msg.content[:50])

All lessons in this course

  1. Why Stateless LLMs Need External Memory
  2. Buffer and Window Memory
  3. Summary Memory and Token-Aware Truncation
  4. Persisting Chat History in Redis and PostgreSQL
← Back to AI Engineering Academy