Long-Term Memory for Agents
The persistence problem
Agent memory has two timescales:
Session memory (seconds to minutes): conversation context, intermediate states. Fine if lost.
Long-term memory (hours to years): user preferences, learned behavior, decisions. Must survive restarts, crashes, and agent updates.
Most teams conflate them and use the same storage. This is a mistake.
Storage tiers
Tier 1: Session (in-memory, non-durable)
Use for: Conversation context, intermediate reasoning, temporary state.
const sessionMemory = new Map<string, Memory>();
// Brain has no in-process / on-device mode — every client speaks the wire protocol to a
// running server. For ephemeral scoping, tag writes and reads with a session id instead:
// new RecallBuilder(query).session(sessionId).maxResults(10).build()Durability: None. Lost on restart. Latency: < 1ms. Cost: Free (RAM). Cardinality: 100–1K facts per session.
Tier 2: Mid-term (local persistent, single-node)
Use for: Recent decisions, conversation summaries, learned preferences (days).
import { BrainClient } from "@brain-db/sdk";
const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
// Self-hosted node, durable to disk (arena + WAL + redb). Retention is server-side (decay +
// consolidation workers, tombstone grace) — there is no client-side ttl knob.
const midTermMemory = await BrainClient.connect("127.0.0.1", 9090, { auth });Durability: Survives restart (disk-backed). Lost if disk fails. Latency: 5–50ms (local disk I/O). Cost: Disk space (~1MB per 100K facts). Cardinality: 1K–100K facts.
Tier 3: Long-term (managed persistent, replicated)
Use for: User profiles, historical facts, policies (months/years).
import { BrainClient } from "@brain-db/sdk";
const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
// Production Brain node; the brain_ token carries identity (namespace + space). Replication and
// region are server deployment/ops concerns, not client config.
const longTermMemory = await BrainClient.connect(process.env.BRAIN_HOST!, 9090, { auth });Durability: Survives any single failure (replicated, backed up). SLA-guaranteed. Latency: 50–200ms P99 (network + DB). Cost: $0.001 per 1K vectors/month (managed). Cardinality: 100K–10M facts per user.
Multi-tier architecture
Most production agents use all three:
import { BrainClient, EncodeBuilder, RecallBuilder } from "@brain-db/sdk";
const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
// One connection per durability tier — the tier is *which server* you point at, not a
// client config flag. Session scoping within a tier uses a session id on the builder.
const midTerm = await BrainClient.connect("127.0.0.1", 9090, { auth }); // durable local node
const longTerm = await BrainClient.connect(process.env.BRAIN_HOST!, 9090, { auth }); // production node
const sessionId = 42n; // ephemeral scope, carried on the builder
// On each turn:
async function agentLoop(input: string) {
// Read from all tiers
const sessionContext = await midTerm.recall(new RecallBuilder(input).session(sessionId).maxResults(5).build());
const recentDecisions = await midTerm.recall(new RecallBuilder(input).maxResults(5).build());
const userProfile = await longTerm.recall(new RecallBuilder(input).maxResults(5).build());
// Combine
const fullContext = [sessionContext, recentDecisions, userProfile];
// Decide and store
const decision = await llm.complete(fullContext);
// Write to the appropriate tiers (memory type is inferred by the server's extractor)
await midTerm.encode(new EncodeBuilder(decision).session(sessionId).build());
if (important) {
await midTerm.encode(new EncodeBuilder(decision).build());
await longTerm.encode(new EncodeBuilder(decision).build());
}
}Eviction policies
Memory grows. You need a policy for what to forget.
LRU (Least Recently Used)
Forget what you haven't accessed in N days.
Best for: User-scoped memory (chat history, preferences). Tradeoff: Might forget important but rarely-accessed facts.
{
eviction_policy: "lru",
window_days: 30,
// Keep facts accessed in last 30 days
}TTL (Time To Live)
Forget specific memories after a fixed time.
Best for: Transient facts (conversation state, temporary preferences). Tradeoff: No automatic cleanup for long-lived memories.
{
type: "conversation_turn",
ttl: new Date(Date.now() + 24 * 60 * 60 * 1000), // 1 day
}Priority-based
Forget low-confidence or low-impact memories first.
Best for: Mixed-importance memory (facts + events + preferences). Tradeoff: Requires predicting what's important.
{
eviction_order: "confidence_desc", // Forget low-confidence first
// or
eviction_order: "type", // Forget events before facts
}Merge + compress
Instead of evicting, compress old memories.
Best for: Long conversations (summarize past turns). Tradeoff: Lossy; summary might miss nuance.
// After a week, summarize old conversation turns into one memory
const oldTurns = await client.recall(
new RecallBuilder("conversation turns older than a week").maxResults(100).build(),
);
const summary = await llm.summarize(oldTurns.memories.map((hit) => hit.text));
await client.encode(new EncodeBuilder(summary).build());
// Brain has no bulk delete-by-filter. The server's decay + consolidation workers age raw
// turns out on their own; to remove a specific memory immediately, forget it by id:
// await client.forget(new ForgetBuilder(memoryId).build());Durability guarantees
Write-ahead logging (WAL)
Every write is logged before it's applied. Survives crashes.
How: Write to log, then to memory. On restart, replay log.
Agent: "Remember: user is in SF"
→ Write to WAL: {memory_id: 123, content: "user in SF"}
→ Confirm write
→ Apply to memory store
→ Delete from WALWhat Brain does: the self-hosted Brain server uses a group-commit WAL with fsync-before-acknowledge (arena + WAL + redb).
Replication
Every write is replicated to N replicas before confirming.
How: Write to primary, replicate to 2+ secondaries, confirm when N replicas ack.
Agent: "Remember: user is in SF"
→ Write to primary
→ Replicate to secondary-1 (ack)
→ Replicate to secondary-2 (ack)
→ Confirm to agent
→ If primary fails, secondaries elect new primaryBrain Cloud: 3-way replication within region, async replication across regions.
Backups
Regular snapshots of memory state, kept for disaster recovery.
Frequency: Hourly for active agents, daily for inactive. Retention: 30 days minimum (longer for compliance).
Brain Cloud: Automatic daily backups, configurable retention.
Retrieval patterns for long-term memory
Pattern 1: User profile (first-access warm-up)
On agent startup, load the user's profile facts (most important facts about them).
async function loadUserProfile(userId: string) {
const profile = await longTermMemory.recall(
new RecallBuilder(`profile facts about user ${userId}`).maxResults(20).build(),
);
return profile.memories; // cache in your app if you need a fast repeat lookup
}Pattern 2: Decision history (context for reasoning)
Before deciding, retrieve past decisions on similar topics.
async function getDecisionHistory(topic: string, userId: string) {
const history = await midTermMemory.recall(
new RecallBuilder(`what did we decide about ${topic} for user ${userId}?`).maxResults(5).build(),
);
return history.memories;
}Pattern 3: Temporal context (recent events first)
Get recent events, then fall back to older facts.
async function getFullContext(userId: string, query: string) {
// Recent — recency is folded into the fusion ranker, so ask for it in the query
const recent = await midTermMemory.recall(
new RecallBuilder(`${query} (user ${userId}, recent)`).maxResults(10).build(),
);
// Historical fallback if recent is sparse
if (recent.memories.length < 5) {
const historical = await longTermMemory.recall(
new RecallBuilder(`${query} (user ${userId})`).maxResults(10 - recent.memories.length).build(),
);
return [...recent.memories, ...historical.memories];
}
return recent.memories;
}Pattern 4: Graph traversal (relationships)
For entity-based memory, traverse relationships.
async function getCompanyContext(companyName: string) {
// Find the company entity
const company = await longTermMemory.recall(
new RecallBuilder(`${companyName} company`).maxResults(1).build(),
);
if (company.memories.length === 0) return null;
// Employees — the graph retriever walks the works_at relations server-side and fuses
// the neighbors into the result; there is no client-side relation traversal to write.
const employees = await longTermMemory.recall(
new RecallBuilder(`employees who work at ${companyName}`).maxResults(20).build(),
);
return { company: company.memories, employees: employees.memories };
}Cost optimization
Long-term memory can get expensive. Optimize:
1. Compression
Summarize old memories. Trade precision for cost.
// Daily: compress events from the past week into one summary
const oldEvents = await client.recall(
new RecallBuilder("events older than a week").maxResults(100).build(),
);
const compressed = await llm.compress(oldEvents.memories.map((hit) => hit.text));
await client.encode(new EncodeBuilder(compressed).build()); // 1 memory instead of 1002. Sampling
Keep every Nth memory, not all.
// Keep 1 in 10 conversation turns
const sampling_rate = 0.1;
if (Math.random() < sampling_rate) {
await longTermMemory.encode(new EncodeBuilder(turn).build());
}3. Selective indexing
Don't index low-value fields.
// Index only high-cardinality, frequently-queried fields
{
index: ["user_id", "type", "timestamp"],
store_only: ["content", "metadata"],
}4. Tiering by value
Cold data goes to cheaper storage.
// Recent (7 days): fast, expensive
// Archive (> 7 days): slow, cheap
if (timestamp.getTime() < Date.now() - 7 * 24 * 60 * 60 * 1000) {
await archiveStorage.store(memory); // S3, cheaper
} else {
await hotStorage.store(memory); // SSD, faster
}Checklist: Before shipping long-term memory
- You have a multi-tier strategy (session/mid-term/long-term)
- Durability is guaranteed (replication or backup)
- Eviction policy is defined and tested
- You can reconstruct recent context from logs if needed
- Cost is predictable and monitored
- Retrieval latency is acceptable (< 200ms P99 for long-term)
- You have a backup restoration plan
- Data is encrypted at rest and in transit
Further reading
- Memory Architectures — System design
- Schema Design Patterns — Durable schemas
- Cheat Sheet — Deployment patterns