Conversation State and Persistence
Store threads, messages, tool calls and attachments so conversations survive reloads, sync across devices and stay within context limits.
Intermediate · about 4 hours · difficulty 3/5
Learn first: Chat and Streaming Interfaces, SQL and Postgres Basics, Memory and Context Engineering
Model APIs are stateless, so your application owns the conversation. How you store it affects cost, debuggability and features like search, sharing and branching.
Data model
A common schema has conversations (owner, title, created time, settings), messages (role, content blocks, model, token usage, parent message id) and attachments. Store the full content blocks, including tool calls and tool results, so you can replay a conversation exactly.
Features that depend on it
- Resume on reload and across devices.
- Branching: editing an earlier message creates a new branch rather than deleting history.
- Auto titles: a cheap model summarizes the first exchange into a title.
- Search over past conversations with full-text or embeddings.
- Sharing and export with permission checks.
Fitting the context window
Long threads eventually exceed limits or become expensive. Options: send only the last N turns, summarize older turns into a running summary, or retrieve relevant earlier messages. Keep the system prompt and key facts pinned.
Provider-managed state
Some APIs can store conversation state server side and let you reference a previous response by id. It is convenient but ties history to one provider and its retention rules; many teams still keep their own copy.
Good enough to move on
Your chat app persists conversations in Postgres with full content blocks, supports branching on edit, auto-titles threads, and trims history with a running summary when it gets long.
Key concepts
- Conversation and message schema
- Storing tool calls and results
- Branching on edit
- Auto-generated titles
- History trimming and summaries
- Conversation search
- Provider-managed state trade-offs
Mini project
Add persistence to your chat UI: a Postgres schema for conversations and messages with parent ids, a sidebar of past threads with auto titles, and branching when a user edits an earlier message.
Check yourself
Why store tool calls and tool results in the message history instead of only the final assistant text?
Free resources
- PostgreSQL: JSON types (PostgreSQL)
- OpenAI docs: conversation state (OpenAI)
- AI SDK UI: chatbot message persistence (Vercel)