Claude API Agent Memory Persistence Patterns
What "memory persistence" means for a Claude agent
Claude's API is stateless: every request you send is evaluated independently, with no awareness of anything outside the messages array you provide. For a chatbot, that's usually solved by replaying recent turns. For an agent — something that runs tasks over hours, days, or across restarts — stateless requests aren't enough. You need a pattern for storing what the agent has learned or done, deciding what's relevant to a new task, and feeding that back into the prompt without blowing past context limits or token budgets.
This article covers the architecture patterns that work in production: what to store, where to store it, how to retrieve it, and how to keep costs predictable. If you're looking for basic multi-turn chat history handling, that's a different problem — this is specifically about agents that need to remember across sessions and tasks.
The three layers of agent memory
Most durable agent memory systems split into three layers, each with a different retention strategy.
1. Working memory (current task state)
This is the active context for the task in progress — the last N messages, tool results, and any scratchpad notes the agent wrote itself. It lives in your request's messages array and disappears once the task completes or the context window fills up. No persistence needed here beyond the duration of the run.
2. Episodic memory (task history)
A record of completed tasks: what the agent was asked to do, what it did, and the outcome. This is what lets an agent say "last time you asked me to deploy this service, I used config X" in a later session. Store it as structured records, not raw transcripts:
{
"task_id": "task_8841",
"summary": "Deployed staging API, rolled back due to failed health check, fixed by increasing timeout to 30s.",
"entities": ["staging-api", "health-check", "timeout-config"],
"outcome": "success_after_retry",
"timestamp": "2025-01-14T09:32:00Z"
}
Summarize before storing. Don't persist full transcripts as your primary memory store — they're expensive to re-inject and most of the content is irrelevant to future tasks.
3. Semantic memory (facts and preferences)
Durable facts that don't belong to a single task: user preferences, project conventions, domain knowledge the agent has accumulated. This layer changes slowly and is usually the smallest but highest-value set of data. It's the one most worth getting right, because it's what gets injected into nearly every system prompt.
The core pattern: summarize, store, retrieve, inject
Regardless of your storage backend, the loop looks the same:
- During the task, let the agent run with normal working memory.
- At task end, ask Claude to produce a compact summary of what happened — a dedicated summarization call, not a side effect of the main task.
- Store the summary in a database, keyed by task, user, or project.
- At the start of the next task, retrieve relevant entries and inject them into the system prompt before the new conversation begins.
A summarization call is cheap and worth the extra request:
const summary = 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,
system: "Summarize this task transcript into 2-4 sentences covering what was requested, what was done, and the outcome. Omit pleasantries.",
messages: [{ role: "user", content: fullTranscript }]
})
});
Store the result with metadata (task ID, entities touched, timestamp) rather than as a blob of text, so you can filter and rank later.
Retrieval: don't inject everything
The mistake teams make is dumping the entire memory store into the system prompt on every request. That works for a handful of entries and falls apart past a few dozen. Two retrieval strategies scale better:
Recency + relevance filtering. Keep the last 5–10 episodic entries plus any semantic facts tagged to the current project or user. This is simple to implement with a plain SQL query and no vector infrastructure.
SELECT summary FROM agent_memory
WHERE project_id = $1
ORDER BY timestamp DESC
LIMIT 8;
Embedding-based recall. When the memory store grows into the hundreds or thousands of entries, embed each summary and the current task description, then retrieve the top-k most similar entries. This is the same retrieval pattern used in RAG systems, applied to the agent's own history instead of external documents.
Either way, the injected memory should be a short, curated block — a few hundred tokens, not a transcript dump:
## Relevant history
- 2025-01-10: User prefers staged rollouts over direct-to-prod deploys.
- 2025-01-14: Health check timeout for staging-api should stay at 30s or higher.
Handling memory conflicts and decay
Memory that's never pruned becomes noise. Two practical rules:
- Newer facts override older ones. If the agent learns a preference changed, update the record instead of appending a contradiction. Tag entries with a
superseded_byreference if you need an audit trail. - Decay low-value entries. Task summaries that were never retrieved after 90 days are candidates for archiving or deletion. Keep semantic facts indefinitely; episodic entries can be pruned more aggressively.
Where SubToAPI fits
If you're running this pattern against Claude, you still need the basic plumbing: an API key, request/response handling, and ideally some visibility into token usage per agent run, since summarization and retrieval calls add up across many sessions. SubToAPI wraps Claude access behind an HTTPS API with application keys (sub_live_...), streaming, and usage metadata per key, so you can see exactly what your memory-summarization calls are costing separately from your main task calls. Set up a key for your agent in a few minutes at /signup, and check /docs/quickstart for the request format — it's the same Messages API shape as above, so there's no agent-side code to rewrite.
Questions
Does Claude have built-in memory across sessions? No. The API is stateless — every request only knows what's in the messages you send. Persistence has to be built on your side using a database or vector store, following patterns like the one above.
Should I store raw transcripts or summaries for agent memory? Summaries. Raw transcripts are expensive to re-inject and mostly irrelevant to future tasks. Summarize at the end of each task and store structured records instead.
When do I need embeddings instead of simple recency filtering? Once your memory store grows past a few dozen entries per user or project. Below that, sorting by recency and filtering by project ID is simpler and good enough.