← Blog

Claude API Agent Memory: Long-Term Storage Guide

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

Claude's API, like every other LLM API, is stateless — it has no built-in long-term memory between requests. Each call to the Messages API only knows what's inside the context window you send it. If you want an agent that remembers a user's preferences, past decisions, or facts from three weeks ago, you have to build that memory layer yourself, outside the model.

This article covers the practical patterns for doing that: what to store, where to store it, how to retrieve it efficiently, and how to keep token costs under control as memory grows. None of this requires a special "memory API" — it's a storage and retrieval problem that sits in front of whatever client you use to call Claude, whether that's the Anthropic API directly or a wrapper like SubToAPI.

Why Claude Has No Native Long-Term Memory

The context window is the model's entire working memory for a single request. Claude 3.5 and newer models support large context windows, but even a 200K-token window gets expensive and slow to fill with months of conversation history, and it still resets on every new session unless you resend it.

"Long-term memory" for an agent really means: an external system that stores facts, summaries, or raw transcripts, and a retrieval step that pulls the relevant subset into the prompt before each call. The model itself never "remembers" anything — you're reconstructing relevant context every time.

The Core Architecture

A working memory system for a Claude agent has three parts:

  1. Storage — a database holding memory records (facts, summaries, embeddings)
  2. Write path — logic that decides what's worth saving after each interaction
  3. Read path — retrieval logic that pulls relevant memories into the next prompt

1. Storage Options

For most agents, you don't need a specialized "vector database" from day one. Pick based on scale:

A simple schema that works well for most agents:

CREATE TABLE agent_memories (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id TEXT NOT NULL,
  content TEXT NOT NULL,
  embedding VECTOR(1536),
  memory_type TEXT, -- 'fact', 'preference', 'event'
  importance SMALLINT DEFAULT 1,
  created_at TIMESTAMPTZ DEFAULT now(),
  last_used_at TIMESTAMPTZ
);

2. The Write Path — Deciding What to Store

Don't store entire transcripts as memory. Extract what's durable. A common pattern is to run a cheap, periodic "memory extraction" pass:

const extraction = 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: 300,
    messages: [{
      role: "user",
      content: `Extract durable facts worth remembering long-term from this conversation. Return a JSON list of short statements, or an empty list if nothing is worth saving:\n\n${conversationText}`
    }]
  })
});

Store each extracted fact as its own row, along with an embedding for later retrieval. Keep the extraction prompt strict — vague summaries pollute memory and make retrieval worse, not better.

3. The Read Path — Retrieval at Query Time

Before sending a new message to Claude, retrieve relevant memories and inject them into the system prompt or as a prefix in the user message:

const relevant = await db.query(`
  SELECT content FROM agent_memories
  WHERE user_id = $1
  ORDER BY embedding <-> $2
  LIMIT 8
`, [userId, queryEmbedding]);

const memoryBlock = relevant.map(r => `- ${r.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-sonnet-4-5",
    max_tokens: 1024,
    system: `You have access to the following long-term memories about this user:\n${memoryBlock}`,
    messages: [{ role: "user", content: userMessage }]
  })
});

Limit this to 5–15 memories per request. Dumping hundreds of facts into the system prompt defeats the purpose — it bloats tokens and the model starts ignoring low-signal content.

Managing Memory Growth and Cost

Long-term memory stores grow forever unless you prune them. A few practical rules:

Session Memory vs. Long-Term Memory

Don't conflate the two. Session memory — the running conversation within one chat — is just the message history you resend each turn, no database required. Long-term memory is what survives across sessions, days, or weeks, and that's what needs the external store described above.

A good agent typically uses both: full message history for the active session (or a summarized version once it gets long), plus a small set of retrieved long-term memories injected at the top. For structured, repeatable agent workflows that call tools alongside memory retrieval, see the tool use docs.

Getting Started Quickly

If you're prototyping this pattern, you don't need to stand up API key infrastructure, rate limiting, and team access on top of your memory layer — SubToAPI gives you an application API key, streaming, and usage tracking out of the box so you can focus on the storage and retrieval logic. Check the quickstart to get a key and start sending requests in minutes, and see pricing for plan details including the free trial.

Questions

Does Claude have built-in long-term memory across sessions? No. The API is stateless — every request only sees what you include in that request's context. Persistent memory has to be built externally with your own storage and retrieval logic.

What's the best database for agent memory? For small-to-medium scale, Postgres with the pgvector extension handles both structured facts and semantic search in one place. At larger scale, a dedicated vector database like Pinecone or Qdrant is worth the added complexity.

How much memory should I inject into each prompt? Keep it small — typically 5 to 15 relevant memories per request. Retrieval should be targeted to the current query via embedding similarity, not a full dump of everything you've ever stored.

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 →