Blog
Designing AI agent memory to avoid production failures
AI agent memory fails more often at the write step than in storage. Learn how write gates, versioning, TTL, and strong consistency fix it. Read the guide.
Blog
AI agent memory fails more often at the write step than in storage. Learn how write gates, versioning, TTL, and strong consistency fix it. Read the guide.
Artificial intelligence (AI) agent memory fails in production more often because of what gets written and not cleaned up than because of where it's stored. Teams add a memory layer so an agent carries context across conversations, tasks, and workflows, and then find the agent is worse: It recalls junk, trusts stale facts, and mixes up projects. Storage matters, only for a specific set of problems, and doesn’t include problems that start when memories are written.
Agent memory is the layer outside the AI model that stores, retrieves, and updates information across calls and sessions. Most quality problems come from the write side of that layer: agents store too much, keep contradictory facts, and don’t forget.
A second set of problems is related to the store itself. If the memory store goes down or fails over, the agent loses all memory. The key questions are what happens when a node or rack fails, how long recovery takes, and whether in-progress writes are lost. Concurrent writes from multiple agents, tenant isolation, and stale copies of facts that have since changed are in the same group: they're reliability and data-correctness problems that databases have handled for decades.
Agent memory also mixes two kinds of data:
Knowledge accumulated over time: What happened, what the agent learned about a user, what it decided. This is a memory-management problem.
Operational state, the authoritative state of the business right now: An account's current status, whether another agent already acted, who owns a task. This is the problem Operational AI deals with: When an agent acts inside live business operations, it has to read authoritative state when it acts, and that state is usually stored in an operational database.
Extraction is the step where a large language model (LLM) determines which parts of a conversation to save as memories. If a memory problem would still happen with perfect extraction, it's a data problem, and the choice of store matters. If it wouldn't, fix the pipeline first.
AI agent memory is the system that lets an agent store, retrieve, and update information across AI model calls, sessions, and tasks. LLMs keep nothing between requests, so anything an agent should remember has to be stored outside the model, in a memory layer the application controls. That layer lets an agent recall what a user said earlier in a conversation, pick up a task after an interruption, and pass what one workflow step learned to the next.
Short-term memory holds what the agent needs for the current task or conversation. It usually includes recent conversation history, the current goal, and intermediate results from tools. Most agent frameworks keep this as state scoped to one conversation (LangGraph calls each conversation a thread) and persist it through checkpoints, so the conversation can resume after a crash. Working memory is narrower: the agent's active workspace for one decision, which in practice is mostly what is stored in the context window for the current model call.
Long-term memory persists across sessions. It holds user preferences, facts learned in earlier interactions, and records of past work, and it's scoped to a user, team, or application rather than to one conversation. Long-term memory is where most quality problems show up, because it accumulates.
In addition to working memory, there are three long-term types borrowed from research on human memory[1].
Memory type | What it holds | Agent example |
|---|---|---|
Episodic memory | Specific past events, in order, with their outcomes | A failed deploy last Tuesday and what fixed it |
Semantic memory | Facts and knowledge detached from the event that produced them | The user works in fintech and prefers concise answers |
Procedural memory | Rules, skills, and workflows for how to do things | Run the test suite before proposing a merge |
Short-term and long-term describe how long information persists and who it's scoped to. Episodic, semantic, and procedural describe what kind of information it is. These are independent dimensions: an episodic record can last one session or several years, and that difference matters later when deciding what to expire and what to keep.
The context window is per-request working space, not persistence. Everything in it is gone after the call unless the application sends it again. Larger windows reduce how often you need to compact or summarize, and they don't carry anything across sessions on their own. Externalizing state into a memory layer or a database makes it survive.
Retrieval-augmented generation[2] (RAG) is a retrieval architecture for grounding a model's answer in external information, while agent memory is information the agent itself retains and reuses across interactions or tasks. The more useful distinction is who writes the data. A RAG corpus is usually maintained by people or pipelines outside the agent, while agent memory is written by the agent, which is why write quality matters so much. Both can be stored in the same place and use the same retrieval methods: vector similarity over embeddings, keyword search, key lookups, SQL queries, or graph traversal.
Workflow state records where a task is in its execution; memory records what was learned. A checkpoint that says step 3 of 5 completed is state. A note that the customer's account is on the enterprise tier is memory. Giving both the same retention policy is a common cause of bloat, because execution state is high-volume and short-lived while memory is supposed to last. Separate retention rules, such as a short per-record time-to-live (TTL) on checkpoints, fix that.
Here’s what happens in a typical turn:
The agent loads its short-term state and assembles the relevant context for the decision.
It retrieves memories and documents through vector search, keyword search, or key lookups.
It compacts or summarizes older conversation history so the prompt fits.
It calls the model and writes anything new back to memory.
Compaction deserves care because it decides what leaves the window: If it drops a detail that wasn’t written to long-term memory, that detail is gone. Treating compaction and memory creation as one design decision avoids that loss.
Memory makes agents worse when the write path stores too much without deleting anything. The agent then retrieves junk alongside useful facts, trusts wrong entries, and drags context from one project into another. These problems start at the write step, where the system determines what to save.
The clearest public evidence is a team's audit of one Mem0 deployment running an agent for 32 days[3]. Of 10,134 stored entries, 224 survived a full manual review, which means about 97.8% didn't, and 186 of the survivors had to be rewritten, leaving 38 clean enough to keep as they were. Over half the junk came from the system prompt being re-extracted as a "memory" on every session. One hallucinated entry, "User prefers Vim," was recalled, treated as new input, and re-extracted until it existed 808 times. Replacing the small extraction model with a stronger one barely changed the junk rate. In the authors' words, "The extraction prompt is the bottleneck, not the model."
That audit covers one team's deployment and was published as a GitHub issue, not a peer-reviewed study, so treat its numbers as an example rather than a population figure. But it’s a common problem.
Automatic extraction writes a memory every time something looks like a fact. Boilerplate, tool output, and configuration values all qualify. A store that grows without a quality check gets bigger with every session, and retrieval quality drops as the ratio of signal to junk falls.
When the memory system can't tell recalled context from fresh user input, anything it retrieves becomes a candidate for re-storage. One wrong entry then compounds. The usual fix is provenance tagging on each memory, so the write path can skip anything that came from its own retrieval.
One developer's analysis of 632 Hacker News comments on AI memory found that distraction was the most common complaint: the agent pulls in old, unrelated context[4] and mixes up projects. For a coding agent, that means advice from last month's repository showing up in this week's work.
Summaries are too vague to act on, while detailed entries run so long the model skips them. The same analysis found builders frustrated with both. The useful middle is usually a short, specific record with the identifiers kept intact.
A controlled study tested how adding and deleting memories affects agents across many tasks. It found that agents tend to repeat the behavior stored in similar past records, so mistakes stored as experience propagate into later tasks[5], and that regulating which experiences enter and stay in memory improved how well agents completed later tasks. Keeping everything was not the safe default. A memory system's value depends on what it doesn't store and what it removes as much as on what it retrieves.
A database addresses memory problems that would still occur with perfect extraction: availability through node and rack failures, writes lost or left in doubt during failover, stale copies of changed facts, contradictions that lose history, expiry, concurrent writes, and tenant isolation. It can't fix extraction quality, relevance judgment, or summary granularity, because those decisions are made in the pipeline before anything reaches storage.
The Mem0 audit is useful because it shows both parts:
The 808 duplicate entries and the re-extracted system prompt were pipeline failures; a different store would have held the same junk. The IP addresses and configuration values found in the vector store were a write-gate failure, too.
An in-memory store that loses everything on restart, or an agent that loses its session state when a database node fails over, is the other kind of problem: it would happen with flawless extraction.
Applied to a specific problem, the question becomes: would this still happen if every memory written were correct and relevant?
If yes, fix it in the storage layer.
If no, change what gets extracted, how it's deduplicated, and when it's written before writing to the database.
Sorting problems this way keeps a team from buying infrastructure to solve a prompt problem, and from tuning prompts to solve a race condition.
"Memory" bundles at least six workloads with different types of access, latency needs, and consistency needs. Treating them as one thing leads to one-tool answers, and that's how a vector store ends up holding session state and a key-value cache ends up holding facts that should have been versioned.
Workload | What it holds | Type of access | Latency need | Consistency need | Typical lifetime |
|---|---|---|---|---|---|
Session and working state | Conversation history, current goal, tool results, checkpoints | Read and write by session ID before every model call | Low at the 99.9th percentile, on the request path, often fanned out across sub-agents | Read-your-writes within the session, including across a failover | Minutes to days |
Long-term facts and preferences | User profile, learned preferences, decisions | Read by user or entity ID; updated when facts change | Low, often on the request path | Latest version wins, with history kept | Months to years |
Semantic recall | Embeddings of past interactions and documents | Similarity search over vectors | Retrieval is on the request path; writing embeddings can run in the background | Eventual is acceptable unless a new memory must be retrievable on the next turn | Varies by source |
Event history | What happened, in what order, with outcomes | Append, then range or time-ordered reads | Moderate | Ordered and durable | Days to months, then compacted |
Shared operational state | What another agent or system just changed: account status, inventory, task ownership | Read and write by key from many agents at once | Low at the tail, on the request path | Strong: linearizable reads for any read that determines an action | Live |
Transactional coordination | Claims, locks, counters, ownership of a task | Check-and-set or transactional update | Low | Strong; two writers must not overwrite each other | Live; claims carry an explicit expiry |
Long-term facts, semantic hold, and event history hold accumulated knowledge. Operational state and transactional coordination hold operational state, and they're where enterprise agents meet operational data. An agent that approves a refund needs the customer's current account status, and it needs to record that it took the action so a second agent doesn't approve it again. A retrieved memory saying the account was active last week is a copy, and it isn't evidence that the account is active now. The source is the authoritative state, the current record in the system of record, and that's what the agent should read before it acts. Neither the status check nor the action record should be in a semantic memory store built around similarity search.
An LLM-extracted summary loses identifiers. In one example from the Mem0 audit's discussion thread, a loyalty number, "LR-11560," became "has a loyalty number" after extraction. Facts that have exact values, such as IDs, amounts, tiers, dates, and status codes, should be in structured records keyed by entity, often as JSON documents, where a lookup returns the exact value. Embeddings are for finding items by meaning, not for data that must be exact.
Before choosing a store, determine which of the six workloads the agent has. It often requires more than one store.
Agent memory reads fan out, so the slowest read sets the pace of every step. One agent step can read session state, user facts, shared operational records, and task claims, often in parallel across sub-agents, and the step can't continue until the slowest of those reads returns. If each read has a 1% chance of landing in its slowest 1% (the 99th-percentile tail), a step that makes 20 reads hits that tail about 18% of the time (1 − 0.99^20 ≈ 0.18), so a delay that's rare for one read shows up in nearly one step in five.
To keep slow steps rarer, look further out, at the 99.9th percentile: the same 20-read step hits that tail about 2% of the time. A cache in front of the store doesn’t necessarily help, because state that determines an action has to be read current.
The effect compounds across steps. An agent that takes ten steps to finish a task, each with its own fan-out, sees tail latency on most runs. A model call shows this because the database reads are on the critical path before and after every call, and they multiply with the number of steps and sub-agents.
Agent memory goes stale the same way a cache does: a fact changes at the source after a copy was stored, and the copy doesn’t get invalidated. Most steps in a memory's life have an equivalent in data-correctness work that databases and caches already handle.
A memory's life runs through eight steps:
An agent observes something during an interaction.
It decides whether the observation is worth keeping.
It writes a memory.
The same agent or another one retrieves it later.
The underlying fact changes.
The stored memory is now stale.
The system updates, invalidates, or supersedes it.
The agent may need the history of that change, not just the current value.
Most of these steps map to a familiar primitive:
Lifecycle step | Data-correctness primitive | What it prevents |
|---|---|---|
Decide whether to keep (2) | Write gate | Junk and secrets entering the store |
Write (3) | Provenance, plus the source's version on the record | Re-extraction loops; stale writes landing after newer ones; losing track of where a fact came from |
Retrieve (4) | Read-your-writes for an agent's own writes; causal or linearizable reads for other agents' writes | An agent missing a fact it, or a collaborating agent, just wrote |
Fact changes (5, 6) | Invalidation tied to the source's version, with TTL as an upper limit | Serving an old value |
Supersede (7) | Versioned records with validity ranges | Deleting history, or keeping contradictions side by side |
Keep history (8) | Append-only event log | Losing the ability to explain why the agent believed something |
TTL limits how long a copy lives, but that doesn't make it current. Only invalidation when the source changes, or reading the source itself, does that. For operational facts, the more reliable memory is often a pointer instead of a copy: Store that the agent is tracking account 1234, and read the account's status from the system of record when the agent is about to act.
The classic cache race[6] shows how this fails in practice. A cache can end up storing outdated information when two operations happen in the wrong order. For example, it starts saving x=42, the database changes the value to x=43, and the cache receives a message to discard the old value. But if the original save finishes after that message arrives, it puts x=42 back in the cache. The same problem can occur with agent memory: an agent might save an old fact after a newer version has already been stored, overwriting the correct information.
This is where versioning comes in. A check-and-set on the memory record's own version counter tells you only whether another writer accessed the memory record. It can't tell you whether the value being written is older than what the source now holds, so it doesn't stop a stale fill. The fix is to store the source's version or timestamp with each fact and reject any write with a source version older than the one already stored, which is the same idea as comparing versions that originate in the database.
Coding agents show the same problem. A stored summary of a codebase goes stale as soon as someone else merges a pull request[7], which is why several coding agents search the code on demand rather than trusting embeddings made earlier. When the underlying information changes frequently, stored memories need an expiration date or version check, or the agent should retrieve the latest information each time.
Three steps that cause the most trouble: deciding what to write, handling facts that change, and forgetting.
A write gate rejects observations that aren't worth storing, and it helps memory quality the most. Extraction prompts usually have actions for adding, updating, and deleting memories. In the audited Mem0 deployment, the update prompt had no reject action, so the model's only choices were to store something or change something.
A write gate should turn away:
System prompts, instructions, and tool schemas, which are already available on every call
Anything that came from the agent's own retrieval, identified by a provenance tag, so recalled memories aren't re-stored as new facts
Secrets, credentials, IP addresses, and other configuration values
Observations that duplicate an existing record, checked by meaning and not only by exact hash
Low-value chatter that doesn't change what the agent should do next
Negative examples in the extraction prompt help as much as positive ones. Showing the model five things it should not store sets the threshold more clearly than a description does. Timing matters, too: writing during the turn gives immediate recall but adds latency and splits the model's attention, while writing in a background pass after the turn allows a stricter review at the cost of a short delay. Both are reasonable; the mistake is writing everything immediately with no review.
The audit's authors later tested this. They deployed four configuration changes together: negative examples in the extraction prompt, an update prompt that defaults to storing nothing, a tighter deduplication threshold, and a higher search threshold. In a 48-hour sample of 73 new entries, the junk share fell from 97.8% to 46.6%.
Supersede the old fact with a new version and keep both, with validity ranges, instead of deleting or duplicating. Deleting loses the history that explains the agent's earlier behavior. Keeping two facts side by side without a version or validity range makes retrieval ambiguous.
The standard example is a user who said they live in Seattle and later says they moved to Portland. This causes two problems: the newer fact wiping the older one, or both coexisting without saying which is current. Some memory layers now attach temporal metadata, so newer facts outrank older contradictory ones at retrieval.
A memory record that supersedes carries a few extra fields:
Field | Purpose |
|---|---|
valid_from | When the fact became true |
valid_to | When it stopped being true; empty for current facts |
supersedes | The ID of the record this one replaces |
source | Where the fact came from: user statement, tool result, inference |
confidence | How much the agent should trust it |
scope | The user, team, or task the fact belongs to |
With these fields, a retrieval for the current address returns Portland, a retrieval for "where did the user live in March" returns Seattle, and an audit shows when and why the belief changed. Ranking newer facts higher handles the first query; the other two need the validity ranges stored and queryable. The schema is a database design decision, and it works in a document store, a relational table, or a graph.
The schema needs two things from the storage layer: a cheap way to look up the current version by key, and an atomic way to change which version is current. Superseding a fact affects two records: the old one gets its valid_to set, and the new one gets written. A single-record check-and-set doesn't make that atomic, so either use a multi-record transaction, or keep the "current" pointer in one record and update only that record with check-and-set.
Forgetting works best when each memory type has its own decay rule, implemented as a TTL or an eviction policy in the store. That's typed decay: a preference might stay valid for months, a stated intent for weeks, and a transient event for days. Some memory layers now rank recently used memories higher and let idle ones fade from results. Ranking decay hides old memories from retrieval without removing them, so storage growth and deletion obligations remain.
A workable starting rule set:
Session and working state: Expire with the session, or within days, unless promoted to long-term memory
Stated intents and in-progress tasks: Expire in weeks, or when the task closes
Preferences and profile facts: No automatic expiry, but supersede on change and review when unused for months
Episodic records of events: Keep raw entries for a short window, then compact into summaries and keep the summaries
Shared operational state: Invalidate on change instead of expiring it silently, because another agent may depend on it
Leases and task claims: Give each one an explicit expiry so a crashed agent's claim gets released
Expiry and deletion are different operations and should stay separate.
Expiry removes a memory because it's probably no longer useful. TTL handles this.
Deletion removes it because a user or a policy requires it, which means it has to be complete and provable: it must reach replicas, cross-datacenter copies, and backups, and the delete itself must be durable, because in some databases a record removed by expiry or a non-durable delete reappears after a restart. It needs a delete scoped to a user, fact, or memory ID that the application can call on request, plus a plan for the copies in backups.
Shared memory across agents is a distributed-systems problem, and the failures are the same kind databases solved with isolation levels, check-and-set writes, and single-writer ownership. Multi-agent systems add a twist: the state being shared is natural language, and the frameworks that orchestrate the agents mostly don't define who is allowed to write what.
In a multi-agent system, reads and writes coexist against the same evolving state. Each agent reads facts that other agents just wrote, and its own writes become what the next agent reads before it acts.
Failures that show up in practice are familiar to anyone who has run a shared cache or a replicated store:
Lost updates. Two agents read the same memory, both modify it, and the second write erases the first.
Duplicate writes from retries. A retried webhook or a re-run turn stores the same fact twice.
Stale cross-agent reads. Agent B acts on a fact that Agent A just updated, because B's read came from a replica or a cached copy.
No read-after-write guarantee. An agent writes a memory, hands off, and the next agent can't see it yet.
These failures are easy to misdiagnose. A race condition between two agents produces an answer that's wrong in a plausible way, which looks like a hallucination[8], so the natural response is to tune prompts when the bug is in the data path.
In a study of more than 1,600 traces across seven frameworks, inter-agent misalignment accounts for roughly a third of observed failures[9]. That category is mostly about communication: agents that don't ask for clarification, drift off task, withhold information, or ignore each other's input. The study shows coordination is a large problem, but it doesn't measure how many failures come from inconsistent shared state, a coordination problem a data layer helps fix.
Agent frameworks give partial help. LangGraph, for example, lets a developer attach a reducer to each state key, which decides how concurrent updates to that key merge. A merge rule decides what happens when writes collide. It doesn't decide which agent is allowed to write, and it doesn't stop an agent from acting on a value that changed after it read it.
Database engineering already has names and tested techniques for these failures:
Technique | What it does for shared agent memory | When to use it |
|---|---|---|
Single-writer ownership per memory scope | Only one agent may write to a given scope; others read | Most pipelines, where roles are fixed (researcher writes findings, planner writes plans) |
Optimistic concurrency (check-and-set) | A write succeeds only if the record's version hasn't changed since it was read | Shared facts that several agents may update, with low contention |
Idempotency keys | A repeated write or action with the same key is a no-op | Retries, webhooks, re-run turns, and in-doubt writes after a timeout |
Fencing tokens | Every new claim gets a higher token, and writes carrying an older token are rejected | Leases and task claims, where a paused agent may act after its claim expired |
Read-your-writes and causal ordering | A reader sees the writes it depends on, in order | Handoffs between agents in a workflow |
Strong consistency with linearizable reads | Every agent reads the latest committed value | Account status, task ownership, anything that determines an irreversible action |
Conflict-free replicated data types | Concurrent edits merge without coordination | Append-only logs and counters; rarely for natural-language facts |
The right consistency level for a multi-agent system depends on what it’s doing. Eventual consistency is fine for a researcher agent's notes, but not for the record that says whether a refund was already issued. A production system usually needs both, in different stores or in a store that offers both modes, chosen per workload instead of per system.
Each technique covers a narrow case. A check-and-set write stops two agents from overwriting the same record, but two agents can still each call a payment API and issue the same refund. Preventing that takes an idempotency key on the external action, or a claim record each agent must acquire before acting.
Decide write ownership for every memory scope before the first agent runs, and put anything that determines an action behind a strongly consistent check-and-set write.
For a single-user coding agent, a markdown file or a SQLite database is often enough, needing a database only when there are multiple users, concurrent writers, real-time freshness needs, or more data than a file holds.
The file-first approach is popular with developers building coding agents. Coding agents read project-level instruction files at the start of each session, such as CLAUDE.md for Claude Code or the project rules files in Cursor, and developers maintain them by hand, sometimes alongside a MEMORY.md or a similar "memory bank." Here are the advantages:
The memory is readable and editable by the person who owns the project.
There's nothing to deploy, back up, or secure beyond the repository.
Staleness is visible, because the file is next to the code it describes.
A human curates what goes in.
The same properties become limits when the agent leaves one developer's machine:
Threshold | Why files don’t work | What you need instead |
|---|---|---|
More than one user | A shared file mixes everyone's preferences and facts together | Records scoped by user or tenant, with access control |
More than one writer at a time | Two agents or processes overwrite each other's edits | A store with locking or check-and-set writes |
Facts that change while the agent runs | The file is a snapshot; nothing invalidates it | A store the application updates and expires, or a live lookup |
Retrieval by meaning across many entries | Reading the whole file into context stops fitting | An index over embeddings, backed by a vector store |
Durability and recovery requirements | A lost or corrupted file is lost memory | Replicated, persisted storage |
Audit and compliance | No record of who changed what, or when | Versioned records with provenance |
One rule of thumb is to move to indexed search when the memory file approaches about 200 lines[10]. Past that size, the agent reads too much irrelevant text on every turn, and a retrieval step that returns only relevant memories costs less than loading the whole file.
Start with files for a single-user agent with a memory a human reads and edits, and move to a database when a second user, a second writer, or a freshness requirement arrives.
No database covers all six memory workloads well, so what matters is which store to use for each tier.
Session state needs low-latency reads and writes by key before every model call.
Long-term facts need durable, versioned records.
Semantic recall needs a vector index.
Shared operational state needs strong consistency under concurrent writes.
The table below maps store categories to those properties; the products named within each category are examples, listed alphabetically.
Store category | Example products | Best for | Latency | Durability and availability | Consistency and concurrency | TTL and expiry | Main limitation for agent memory |
|---|---|---|---|---|---|---|---|
Files and embedded databases | Markdown files, SQLite | Single-user agents; human-curated memory | Local disk; fast for one process | Local disk only; no replication | Single writer | Manual | Breaks at the second user or concurrent writer |
Operational key-value database | Session state, shared operational state, coordination records, versioned facts by key | Sub-millisecond point reads and writes in Aerospike's published benchmarks, including data sets larger than RAM | Synchronous replication across nodes and racks; persistent storage | Check-and-set writes; optional strong consistency with linearizable reads; multi-record transactions | Per-record TTL; restricted in strong-consistency namespaces | No vector search | |
Operational key-value database | Session state and key-value facts on AWS | Single-digit milliseconds, AWS's stated target | Managed; replicated across availability zones | Conditional writes; strongly consistent reads; transactions | Per-item TTL; deletion runs in the background, sometimes well after expiry | Tied to AWS; cost scales with request volume | |
In-memory data store | Session state, caching, and vector search | Sub-millisecond, with data held in RAM | Persistence through snapshots or an append-only file; asynchronous replication, so acknowledged writes can be lost on failover | WATCH for check-and-set; MULTI/EXEC transactions | Per-key TTL | Memory cost grows with data | |
MySQL, PostgreSQL | Long-term facts with rich queries; audit trails; vectors through extensions such as pgvector | Milliseconds, depending on indexing | Write-ahead log; synchronous or asynchronous replication | No native TTL; scheduled deletion | Vector search through extensions shares resources with transactional load | ||
Document databases | JSON profiles, preferences, and event history; integrated vector search on MongoDB Atlas | Milliseconds | Replica sets; durability set by write concern | Tunable read and write concerns; causally consistent sessions | TTL indexes | Stronger read and write concerns add latency | |
Dedicated vector stores | Semantic recall over embeddings | Milliseconds for approximate nearest-neighbor queries; index builds take longer | Varies by product | Varies by product; newly written vectors may not be searchable immediately | Varies; often by metadata filter | Embeddings don’t carry time or validity, and similarity doesn't establish correctness | |
Graph stores | Aerospike Graph, Neo4j, Zep (including its open-source Graphiti library) | Facts with relationships, including how they change over time | Milliseconds to seconds, depending on query depth; temporal graph building often runs in the background | Varies by product | Transactional within the graph engine | Validity ranges on edges in temporal designs | Extraction still depends on LLM judgment, so wrong or duplicate edges need uniqueness constraints and review |
A few caveats on the table. Latency figures come from each vendor's own statements and benchmarks, including Aerospike's benchmark against Redis, and any number that affects your decision should come from a test on your own data.
Several products span categories: Redis includes vector search, PostgreSQL adds it through pgvector, and MongoDB Atlas integrates it, which is why the mapping is by workload instead of by product. Consistency, durability, and transaction guarantees also vary between products in the same category, so check each product's documentation for a guarantee if your workload depends on it.
For an agent that needs memory, retrieval, and low-latency responses, these are the properties to check, in roughly the order they affect production:
Point-access latency at the 99.9th percentile, because one agent step fans out into many memory reads that must all return before the step continues, and the slowest one sets the pace. Check-and-set or transactional writes, so two agents or two retries can't both succeed on the same record
A choosable consistency mode, with strong consistency and linearizable reads for state that determine actions, and relaxed consistency where staleness is harmless
Per-record expiry (TTL), so typed decay is enforced by the store instead of by a cleanup job
Durability and availability through node and rack failures, including how long the store refuses writes during a failover and what happens to writes that were in flight; decide in advance what the agent does while the store is unavailable: fail open for low-stakes reads such as preferences, and fail closed for anything that determines an action
Enforced tenant isolation, usually key design plus access control scoped to sets, tables, or collections; key prefixes alone aren't isolation, and a separate namespace or database per tenant rarely scales
Secondary indexes or query by attribute, for lookups such as "all open tasks owned by agent X" that aren't one key; treat index results as candidates and confirm with a read by primary key before an irreversible action
Similarity search over embeddings, in the same store or a separate one, for semantic recall
Long-term memory and checkpoints are different[11], and if you don’t differentiate them, checkpoints get too big.
The checkpointer saves a thread's execution state so it can resume. It's keyed by conversation thread, written every step, and grows with every step. It isn't a message archive, and teams that use it as one report checkpoint tables bloating in PostgreSQL.
To prevent this, LangGraph ships PostgreSQL and SQLite checkpointers, and community packages add other backends, including an Aerospike checkpointer. Whatever backs it needs TTL or pruning, and because a checkpoint with a long history gets large, check it against the store's maximum record or row size before choosing.
The long-term store holds application-defined memories that outlive any thread. It's keyed by namespace, such as user and application, and it's where facts, preferences, and compacted history go. Durability and versioning matter more than raw speed here, and this is where a document database, a relational database, or an operational store with secondary indexes is most appropriate.
Teams that keep the two layers in different stores, with different retention rules, avoid most of the bloat and most of the confusion.
Every memory system pays for writes somewhere. Extraction usually means an LLM call per turn, which adds hundreds of milliseconds to seconds. Graph-based memory systems often build the graph in the background, and correct answers may appear hours later[12].
The time budget question to answer before choosing a store is whether memory writes are in the hot path or run in the background, and how much delay before a fact is queryable the use case tolerates. A customer-support agent that must remember what the user said two messages ago has a time budget of zero. A research agent that compacts its notes overnight has a time budget of hours.
Choose a low-latency operational key-value store for session state, shared operational state, and anything two agents might both try to update.
Choose a relational or document database for long-term facts that need rich queries, audit trails, and versioned history.
Choose a dedicated vector store, or vector capability in an existing store, for semantic recall over embeddings, but don't put exact-value facts there.
Choose a temporal graph store when the questions are about relationships and when facts were true, and the use case can tolerate background processing.
Choose self-hosted or embeddable options when you need data locality, privacy, or to avoid lock-in to one model provider.
The problems that appear after a prototype works are infrastructure problems: memory that vanishes on restart, a store that refuses writes while a node fails over, contention on hot records under concurrent writes, slow cold starts for large indexes, and tenant data that leaks across scopes. They rarely show up in a demo, because a demo has one user, one writer, a small dataset, and no node failures.
Each problem has a cause and a fix:
Problem | What causes it | What prevents it |
|---|---|---|
Memory lost on restart | Session state or memories held only in process memory or a non-persisted cache | Replicated, persisted storage for anything that must survive a restart |
Store unavailable during a node or rack failure | Slow failover, or too few replicas to keep data available | Replication across racks or zones, measured failover time, and an agent policy for the unavailable window |
Contention under concurrent writes | Many agents updating the same records or rows | Per-record atomic operations, write ownership per scope, and consistent lock ordering in the application |
Slow cold start | Loading large indexes before serving | Persistent indexes and warm replicas |
Checkpoint bloat | Using the per-step checkpointer as a long-term archive | TTL or pruning on checkpoints; a separate long-term store |
Cross-tenant leakage | Flat key spaces; retrieval without scope filters | Tenant in the key design, access control, and scope checks on every read |
Recovery after interruption deserves its own mention, because agents fail mid-task more often than conventional services do. A long-running agent that crashes between steps needs a durable checkpoint, and any task it had claimed needs to be released or reassigned.
Writes that time out are the hard case. In a strongly consistent store, a timed-out write can be in doubt: the client can't tell whether it was applied. That's when an agent retries, so every write that matters needs an idempotency key or a check-and-set condition, and the agent should re-read the record to resolve an in-doubt result before acting again. Aerospike, for example, flags in-doubt errors explicitly so the application can tell them apart from failed writes.
Run the prototype with ten concurrent users, restart it mid-task, and kill a database node mid-write to test this before production.
Memory poisoning[13] is an attack that plants false or malicious entries in an agent's long-term memory so they influence every later session, and it persists in a way a prompt injection doesn't. Research shows the attack can be cheap. Memory injection through ordinary queries alone, with no access to the agent's internals, has a 98.2% average injection success rate and a 76.8% attack success rate[14] under its experimental setup. (Those are results for the attack conditions the authors defined, not estimates of how often production agents get poisoned). A follow-up study found injection success fell to about 25%[15] when correct memories were already present, which suggests a well-populated, well-curated store resists poisoning better than an empty one. Detecting poisoned entries after the fact is still an open research problem, which is why the defenses below focus on controlling what can be written.
The defenses are almost the same as data-quality practice:
Provenance on every record. A memory should carry where it came from: a user statement, a tool result, a document, or the agent's own inference. Retrieval and review can then weight or exclude by source.
Write gates with rejection. The same gate that keeps out system prompts and secrets keeps out instructions disguised as facts.
Scoped write permissions. An agent that handles untrusted input shouldn't be able to write to a memory scope that other agents trust. Single-writer ownership per namespace limits the impact.
Versioning and rollback. If a poisoned entry is found, the store needs to show when it arrived and what it superseded, and the application needs to be able to revert.
Audit of what changed. An append-only log of memory writes, with the acting agent and the triggering input, is what makes an incident investigable.
Privacy leakage is a related risk. The Mem0 audit found IP addresses, chat IDs, and configuration values stored as memories, and research on memory extraction attacks shows that stored memories can be pulled back out through the agent[16]. A store that doesn’t have the secret is the only reliable defense, which again points at the write gate.
In a security review, the two most important questions are:
Does the memory store record provenance?
Can untrusted input reach any write path without review?
Published memory benchmarks are mostly vendor-run, their scores conflict[17], and they measure recall on conversation datasets rather than the staleness, conflict, and concurrency problems that break production systems, so you need your own tests.
Most benchmarks also don't measure whether a corrected fact propagates, how often a stale entry is retrieved, or what happens when two writers collide.
Run these against your store and pipeline, with synthetic users whose facts you control:
Staleness rate. Change a known fact at the source, then query the agent at intervals. Measure how long the old value appears and how often it appears after the correction.
Overwrite propagation. Update a fact through one agent or session and read it through another. Measure the delay before the second reader sees it, and whether it ever does.
Conflict-resolution accuracy. Feed contradictory facts in sequence. Check that the current value is the newer one and that the history is retrievable.
Duplicate rate under retries. Replay the same write, and the same turn, several times. Count the resulting records.
Junk ratio. Sample stored memories after a week of use and classify them. The Mem0 audit's method, counting entries that would change the agent's behavior, is a reasonable rubric.
Read and write latency at the 99.9th percentile. Measure both on the request path, under the concurrency and fan-out you expect, and separately measure how long a new fact takes to become retrievable.
Recovery after an agent restart. Kill the agent process mid-task and restart it. Check that session state, claimed tasks, and recent writes survive.
Database node failure. Kill a database node mid-write. Measure how long writes are refused or time out, how many come back in doubt, and whether any acknowledged write is lost.
Scope isolation. Query as one tenant for a fact stored by another. The correct result is nothing.
These tests produce numbers for your workload.
Check who ran it and whether the configuration, prompts, and dataset are published.
Look for a no-memory or full-context baseline. A memory system that doesn't beat it[18] isn't helping.
Note the dataset. Conversation-recall datasets say little about operational facts, identifiers, or multi-agent state.
Treat a single-deployment audit as an example of a problem rather than a measurement of how common it is.
Aerospike serves the operational state in an agent's loop: current facts an agent reads before it acts, the record of what it did, and coordination records that stop two agents from acting on the same item. Aerospike uses the term Operational AI for AI that acts inside live business operations, where every decision follows the same loop:
Read the authoritative state, the current record of the business.
Assemble the relevant context, including accumulated knowledge such as preferences and past interactions.
Decide.
Act.
Record the consequence.
Leave updated state, which becomes the starting point for the next cycle, whether the next actor is the same agent, another agent, or a person.
The loop breaks when an agent acts on a version that no longer exists. The model supplies the intelligence, and the application or agent holds the decision logic and takes the action. Aerospike holds the state those decisions depend on and records the consequences so the next decision can use them. Aerospike doesn't run the model, own the decision, or offer vector search, so semantic recall over embeddings needs a separate vector store.
In the six-workload model, that places Aerospike on session and working state, long-term facts read by key, shared operational state, and transactional coordination.
Here are more details on how Aerospike works with each of the workload types.
An agent reads its state before every model call and writes it after, so the store is on the request path, and each agent step fans out into many such reads. Aerospike is built for predictable sub-millisecond reads and writes by key at high throughput. Its patented Hybrid Memory Architecture keeps the primary index in memory and the records on flash, which matters for agent memory because memory accumulates: latency stays predictable as the data grows past RAM, without paying to hold all of it in RAM. Aerospike's benchmark against Redis measures this as data scales beyond memory. Per-record TTL lets ended sessions clean themselves up.
The superseding schema from the lifecycle section is suitable for a record per fact or per entity, read by primary key. Secondary indexes help an agent find candidates, such as all open tasks owned by one agent, but secondary-index queries in SC mode can return stale or uncommitted records. The safe sequence is to query the index for candidate keys, then read each record by primary key before anything irreversible happens.
An agent approving a refund needs the account's current status, and it needs to record that it acted so a second agent, possibly running seconds later, doesn't approve it again. Aerospike's strong-consistency (SC) mode, available in Aerospike Database Enterprise Edition and Aerospike Cloud, guarantees that acknowledged writes to a record are applied in order and aren't lost during network partitions, with a few documented exceptions, such as process pauses or clock skew between nodes beyond about 27 seconds.
Each read picks its own guarantee. The default, session consistency, means a client always sees its own latest writes, and with the common replication factor of 2, it performs about the same as Aerospike's availability mode, so SC isn't a latency penalty for most operations. A linearizable read returns the latest committed version written by any client and carries extra cost. When one agent must see what another agent just changed before it acts, that read should be linearizable.
The same requirement already runs at production scale without agents. PayPal evaluates fraud risk at every customer touchpoint, and a second evaluation that reads an account before the first evaluation's result is written can approve a transaction the updated risk profile would have flagged. PayPal uses Aerospike for inline, machine language-based risk scoring, and its fraud analysis completes in under 200 milliseconds end to end.
Agents add actors to those records. More enterprises encounter this requirement as they let agents act on their systems, and each one makes it worse: thousands of agents, each reading context, recording progress, and changing facts other agents need, put more concurrent reads and writes on shared records than human users ever did. The question to ask is how many actors have access to a record between one decision and the next, and whether each one sees the last consequence before it acts.
Every Aerospike record carries a generation counter, a version number the database increments on each write, and a write can be made conditional on the generation the client read. That check-and-set stops a writer working from a stale read from overwriting a newer value. The counter wraps around after a fixed number of updates, so it suits check-and-set but not version history. Updates that must succeed or fail together across several records need
Aerospike transactions, which run in SC namespaces. Neither one makes an external action happen exactly once: an agent that calls a payment API still needs an idempotency key, or a claim record with a fencing token that it acquires before acting.
In Aerospike SC namespaces, expiration and eviction are non-durable deletes, and the SC guarantee doesn't cover them. Aerospike's guidance is to disable them in SC namespaces unless an operator sets strong-consistency-allow-expunge for data known to be safe. Durable deletes are fully consistent, and they're also the way to make a deletion stick, because a record removed by expiry or a non-durable delete can reappear after a cold restart.
That leaves a choice for session state. A namespace configured for availability supports TTL freely and gives read-your-writes in normal operation, but not across every failover. If losing a session write during a failover is unacceptable, keep session state in an SC namespace with session-consistency reads, and either allow expunge for it or expire it through an application field. State that determines actions, including task claims, should be stored in an SC namespace, with any expiry stored as a field such as expires_at that's checked when the claim is acquired, and is retired through durable deletes.
Semantic recall. Aerospike has no similarity search over embeddings. Pair it with a dedicated vector store or a database with vector capability for that workload.
Human-curated single-user memory. A coding agent with one developer and one project is well served by a file, and a distributed database is more work without helping anything.
Analytical scans over memory history. Aerospike is built for point access and indexed lookups, and large exploratory scans across event history should be in an analytical store.
A proper production layout should look like this.
Aerospike holds session state with TTL, keeps shared operational state and task claims in an SC namespace with linearizable reads where an action depends on them, and stores versioned fact records updated with check-and-set writes or transactions.
A vector store holds embeddings for semantic recall.
Relationship-heavy questions can go to a graph store, such as Aerospike Graph, which runs property-graph queries on Aerospike.
An append-only log or document store holds raw event history until it's compacted.
The agent framework's checkpointer and long-term store each point at the layer whose retention rules match.
Aerospike helps with the problems that survive perfect extraction:
Bounded lifetimes through TTL
Current reads through linearizable SC reads
Lost updates through generation checks
Multi-record changes through transactions
It doesn’t help what the agent decides to remember.
Pick one agent action where a late or stale read has a cost, and trace its loop with these questions, which also make up Aerospike's Operational AI Workload Assessment:
What decision is the agent making, and what is its time budget?
What state does it need, and how current must that state be?
What changes after the agent acts, and which other agents or systems need to see it?
How many actors read and update the same records between one decision and the next?
What happens if the agent reads a fact that's a few seconds old?
Aerospike's guide, Operational AI: The data layer behind real-time decisions, explains the loop and the PayPal workload in full, and the assessment tells you Aerospike’s role in a given workload. Confirm that with a benchmark on your own data before you decide.
Aerospike's documentation includes tutorials for AI agent memory, such as expiring chat sessions with LangGraph and atomic session appends with Google's Agent Development Kit.
Agent memory stores, retrieves, and updates information outside the model. The context window and RAG don't replace it.
Agent memory mixes accumulated knowledge with operational state, the authoritative state of the business right now. Operational AI depends on reading that state when an agent acts and recording the consequence for the next decision.
Most memory quality problems start at the write step, so write gates and deletion matter more than a stronger model.
"Memory" covers six workloads with different latency and consistency needs, and because agent steps fan out, the 99.9th percentile matters more than average latency.
Shared memory needs write ownership, check-and-set writes, strong consistency for state that gates actions, and idempotency keys for external actions.
Files are enough for one user. You need a database at the second user, the second writer, or the first freshness requirement.
Aerospike is useful for the operational side of agent memory: session state, shared operational state, coordination records, and versioned facts by key. Semantic recall needs a separate vector store.
FAQs
No. RAG grounds a model's answer in external information that's usually maintained outside the agent, while agent memory is information the agent writes and reuses across interactions or tasks, such as preferences, decisions, and past interactions. The two can share storage and retrieval methods, and most production agents use both.
No. A larger window lets the agent hold more of the current conversation history before it has to compact, but nothing in the window survives the request unless the application stores it. Cross-session continuity, shared state between agents, and durable user profiles all require a memory layer or database outside the model.
Store compacted conversation history and extracted facts in a durable store keyed by user, and index the parts that need semantic recall in a vector store. For a single-user assistant, a file or SQLite is enough to start. For many users, use a database with per-user scoping, versioned fact records, and expiry, and add a vector store for similarity search over embeddings.
Low-latency operational key-value stores, such as Aerospike, DynamoDB, or Redis, are useful for session state because the agent reads and writes it by session ID on every turn and needs predictable latency. Per-record TTL cleans up ended sessions, and check-and-set writes prevent two concurrent turns from overwriting each other. Choose one with durable replication if the session must survive a restart or a node failure.
A store with atomic per-record updates and strong consistency, such as an operational key-value database in strong-consistency mode with linearizable reads, or a relational database with transactions. Runtime state and task claims determine actions, so two agents must never both claim the same task, which is why you can’t use eventually consistent stores for this workload. Each claim also needs an explicit expiry and a fencing token.
Shared agent memory is usually built on a database rather than bought as a product, because frameworks that orchestrate agents don't assign write ownership for shared state. Common choices are operational key-value stores with check-and-set writes and strong consistency, such as Aerospike or DynamoDB; document databases with causally consistent sessions, such as MongoDB; and relational databases with transactions, such as PostgreSQL. Dedicated memory services such as Letta, Mem0, and Zep also store memory, and most scope it per agent or per user rather than across agents.
Most coding agents read project-level instruction files at the start of each session, such as CLAUDE.md for Claude Code or project rules files in Cursor, and developers edit them by hand. Automatic memory extraction is available through plugins and memory services, and builders report it works best with strict write gates, because unfiltered extraction fills the file with low-value notes.
Only for semantic recall over embeddings. Session state, exact facts, identifiers, and shared operational state should be stored in structured records keyed by entity, where lookups return exact values. A vector store is the right tool for finding past interactions or documents by meaning, but not for anything that must be exact or current.
By memory type, using the store's TTL or an eviction rule set at write time. Session state should expire with the session, intents in weeks or when the task closes, episodic entries after compaction, and preferences when superseded instead of on a timer. Authoritative operational state should be invalidated on change, and leases and task claims should carry an explicit expiry.
By architecture type rather than by benchmark score. Letta is an agent runtime with memory built in, which means adopting its runtime. Mem0 is a memory API that extracts and retrieves facts and sits alongside an existing agent. Zep is built around a temporal knowledge graph for facts that change over time. Decide which of the six memory workloads you have, whether your facts change over time, and whether you need self-hosting, and then run the staleness and conflict tests from this article against the shortlist.
Theodore R. Sumers, Shunyu Yao, Karthik Narasimhan, and Thomas L. Griffiths. "Cognitive Architectures for Language Agents." arXiv:2309.02427, September 5, 2023 (revised March 15, 2024). Published in Transactions on Machine Learning Research, 2024. https://arxiv.org/abs/2309.02427
Patrick Lewis, Ethan Perez, Aleksandra Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich Küttler, Mike Lewis, Wen-tau Yih, Tim Rocktäschel, Sebastian Riedel, and Douwe Kiela. "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks." arXiv:2005.11401, May 22, 2020 (revised April 12, 2021). Published in Advances in Neural Information Processing Systems 33 (NeurIPS 2020). https://arxiv.org/abs/2005.11401
jamebobob. "What we found after auditing 10,134 mem0 entries: 97.8% were junk." Issue #4573, mem0ai/mem0 repository, GitHub, 2026. https://github.com/mem0ai/mem0/issues/4573
fengchao. "632 Hacker News comments about AI memory: six pitfalls, and the one we got wrong." DEV Community, 2026. Originally published at hello-fengchao.com. https://dev.to/fengchao/632-hacker-news-comments-about-ai-memory-six-pitfalls-and-the-one-we-got-wrong-587p
Zidi Xiong, Yuping Lin, Wenya Xie, Pengfei He, Zirui Liu, Jiliang Tang, Himabindu Lakkaraju, and Zhen Xiang. "How Memory Management Impacts LLM Agents: An Empirical Study of Experience-Following Behavior." arXiv:2505.16067, May 21, 2025 (revised October 10, 2025). Published in the proceedings of ACL 2026. https://arxiv.org/abs/2505.16067
Lu Pan. "Cache made consistent." Engineering at Meta, June 8, 2022. https://engineering.fb.com/2022/06/08/core-infra/cache-made-consistent/
Hacker News. "Open source memory layer so any AI agent can do what Claude.ai and ChatGPT do." Discussion thread, item 47897790. Y Combinator, April 2026. https://news.ycombinator.com/item?id=47897790
Tian Pan. "Race Conditions in Concurrent Agent Systems: The Bugs That Look Like Hallucinations." TianPan.co, April 12, 2026. https://tianpan.co/blog/2026/04/12/race-conditions-in-concurrent-agent-systems
Mert Cemri, Melissa Z. Pan, Shuyi Yang, Lakshya A. Agrawal, Bhavya Chopra, Rishabh Tiwari, Kurt Keutzer, Aditya Parameswaran, Dan Klein, Kannan Ramchandran, Matei Zaharia, Joseph E. Gonzalez, and Ion Stoica. "Why Do Multi-Agent LLM Systems Fail?" Advances in Neural Information Processing Systems (NeurIPS 2025), Datasets and Benchmarks Track, 2025. Preprint: arXiv:2503.13657, March 17, 2025. https://proceedings.neurips.cc/paper_files/paper/2025/hash/b1041e52d3be19f0a9bc491657488e4a-Abstract-Datasets_and_Benchmarks_Track.html
Atlas Whoff. "Multi-Agent Memory Without a Vector Database: The Markdown-First Approach." DEV Community, 2026. https://dev.to/whoffagents/multi-agent-memory-without-a-vector-database-the-markdown-first-approach-2lo0
"Separate Long term memory and Checkpointing." Forum thread, LangChain Forum, September 29, 2025. https://forum.langchain.com/t/separate-long-term-memory-and-checkpointing/1668
Sebastian Chedal. "Agent Memory and Knowledge Systems Compared (2026 Guide)." Fountain City, 2026 (content current as of April 2026). https://fountaincity.tech/resources/blog/agent-memory-knowledge-systems-compared/
John Sotiropoulos, Keren Katz, and Ron F. Del Rosario. "OWASP Top 10 for Agentic Applications – The Benchmark for Agentic Security in the Age of Autonomous AI." OWASP GenAI Security Project, December 9, 2025. https://genai.owasp.org/2025/12/09/owasp-top-10-for-agentic-applications-the-benchmark-for-agentic-security-in-the-age-of-autonomous-ai/
Shen Dong, Shaochen Xu, Pengfei He, Yige Li, Jiliang Tang, Tianming Liu, Hui Liu, and Zhen Xiang. "Memory Injection Attacks on LLM Agents via Query-Only Interaction" (originally titled "A Practical Memory Injection Attack against LLM Agents"). arXiv:2503.03704, March 5, 2025 (revised February 12, 2026). https://arxiv.org/abs/2503.03704
Balachandra Devarangadi Sunil, Isheeta Sinha, Piyush Maheshwari, Shantanu Todmal, Shreyan Mallik, and Shuchi Mishra. "Memory Poisoning Attack and Defense on Memory Based LLM-Agents." arXiv:2601.05504, January 9, 2026 (revised January 12, 2026). https://arxiv.org/abs/2601.05504
Yanki Margalit, Nurit Cohen-Inger, Erni Avram, Ran Taig, and Oded Margalit. "Governed Shared Memory for Multi-Agent LLM Systems." arXiv:2606.24535, June 23, 2026. https://arxiv.org/abs/2606.24535
Daniel Chalef and Preston Rasmussen. "Lies, Damn Lies, and Statistics: Is Mem0 Really SOTA in Agent Memory?" Zep Blog, May 6, 2025. https://blog.getzep.com/lies-damn-lies-statistics-is-mem0-really-sota-in-agent-memory/
Prateek Chhikara, Dev Khant, Saket Aryan, Taranjeet Singh, and Deshraj Yadav. "Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory." arXiv:2504.19413, April 28, 2025. https://arxiv.org/abs/2504.19413
For a deeper understanding and more insights, explore these additional resources.
See moreBlog
Blog
Blog
Blog