
Large language model inference is stateless: every token the model can use must be placed into its context window on every call. Agents that plan multi-step work, edit codebases, or serve users across sessions therefore need an engineered memory layer, and its shape determines both cost and reliability. This article maps the spectrum of memory organization used in agent systems, from the in-session scratchpad through persistent, namespaced stores to hierarchical tiers, knowledge graphs, and entity-aware consolidation. Coverage includes when each tier pays off, how memories are written, distilled, and forgotten, and how graph retrieval applies to structured domains such as code. The target reader is a developer designing the context and storage layer of a coding or task agent. Multi-agent topology and control-loop design are out of scope and treated in companion pieces.

LLM inference is stateless: the model can only reason over the tokens that appear in its context window at the moment of a call — there is no hidden internal recall Five Agent Memory Types in LangGraph. Consequently, every form of “memory” that an agent exhibits is an external engineering artifact that must be pulled into that window before the model can use it.
| Tier | Typical implementation | What lives here | Typical cost / latency |
|---|---|---|---|
| 1. In‑context working memory | Prompt + conversation history + tool outputs | Immediate reasoning state, scratch‑pad, recent turns | Highest token‑price, limited by window size (e.g., 128 K tokens for GPT‑4o, 200 K for Claude 3.5) In‑context memory costs |
| 2. Session‑scoped buffer | In‑memory list or short‑lived datastore (e.g., Redis) | Full session transcript, temporary caches that survive a single user session | Low latency, volatile, cleared after session |
| 3. Cross‑session key‑value / document store | Relational DB, NoSQL, simple JSON store | Persistent user preferences, configuration flags, small docs | Cheap storage, moderate read latency; retrieval must be staged into tier 1 |
| 4. Semantic vector store | FAISS, Pinecone, Qdrant | High‑dimensional embeddings for similarity search (facts, code snippets) | Moderate cost (embedding compute) but cheap long‑term; enables “semantic recall” |
| 5. Knowledge‑graph memory | Neo4j, JanusGraph, RDF stores | Structured relationships, provenance, dependency graphs (e.g., code module graphs) | Higher setup cost, but enables graph‑traversal retrieval for complex domains |
The design goal is to keep the volatile, high‑cost context (tier 1) filled only with information that is needed right now, while moving everything else to durable, cheap layers (tiers 2‑5) that can be fetched later as needed. This mirrors classic memory hierarchies in operating systems Hierarchical Context Management.
The CoALA framework maps these engineering tiers onto human‑memory categories LangChain memory for agents — Episodic, Semantic, and Procedural memory.
When building a coding or task agent, the central question throughout the article is “Which tier holds this fact, and who is allowed to write it?”
Because context‑window sizes differ across providers and model generations, treat the numbers as illustrative rather than absolute. The key takeaway is the trade‑off: keep the window lean, push everything else into the appropriate durable tier, and use a clear write‑policy to maintain consistency across the memory hierarchy.

The session scratchpad is the working memory that lives directly inside the LLM’s context window. Because every token must be present on each inference call, the window becomes an attention budget that quickly turns into a bottleneck when it is over‑filled. Anthropic’s engineering team describes this as “curating the attention budget” – an over‑stuffed context degrades reasoning and forces the model to attend to irrelevant noise [Anthropic, Effective Context Engineering].
When the token count approaches the window limit, the safest mitigation is compaction: summarize the conversation, discard redundant material, and restart with the summary plus the newest turns. This preserves high‑level intent (decisions, constraints, file paths, open questions) while discarding verbose tool output that has already been incorporated into the agent’s state [Datahub, Context Window Optimization].
| Technique | What it does | Typical trade‑offs |
|---|---|---|
| Tool‑result clearing | Strips raw tool outputs from deep history, leaving only the fact that a tool was called. | Minimal token saving; safest because no information is lost beyond what the agent already recorded. |
| Reversible offloading | Stores the full tool result in an external store; the context keeps only a short preview and a pointer. | Allows later recall without re‑sending large payloads; adds indirection latency and requires a reliable store. |
| Token‑threshold summarization | Watches token usage; once a configurable fraction (e.g., 80 % of the window) is reached, an LLM summarizer rewrites older turns into a concise gist. | Easy to wire, but the summary can vary run‑to‑run; recall may suffer if the prompt does not explicitly request the right details. |
| Sliding window | Keeps the last N turns (or last M tokens) and drops everything older, with no summarization. | Guarantees a bound token count and constant latency; permanently loses any context that spans more than N turns. |
compact_20260112 block that fires automatically when the remaining budget falls below 20 % [Claude, API Compaction Spec].By treating the scratchpad as a curated, mutable ledger rather than a raw dump of every interaction, developers can keep inference costs predictable while preserving the critical knowledge that lets an agent continue a multi‑step task reliably.

Thread‑scoped short‑term memory – In LangGraph each execution belongs to a thread identified by a thread_id. The graph’s state (messages, variables, interim results) is serialized on every step and written by a checkpointer to a backend chosen for the deployment tier. Development and unit‑tests typically use an InMemorySaver because it requires no external service and resets cleanly between runs, but it must never be deployed to production where any restart would lose state【0†https://activewizards.com/blog/langgraph-state-management-checkpointing-recovery-and-the-persistence-layer-decision/】. Production workloads switch to a durable saver—SqliteSaver for single‑process or low‑traffic services, and PostgresSaver (often with a connection‑pooler such as pgbouncer) for multi‑process or high‑throughput agents【0†https://reference.langchain.com/python/langgraph/checkpoints】. Because the checkpointer stores data under the explicit thread_id, a crashed process can be resumed exactly where it stopped simply by invoking the graph with the same identifier【0†https://www.kunalganglani.com/blog/ai-agent-memory-state-management】.
Namespace‑based long‑term memory – Long‑term memory lives outside the checkpointer in a separate JSON document store. Documents are arranged in a two‑level hierarchy that mirrors a file system: a namespace (analogous to a folder) groups related keys (the file names). Typical namespaces are scoped by a user ID, organization ID, or project ID, allowing a single deployment to isolate data for many tenants. Search across namespaces is supported by content filters that respect these boundaries, so a query for “authentication flow” can be limited to the current repository while still allowing global lookup of shared utilities.
IDE‑agent scoping pattern – Modern coding assistants adopt the same three‑tier instinct. VS Code agents keep:
/memories/) whose first ~200 lines are auto‑loaded into every session, preserving personal preferences across all workspaces【1†https://code.visualstudio.com/docs/agents/concepts/agents】./memories/repo/) that survives across conversations for the same codebase./memories/session/) cleared when the conversation ends.These boundaries make the blast radius of a fact explicit: a preference saved in user memory is visible to every project, while a bug fix stored in session memory disappears with the chat.
Design take‑aways
By separating checkpointed thread state from a hierarchical, namespace‑aware long‑term store, agents can resume after failures, enforce clear retention policies, and limit the impact of stray writes—crucial properties for reliable, cost‑effective coding assistants.

Most coding agents rely on a simple, file‑system store for long‑term knowledge. The pattern splits along two independent dimensions: who writes the files and where the files reside.
Human‑authored instruction files are typically committed to a repository and loaded at every session start. Because they are version‑controlled, teams can diff, review, and roll back changes, guaranteeing deterministic guidance for the model. These files encode project overviews, build scripts, coding conventions, or a CLAUDE.md‑style manifest that the agent reads before any tool use. Their static nature means developers must manually keep them in sync with reality, but the payoff is high reliability and auditability.
Model‑written auto memory captures facts discovered at run‑time: successful build commands, debugging work‑arounds, or user‑provided corrections. In Claude’s “memory tool” the model can view, create, insert, delete, rename files inside a designated memory directory, and an auto‑injected system prompt forces a check‑memory‑first discipline—each new request begins with a lookup of relevant entries before proceeding. The tool identifier is version‑sensitive (memory_20250818) and must be cited as of that release Claude cookbook.
Benchmark‑only agents usually forgo any cross‑session storage; each run starts fresh and the only output is the generated artifact. Interactive CLI agents, by contrast, fall anywhere on the spectrum: from static, human‑maintained config files to fully LLM‑editable rule directories that evolve as the agent learns.
Treating authorship (human vs model) as orthogonal to location (disk file) clarifies design choices. Human‑written files stay immutable during a session, providing a stable scaffold, while model‑written files remain mutable, enabling dynamic adaptation. Because both reside as plain text, they are diffable, searchable with standard tools, and can be backed by a VCS, preserving audit trails without introducing the complexity of vector databases or external services. This lightweight tier often suffices for coding agents that need persistent semantic memory without incurring high latency or cost.

MemGPT treats an LLM’s limited context window as main memory and augments it with an external context that functions like a disk‑backed store. The architecture mirrors operating‑system virtual memory: data is paged in and out by the agent itself through function calls, rather than by a fixed runtime component.
Main context (in‑memory tier)
External context (secondary tier)
Because the LLM knows which facts are presently relevant, it issues function calls such as working_context.append(), load_from_archive(), or search_recall() to move data between tiers. This self‑directed paging lets the model decide what to keep in the costly context window and what can be deferred to disk, effectively extending the usable context without exceeding the model’s token limit【1†https://www.alphaxiv.org/abs/2310.08560】.
| Tier | Access cost | Typical latency | Ideal payload |
|---|---|---|---|
| Main context | High (token‑priced) | Immediate (in‑prompt) | Hot facts, current plan, short‑term scratchpad |
| Recall storage | Moderate (vector search) | Milliseconds‑to‑seconds | Recent messages, code diffs, snippets |
| Archival storage | Low (batch retrieval) | Seconds‑to‑minutes | Full documents, historic logs, large codebases |
When the agent successfully pages out irrelevant items, reported token‑savings can exceed 85 % of naïve full‑context approaches【5†https://pub.towardsai.net/how-to-design-efficient-memory-architectures-for-agentic-ai-systems-81ed456bb74f】. These numbers are workload‑dependent; savings vanish for queries that already fit within the raw context window.
Many production agents adopt a similar hierarchy. For example, Mem0 separates conversation memory (single turn), session memory (minutes‑to‑hours), and user/organization memory (persistent semantic store). Facts are promoted between tiers only after an editorial decision that deduplicates and summarizes the content, mirroring the hippocampal‑to‑cortical consolidation model in human cognition【6†https://mem0.ai/blog/memory-eviction-and-forgetting-in-ai-agents】. Coding assistants often keep a lightweight always‑loaded index of symbols while loading full source files on demand, treating the retrieved snippet as part of the prompt and re‑validating it against the actual filesystem before execution【1†https://www.alphaxiv.org/abs/2310.08560】.
In practice, virtual context paging lets developers design agents that scale to complex, multi‑step tasks (e.g., code refactoring across dozens of files) while keeping inference costs predictable. The key is to expose clear function‑call primitives for loading, updating, and evicting pages, allowing the LLM to act as its own memory manager.

1. Raw ingestion – Every interaction (turn, tool call, outcome) is appended to an episodic buffer that never overwrites. Each entry is enriched with immutable metadata (timestamp, session ID, tool name, token count) so that later processors can reason about provenance and freshness.
2. Immediate processing (hot‑path) – A lightweight memory processor runs in parallel with the agent and performs three best‑effort actions:
utils.py was edited”).The processor is non‑blocking: if extraction or pattern detection fails, the raw episode remains saved and the agent continues operating.
3. Consolidation mechanics (background / “sleep‑time” compute)
| Mechanism | Trigger condition | Effect |
|---|---|---|
| Merge‑first update | Similarity > δ with an existing episode (nearest‑neighbor) | The new unit is folded into the matching episode, keeping a single coherent narrative and avoiding parallel, fragmented stories on the same topic【2†source】 |
| Recurrence‑based abstraction | ≥ γ similar units retrieved from the subconscious store (cosine similarity ranking) | Only when a cluster shows sustained recurrence does an LLM generate a higher‑level summary, promoting the cluster to episodic / semantic memory【1†source】 |
| Semantic refinement | After abstraction, the system re‑examines the raw texts of the cluster | Critical entities omitted by the summary are recovered, redundant facts are filtered, and evolving user state (e.g., changed preferences) is updated. Each refined fact is stored as an independent entry to preserve retrieval specificity【5†source】 |
4. Timing and workload separation – Hot‑path writes execute in‑process, typically within a few milliseconds. Consolidation runs on a configurable cron schedule that matches the observed interaction cadence (e.g., every few minutes for chatty assistants, hourly for batch‑oriented agents). This decoupling limits latency while still keeping long‑term memory up‑to‑date.
5. Maintenance and failure handling
By guaranteeing that raw experience is never lost, while letting expensive LLM‑driven abstraction run asynchronously and only on truly recurring patterns, the write path delivers both high‑quality, entity‑aware memories and predictable operational costs.

When a domain exhibits rich relational structure—software repositories, compliance document collections, or investigative dossiers—plain vector similarity often returns passages that only look similar to the query. The missing piece is the explicit connectivity between the entities mentioned in the query. Graph‑augmented retrieval addresses this gap by grounding the search in an entity graph whose edges encode real relationships (e.g., function‑calls, policy references, or investigative links).
Typical GraphRAG pipeline (Microsoft’s implementation) follows five stages:
(subject, predicate, object) triples [source].Research in the recent agent‑memory survey highlights two orthogonal optimisation streams:
| Goal | Approach | Typical trade‑off |
|---|---|---|
| Accuracy | Dual local/global retrievers, sub‑graph scoring functions that rank candidate hops by semantic relevance. | Higher latency and larger index because every edge may be inspected. |
| Efficiency | Divide‑and‑conquer sub‑graph selection, aggressive path pruning, cache‑aware hop limits. | Faster responses but possible loss of peripheral facts needed for multi‑hop reasoning. |
For source‑code corpora, graph construction can be driven by static analysis rather than LLM extraction. Tools such as graphify parse abstract syntax trees (ASTs) with Tree‑sitter, extract symbols, import relationships, and call graphs, then compute centrality scores to rank the most influential nodes [source]. This “scaffold” graph gives the agent a domain‑specific notion of relevance that pure keyword search lacks. By contrast, the “LLM‑as‑navigator” approach treats the codebase as an unstructured text blob and relies on generic search tools, which often miss structural dependencies.
The downside is the upfront cost of extraction, graph building, community detection, and summary generation. Vendors report precision gains of up to 20 % on complex enterprise queries, but those numbers are highly workload‑specific [source]. For small, shallow corpora the overhead rarely justifies the benefit, and a plain vector index remains the simpler, cheaper choice.

Treat any retrieved memory as a prompt hint, not as ground truth. Before the agent acts, it must verify the hinted fact against the current external state (file system, API response, etc.). Naïve approaches—raw truncation, sliding windows, or offloading everything to retrieval—fail either by losing necessary context or by feeding hallucinated data into the model 【6†source】.
Following this staged, metric‑driven approach lets developers balance cost, reliability, and the semantic richness of an agent’s long‑term memory.