
From RAG to Memory Systems: Building Stateful AI Architecture on AWS
This article explores how a small set of AWS-native components — typed memory, a promotion gate, hybrid retrieval, and bounded-context prompt assembly — turn a retrieval pipeline into a memory system that lets AI agents remember, reuse, and stay governable in production.
This article explores how a small set of AWS-native components — typed memory, a promotion gate, hybrid retrieval, and bounded-context prompt assembly — turn a retrieval pipeline into a memory system that lets AI agents remember, reuse, and stay governable in production.
Introduction
Most teams that ship an AI agent start with retrieval-augmented generation: embed your documents, embed the query, pull the top-K nearest neighbours, stuff them into the prompt. It's roughly four lines of code, and it's good enough to be the default for nearly every internal knowledge assistant shipped in the last two years.
It also explains why those assistants all feel the same after the first interesting conversation. They forget. They repeat themselves. They can't learn from what they were just told, and they can't carry a meaningful thread across sessions. RAG answers "what does the corpus say" — it was never built to answer "what does this system already know about this user, this account, or this task."
Organizations that want AI agents to behave like durable systems of record face a specific set of challenges:
- They need the agent to recall user preferences, account facts, and policy exactly — not approximately — and do it the same way on every turn.
- They need conversations and workflows to survive a closed tab, a process restart, or a handoff to another agent.
- They need long-running interactions to stay within a bounded, affordable context window instead of growing the prompt forever.
- They need a governed write path, so what the agent "learns" during a session doesn't silently poison what every future session sees.
- They need to delete a user's data on request, across every store that touched it, without losing the ability to audit what happened.
What makes a memory system different
Retrieval is a query against a corpus you ingested once. The corpus sits upstream, the query sits downstream, and nothing the model says or does flows back into it.
A memory system adds a write path. Anything the system observes during a run — or that a user explicitly confirms — can be promoted into a durable store with its own scope, its own provenance back to the run that created it, and a retention rule. That same record can then be read back by a different turn, a different session, or a different agent operating under the same access boundary.
The popular shorthand for this is "second brain," and most implementations stop one step short of earning it: they give you searchable notes, which is closer to a better filing cabinet than to memory. A real second brain is accumulated, reusable memory — notes distilled into facts attached to the entities they describe, completed work summarised into reusable episodes, and one store serving a chat session, an autonomous agent, and a human searching their own history later, without any of them needing their own copy.
A vector store alone is not a memory system. It's one component of one path inside a larger loop.

Key features of a memory system on AWS
Five types of memory, five jobs
"Add memory" sounds like one feature. In practice it's several distinct systems with different lifecycles, and conflating them produces predictable failure modes — a user preference that looks like a passing remark from three weeks ago, or a tenant policy ranked by similarity instead of enforced exactly.
- Policy memory (DynamoDB) — procedural rules and constraints: approval thresholds, compliance boundaries, brand guardrails. Retrieved by exact match only, never by similarity. A policy found "approximately" is a policy you're not actually enforcing.
- Preference memory (DynamoDB + ElastiCache) — stable personalization: output format, tone, date formats. Cached per session, and it feeds the stable part of the prompt.
- Fact memory (Aurora pgvector + OpenSearch) — durable, reusable assertions with provenance, like "this customer's production database is in eu-west-1." This is what stops the agent asking the same clarifying question every session — and what poisons the system fastest if promoted carelessly.
- Episodic memory (Aurora pgvector) — structured summaries of completed work, so the agent can recognize "we've done this before" and retrieve the shape of a prior solution instead of re-deriving it.
- Trace memory (S3 + Kinesis) — the raw, append-only flight recorder: what was retrieved, what was decided, what tools were called. It's the source that facts and episodes get distilled from, and the wrong place to search when you want to know what a user prefers.

Two retrieval paths, not one
Memory retrieval isn't one operation wearing two hats — it's two genuinely different queries. Known-scope lookup asks "give me everything active for this tenant and user" — exhaustive, no ranking, no top-K cutoff, and it feeds the stable part of every prompt. Semantic discovery asks "find what's conceptually relevant to this message" — ranked, score-thresholded, and it runs against facts and episodes on demand, combining vector similarity with lexical match so a query for "this user's timezone" doesn't get lost among documents that are merely about timezones.
Scope has to be filtered before ranking, not after. A query that ranks across every tenant and filters the results down afterward has already let the wrong tenant's data shape the neighbourhood it's ranking against — the filter arrives too late to matter.
-- Wrong: ranks across everyone, filters afterSELECT * FROM fact_memoryORDER BY embedding <=> :query LIMIT 100-- then filtered by tenant_id in application code
-- Right: scope enforced before any ranking happensSELECT * FROM fact_memoryWHERE tenant_id = :tenant_id AND status = 'active'ORDER BY embedding <=> :query LIMIT 5The promotion gate — the highest-risk operation in the system
Promote everything the model observes and the store poisons itself with speculation. Promote nothing and the agent is amnesiac. The promotion gate is the single decision point in between: given a candidate fact, should it enter durable memory, with what scope, and what confidence?
In practice the gate runs three checks in one transaction: it deduplicates by content hash so a fact re-stated twice reinforces a confidence score instead of creating a duplicate; it checks confidence and source, so a user-confirmed statement ("yes, remember that") goes straight to active status while a low-confidence inference gets held for review or rejected outright; and it computes the embedding once, at write time, so read-path latency never depends on live embedding calls. Every rejection gets logged — when a user says "the agent forgot X," that log is almost always where the answer is, not in the retrieval path.
Bounded context — the prompt is rebuilt, never accumulated
The instinct in a long-running conversation is to keep dumping the transcript into the prompt and trust the context window to absorb it. That fails for three compounding reasons: a prompt with a lot of volatile content gets poor cache hit rates, more tokens often make the model worse through lost-in-the-middle effects, and a raw transcript is the wrong shape to answer "what does this user prefer" — you can only answer that from a summary you already extracted.
A memory system reassembles the prompt from durable storage on every turn instead. Policy and preferences sit in a stable prefix that hits the model's prompt cache; the top few relevant facts and episodes, plus a compressed tail of recent turns, sit in a dynamic suffix underneath. The full transcript stays in the trace log in S3 — available for replay, never re-sent wholesale. Structuring the prompt this way, with everything stable at the top, is what makes prompt caching actually pay off instead of missing on every call.
Common use cases for memory systems
Multi-turn continuity and resumable sessions
A user closes the tab Friday and reopens Monday, expecting the agent to remember what they were doing. With retrieval alone, the only thing that survives is the document corpus — every preference and every partial workflow is gone. With typed memory, the session picks up from durable state rather than a live process, so it survives restarts, multiple servers, and multiple regions without any special handling.
Long conversations without context blowup
After a few hundred turns, a transcript can't be packed into a prompt anymore. Two distillation modes handle this: rolling summarisation compresses older turns as the conversation grows, and episodic extraction runs when a task completes, turning it into a reusable summary — task, outcome, key decisions — that a future session can retrieve instead of re-deriving the same solution from scratch.
Precise preference and policy recall
"This tenant formats dates DD/MM/YYYY." "Refunds over €500 need approval." These aren't retrieved by similarity to the last thing the user said — they're durable rules that need exact, stable lookup on every single turn, scoped correctly to the right user or tenant. Getting this wrong doesn't fail loudly; it fails as a policy that's quietly not being enforced.
Memory across multiple agents and sessions
When more than one agent operates on behalf of the same user or tenant, memory needs to be shared without being tangled. Some deployments use a single shared store all agents read from; others give each agent private working memory with a coordinated handoff when work moves between them. Either way, scope — not physical separation — is what keeps agents from stepping on each other's context.
Privacy, scope, and the right to be forgotten
Every record carries a scope — tenant, user, and sometimes a specific agent — enforced as a hard predicate before anything is ranked. Row-level security at the database layer means even a query that forgets to filter by tenant still can't see across boundaries. And because durable memory lives in an actual database rather than a live process, a deletion request becomes a real operation: a cascading delete across every store the data touched, not a promise about what a running process might eventually forget.
An example journey: getting there from RAG

You don't need to build all of this on day one. A working path looks like this:
Start with trace logging. Write every user message and model response to an append-only log, even before anything else changes. This alone makes debugging and later evaluation possible, and it costs almost nothing to add.
Split policy and preference out of the vector store. These need exact lookup, not similarity ranking — pulling them into their own exact-match store (DynamoDB works well) immediately fixes the class of bug where a rule gets "approximately" enforced.
Add a memory manager layer. Instead of the agent talking to a vector store directly, route every read and write through one component that knows the scope rules and can be changed in one place.
Add the promotion gate — but don't turn it on yet. Run it in shadow mode first: log what it would promote, and review that log before trusting it to write automatically. This is where most of the risk in the whole system lives, so it's worth watching before it's live.
Move facts and episodes into a proper store with vector support, and add hybrid retrieval — combining lexical and semantic search — once ranked recall is actually needed rather than exact recall.
Each step is independently useful, which is what makes this a migration rather than a rewrite.
Is a memory system right for you?
A few signals are worth checking before you build any of this.
Start with exactness. If someone asks your agent "what's our refund policy" and a wrong-but-close answer is a real business risk, similarity search was never going to get that right reliably, no matter how good the embeddings are — that's a lookup problem, not a ranking problem.
Then there's continuity. Users who close a tab on Friday and come back Monday expect the agent to remember what they were doing. If a fresh session every time is genuinely fine for your use case, you can put this off. Most teams find out it isn't fine the first time a customer complains about repeating themselves to a bot that already forgot.
Prompt size is another tell. If it's been quietly growing for months and nobody's touched the ceiling on it, that's not a token-budget problem you patch with a bigger context window — it's the first visible symptom that summarisation and structured memory are overdue, and it tends to get worse on its own, not better.
Multi-tenant or multi-agent setups raise the stakes further. Scope enforcement can't live in application code that everyone has to remember to write correctly every time — eventually someone forgets, and someone's data ends up somewhere it shouldn't. It has to be a property of the database itself.
And if there's any regulatory obligation, existing or likely, to delete a user's data on request, that alone settles it. A deletion request needs somewhere real to reach. State that only lives inside a running process isn't somewhere real.
For most teams these don't show up one at a time — they compound. The good news is the AWS services involved (DynamoDB, Aurora with pgvector, OpenSearch, S3, Kinesis, Bedrock) are usually ones you're already running for something else. The lift is mostly architectural discipline, not new infrastructure.
Conclusion
RAG is retrieval, and retrieval is one input to a larger loop — not the whole system. What separates a stateful AI agent from a well-read one is a write path: typed memory with real scope, a promotion gate that decides what's worth remembering, retrieval that knows the difference between an exact rule and a similar-sounding fact, and a prompt that gets rebuilt from durable storage every turn instead of growing without bound. None of it requires exotic infrastructure — it's a handful of AWS services arranged around a clear set of rules about what each one is for.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article