← Blog

Claude API Chat History Persistence: Database Guide

2026-11-21 · 5 min read · SubToAPI Team

Why Claude API chat history needs its own database layer

The Claude API is stateless: every request you send is a self-contained list of messages, and Anthropic doesn't store your conversation history for you to retrieve later. If you want a chatbot, support tool, or AI feature that remembers what a user said five minutes — or five days — ago, you have to persist the conversation yourself in a database and replay the relevant messages on each new request.

This is the core answer to "how do I persist Claude API chat history": store every message (role, content, timestamps, conversation ID) in your own database, then on each new turn, fetch the prior messages for that conversation and send them back to the API as the messages array. Claude never "remembers" anything between calls — your database is the memory.

The basic persistence pattern

A conversation with Claude is just an ordered array of {role, content} objects. To persist it, you need a table (or document) that can reconstruct that array for any given conversation at any point in time.

A minimal relational schema looks like this:

CREATE TABLE conversations (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL,
  title TEXT,
  created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE messages (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  conversation_id UUID REFERENCES conversations(id),
  role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),
  content TEXT NOT NULL,
  token_count INT,
  created_at TIMESTAMPTZ DEFAULT now()
);

CREATE INDEX idx_messages_conversation ON messages(conversation_id, created_at);

On each new user turn:

  1. Insert the new user message into messages.
  2. Query all messages for that conversation_id, ordered by created_at.
  3. Map them into the messages array format the API expects.
  4. Send the request, get the assistant reply.
  5. Insert the assistant reply into messages.
async function sendTurn(conversationId, userText) {
  await db.query(
    `INSERT INTO messages (conversation_id, role, content) VALUES ($1, 'user', $2)`,
    [conversationId, userText]
  );

  const { rows } = await db.query(
    `SELECT role, content FROM messages WHERE conversation_id = $1 ORDER BY created_at ASC`,
    [conversationId]
  );

  const response = await fetch('https://api.subtoapi.app/v1/messages', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.SUBTOAPI_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'claude-sonnet-4-5',
      max_tokens: 1024,
      messages: rows
    })
  });

  const data = await response.json();
  const assistantText = data.content[0].text;

  await db.query(
    `INSERT INTO messages (conversation_id, role, content) VALUES ($1, 'assistant', $2)`,
    [conversationId, assistantText]
  );

  return assistantText;
}

That's the whole pattern. Everything else — pruning, summarization, multi-tenant isolation — is an optimization on top of it. See /docs/messages for the full request/response shape.

Choosing a database: SQL vs document store vs vector store

Relational (Postgres, MySQL): Best default. Conversations and messages map cleanly to two tables, you get transactional guarantees, and you can join against your users/billing tables. Use JSONB columns if message content includes tool calls or structured blocks rather than plain text.

Document store (MongoDB, DynamoDB): Natural fit if each conversation is a single document with an array of messages. Simpler to reason about, but watch document size limits if conversations get long — DynamoDB caps items at 400KB.

Vector database (Pinecone, pgvector, Weaviate): Not a replacement for message storage, but a useful addition when you need semantic search over past conversations ("find the time this user asked about refunds"). Store the raw messages in your primary database and embeddings in the vector store, keyed by message ID.

For most products, Postgres with a conversations + messages schema is sufficient and the easiest to migrate and query later.

Handling context window limits

Persisting every message forever is easy; sending every message back to Claude on every turn is not, because context windows and cost both grow with history length. Three common strategies:

A practical hybrid: keep the last 10–15 turns verbatim, summarize everything older into a running summary field on the conversations table, and update that summary every 20 messages or so.

ALTER TABLE conversations ADD COLUMN running_summary TEXT;
const systemPrompt = conversation.running_summary
  ? `Earlier context: ${conversation.running_summary}`
  : undefined;

Multi-user and multi-tenant considerations

If you're building this into a product with multiple users or teams, always scope queries by user_id or tenant_id — never trust a client-supplied conversation_id alone. Add a WHERE user_id = $current_user clause to every read, and index on (user_id, conversation_id).

If your app is calling Claude through SubToAPI, the persistence layer described above sits entirely in your own infrastructure — SubToAPI handles the API key, streaming (/docs/streaming), tool use (/docs/tools), and usage metadata per request, but your database is still what gives the conversation continuity. This separation is useful: you can swap models or providers later without touching your storage schema, since it's just role/content pairs.

Don't forget retention and deletion

Chat history often contains personal data, so decide your retention policy up front: how long messages are kept, whether users can delete a conversation, and whether deletion is a hard delete or a soft delete (deleted_at column) for audit purposes. A simple cron job that purges conversations older than your retention window keeps storage costs predictable and keeps you compliant with whatever privacy commitments you've made to users.

Questions

Does Claude or Anthropic store my conversation history for me? No. The API is stateless — each request only contains what you send in the messages array. You're responsible for persisting and replaying history yourself.

What's the simplest schema for storing Claude chat history? Two tables: conversations (one row per thread) and messages (one row per turn, with role, content, and a foreign key to the conversation). This covers the vast majority of use cases.

How do I keep long conversations from exceeding the context window? Use a sliding window of recent messages combined with a periodically updated summary of older turns, or retrieve only semantically relevant past messages instead of sending the entire history every time.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →