Claude API Chat History & Memory Management Guide
Claude's API is stateless — every request you send must include the full conversation history, because Claude has no memory of previous turns on its own. "Chat history memory management" means building the system around the API that stores, trims, and reconstructs that history so conversations feel continuous without blowing past token limits or your budget.
The short answer: store every message in your own database, send back only what's relevant (not necessarily everything), and use summarization or sliding windows once the conversation gets long. The rest of this article walks through how to implement that in practice.
Why Claude Doesn't Remember Anything by Default
Each call to /v1/messages is independent. If you send a single user message with no prior context, Claude has no idea what was said five minutes — or five seconds — ago. The messages array you send is the memory. If it's not in that array, Claude can't see it.
This is different from a stateful chat product like the Claude.ai web app, which manages history for you behind the scenes. When you build on the API directly, you own that responsibility.
The Basic Pattern: Store Everything, Send What's Needed
A minimal memory system has three parts:
- Persistent storage — a database table keyed by conversation ID, storing every user and assistant message with timestamps.
- A retrieval/assembly step — before each API call, pull the relevant messages and build the
messagesarray. - A write-back step — after Claude responds, save both the user's message and Claude's reply.
async function sendMessage(conversationId, userText) {
const history = await db.getMessages(conversationId); // array of {role, content}
const messages = [...history, { role: "user", content: userText }];
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
})
});
const data = await response.json();
const reply = data.content[0].text;
await db.saveMessage(conversationId, "user", userText);
await db.saveMessage(conversationId, "assistant", reply);
return reply;
}
This works fine for short conversations. The problem starts when a conversation runs for hours or days — the history grows unbounded, token costs climb, and eventually you'll hit the model's context window limit.
Strategy 1: Sliding Window (Last N Messages)
The simplest fix is to cap how much history you send. Keep the last N messages (or last N tokens) and drop the rest.
function trimHistory(messages, maxMessages = 20) {
if (messages.length <= maxMessages) return messages;
return messages.slice(-maxMessages);
}
This is cheap and predictable, but it's lossy — Claude will "forget" anything outside the window, including facts the user mentioned early on that might still matter ("my name is Sam," "I'm using PostgreSQL 14").
A token-aware version
Message count is a rough proxy for token count. For tighter control, estimate tokens per message and trim by budget instead:
function trimByTokenBudget(messages, maxTokens = 6000) {
let total = 0;
const kept = [];
for (let i = messages.length - 1; i >= 0; i--) {
const estTokens = Math.ceil(messages[i].content.length / 4);
if (total + estTokens > maxTokens) break;
total += estTokens;
kept.unshift(messages[i]);
}
return kept;
}
This is still a rough heuristic — real tokenization varies by content — but it's good enough to avoid sending oversized requests.
Strategy 2: Rolling Summarization
When you don't want to lose old context entirely, periodically compress older turns into a short summary and keep that instead of the raw messages.
Pattern:
- Once history exceeds a threshold (say 30 messages), take the oldest 20.
- Send them to Claude with an instruction like: "Summarize the key facts, decisions, and preferences from this conversation in under 150 words."
- Replace those 20 messages with a single system or user message containing the summary.
- Keep the most recent messages verbatim.
async function summarizeOldMessages(oldMessages) {
const transcript = oldMessages.map(m => `${m.role}: ${m.content}`).join("\n");
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-haiku-4-5",
max_tokens: 300,
messages: [{
role: "user",
content: `Summarize the key facts and decisions from this conversation in under 150 words:\n\n${transcript}`
}]
})
});
const data = await response.json();
return data.content[0].text;
}
Store the summary alongside the untouched recent messages. This keeps conversations feeling coherent indefinitely while keeping token usage bounded. It costs an extra API call per summarization cycle, but a smaller/cheaper model works well for this since the task is simple.
Strategy 3: Structured Memory (Facts, Not Transcripts)
For long-lived assistants — a support bot, a personal assistant — raw transcript storage is often the wrong model. Instead, extract structured facts as the conversation progresses ("user's plan: Team," "prefers dark mode," "last order #4821") and store them separately from the chat log. Inject only the relevant facts into the system prompt for each new conversation, rather than replaying old messages.
This is more engineering work upfront but scales much better than ever-growing transcripts, and it avoids re-sending stale conversational filler that adds no value.
Choosing a Strategy
- Short-lived sessions (support chat, one-off tasks): sliding window is usually enough.
- Long conversations that need continuity: rolling summarization.
- Persistent assistants across many sessions: structured memory plus a small amount of recent transcript.
Whichever approach you pick, the mechanics of calling the API don't change — you're still assembling a messages array and sending it fresh each time. If you're routing these calls through SubToAPI, the same patterns apply directly against /v1/messages; see the quickstart and messages docs for request/response details, or streaming if you want partial responses while the assistant is still generating.
FAQ
Does Claude remember past conversations automatically? No. Each API call is stateless — Claude only "remembers" what's included in the messages array of that specific request. Your application is responsible for storing and resending history.
How much history should I send on every request? Enough to preserve relevant context without approaching the model's context window limit. A sliding window of the last 10–20 turns, or a rolling summary plus recent turns, works for most chat applications.
What's the cheapest way to manage long conversation history? Trimming by token budget is cheapest computationally, since it adds no extra API calls. Summarization costs a small additional request per cycle but preserves more context over long conversations.