← Blog

Claude API Chatbot Memory Persistence Guide

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

If you're building a chatbot with the Claude API and wondering why it "forgets" everything between requests, the answer is simple: Claude is stateless. Every call to the Messages endpoint is independent — there is no server-side session, no hidden conversation ID, no built-in memory. If you want your bot to remember what the user said five minutes (or five days) ago, you have to build that persistence yourself.

This guide covers the practical patterns for doing that: storing conversation history, managing the context window as conversations grow, summarizing old messages so they don't blow your token budget, and implementing longer-term "memory" that survives across sessions.

Why Claude doesn't remember anything by default

The Claude API is a pure request/response model. Each call to /v1/messages takes a messages array and returns a reply — Claude has no knowledge of any previous call unless you include that history in the request yourself. This is true whether you're calling Anthropic directly or through a proxy like SubToAPI; the underlying model behavior is the same.

That means "memory" in a Claude chatbot is really just you re-sending the relevant parts of the conversation on every request. The engineering problem isn't "how do I turn on memory" — it's "what do I store, what do I resend, and what do I summarize or drop."

Level 1: Short-term memory (the current conversation)

The simplest form of persistence is keeping the full message history for an active conversation and replaying it on each turn.

// Store messages per conversation ID in your DB
const history = await db.getMessages(conversationId);

history.push({ role: "user", content: userInput });

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",
    max_tokens: 1024,
    messages: history
  })
});

const data = await response.json();
history.push({ role: "assistant", content: data.content });
await db.saveMessages(conversationId, history);

This works fine for short conversations, but two problems appear as the conversation grows:

  1. Token cost — you're re-sending the entire history on every single turn, so cost grows roughly quadratically with conversation length.
  2. Context window limits — eventually the history exceeds the model's context window and requests start failing or truncating.

See the full request/response shape in the Messages API docs.

Level 2: Sliding window + summarization

The standard fix is a hybrid: keep the last N messages verbatim (so recent context is sharp), and periodically compress older messages into a running summary.

A practical implementation:

async function compressHistory(oldMessages) {
  const summaryResponse = 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",
      max_tokens: 200,
      messages: [{
        role: "user",
        content: `Summarize this conversation segment in 3 sentences, keeping names, decisions, and open questions:\n\n${JSON.stringify(oldMessages)}`
      }]
    })
  });
  const data = await summaryResponse.json();
  return data.content[0].text;
}

Use a cheaper/faster model for summarization — you don't need your strongest model to compress old chat turns, which is a good use case for picking a lighter model tier if your provider supports model selection per request.

This keeps token usage roughly flat regardless of how long the conversation runs, at the cost of some fidelity on older details.

Level 3: Long-term memory across sessions

Short-term memory solves "remember this conversation." Long-term memory solves "remember this user" — their preferences, facts they've told you, prior decisions — even after the session ends and a new one starts days later.

The common pattern:

  1. Extract facts, don't store transcripts. After each session (or periodically), ask Claude to extract durable facts about the user ("prefers Python over JS", "is building a logistics app", "timezone: CET") into a structured list.
  2. Store facts keyed by user ID, not conversation ID, in a normal database table.
  3. Inject relevant facts as a system message at the start of new conversations instead of replaying old transcripts.
{
  "role": "system",
  "content": "User facts: prefers concise answers. Working on a Next.js e-commerce project. Timezone: CET. Previously asked about Stripe webhooks."
}

For larger fact stores, a vector database retrieval step (embed the user's new message, pull the top-k relevant stored facts) scales better than dumping every known fact into every request. But for most chatbots — support bots, personal assistants, internal tools — a flat fact table per user is simpler and good enough.

Where to actually store the data

Memory persistence is a database problem, not an API problem. Common choices:

None of this requires anything special from the API layer — it's standard application state management, with Claude calls dropped in at the points where you need to read or write.

Tying it into a real API setup

If you're prototyping this, don't start by wiring up raw API keys per environment. SubToAPI gives you a single application key (sub_live_...) you can use across dev, staging, and production, with usage metadata on every response so you can see token consumption per conversation — useful for tuning how aggressively you need to summarize. Streaming is supported too if your chatbot needs token-by-token responses (streaming docs), and tool use works the same way if your memory layer needs to call out to a database lookup function mid-conversation (tools docs).

Start with the quickstart to get a key, then layer the memory patterns above on top — they're identical whether you're calling Claude directly or through a proxy.

questions

Does the Claude API have a built-in "memory" or session feature? No. Every request is stateless. Any memory — short-term conversation history or long-term user facts — has to be stored and replayed by your application.

How do I keep long conversations from exceeding the context window? Use a sliding window of recent messages plus periodic summarization of older turns, compressed into a short synthetic message that replaces the raw history it summarizes.

What's the best way to remember things about a user across separate sessions? Extract durable facts (preferences, prior decisions) into a structured record keyed by user ID, stored in a regular database, and inject relevant facts as a system message at the start of new sessions instead of resending old transcripts.

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 →