You add memory to your AI agent with Amazon Bedrock AgentCore Memory. It works. The agent remembers a customer's name, their last order and what they asked about yesterday.
A few days later, things get strange. Answers start repeating old facts. The context the agent pulls back keeps getting longer. Some "memories" look like notes the agent wrote to itself.
Nothing crashed, so it's easy to miss. But your agent's memory is slowly filling up with its own echoes.
I call this memory pollution, and it comes from one small mistake that's very easy to make. Let's look at what it is, how to spot it and how to fix it.
In this post:
- How memory usually gets added to an agent
- The one line that causes memory pollution
- How to spot it
- How to fix it, and clean up afterwards
How memory usually works in an agent
A common pattern with AgentCore Memory and the Strands Agents SDK is to use hooks. A hook is a function that runs automatically at a certain moment in the agent's life, for example when a request starts or when it ends.
Most memory setups use two hooks:
- When a request starts: look up related memories and add them to the user's message as extra context.
- When the request ends: save the conversation turn to memory, so it can be recalled later.
AgentCore keeps those saved turns as events. If you've configured long-term memory strategies, AgentCore also processes the events in the background and extracts useful facts, such as "the customer prefers email" or "the customer's name is Amina". These extracted facts are stored separately as memory records. Extraction happens asynchronously, so new records may not be available straight away.
This is a good design. The problem is in how step 1 and step 2 interact.
The one line that causes it
Here's a simplified version of a memory hook. It's a teaching example, so it leaves out error handling. Look closely at what gets saved.
from strands.hooks import AfterInvocationEvent, BeforeInvocationEvent, HookProvider, HookRegistry
class MemoryHook(HookProvider):
def __init__(self, client, memory_id, actor_id, session_id):
self.client = client
self.memory_id = memory_id
self.actor_id = actor_id
self.session_id = session_id
def add_context(self, event: BeforeInvocationEvent):
if not event.messages:
return
message = event.messages[-1]
if message["role"] != "user":
return
user_text = message["content"][0]["text"]
memories = self.client.retrieve_memories(
memory_id=self.memory_id,
namespace=f"/support/customer/{self.actor_id}/facts/",
query=user_text,
top_k=3,
)
context = "\n".join(m["content"]["text"] for m in memories)
if context:
# The user's message is rewritten to include the memories
message["content"][0]["text"] = f"Relevant context:\n{context}\n\nUser: {user_text}"
def save_turn(self, event: AfterInvocationEvent):
messages = event.agent.messages
user_text = messages[-2]["content"][0]["text"] # <-- the problem
reply = messages[-1]["content"][0]["text"]
self.client.create_event(
memory_id=self.memory_id,
actor_id=self.actor_id,
session_id=self.session_id,
messages=[(user_text, "USER"), (reply, "ASSISTANT")],
)
def register_hooks(self, registry: HookRegistry):
registry.add_callback(BeforeInvocationEvent, self.add_context)
registry.add_callback(AfterInvocationEvent, self.save_turn)
A note on the namespace: the one you retrieve from has to match the namespace configured in your memory strategy. AWS recommends a leading and trailing slash, as shown here.
Did you spot the problem?
add_context changes the user's message in place. By the time save_turn runs, the "user message" in the conversation isn't what the user typed anymore. It's the user's words plus every memory that was retrieved.
So the agent saves its own memories back into memory, as if the user had said them.
Here's what that looks like in storage. This is what gets saved as the USER message:
Relevant context:
The customer's name is Amina.
User: Where's my order?
And this is what should be saved:
Where's my order?
Why this snowballs
Here's what happens over a few turns:
- Turn 1: the user says "Hi, I'm Amina." That gets saved. AgentCore extracts the fact: the customer's name is Amina.
- Turn 2: the user asks "Where's my order?" The hook adds "the customer's name is Amina" to the message. The whole thing gets saved.
- AgentCore processes that saved turn and extracts the name fact again, now from a message that looks like the user said it.
- Turn 3: more memories are retrieved, added, and saved again.
Each turn feeds old memories back in. You get duplicate facts, longer and longer context, and old information that keeps getting reinforced even after it's out of date. If a fact was wrong once, it keeps coming back.
There can also be a cost. More text saved means more text processed, and more context sent to the model on every turn.
There's a second, smaller bug hiding in save_turn. It assumes the second-to-last message is always the user's input, and that the last message is the reply. That assumption can break when the conversation includes tool calls, tool results or other messages. It's safer to identify the user's message and the reply explicitly than to rely on their position in the list.
How to spot it
You don't need special tools. Check what's actually stored, in both places:
-
Raw events. List the events for one test customer. If a USER message starts with
Relevant context:(or whatever label your hook uses), you have memory pollution. - Long-term memory records. Check these separately. If the same fact appears again and again with slightly different wording, that's another sign.
- Context size. Log the length of the context your hook retrieves. If it keeps growing for the same customer, something is feeding back in.
The fix: save what the user actually said
The fix is simple. Keep a copy of the original message before you add context, and save that copy.
Where you keep the copy matters. If you store it on the hook object itself, two requests running at the same time could overwrite each other's copy. Strands passes an invocation_state dictionary through each request, and it's available to both hooks. That's the right place for anything that belongs to one request.
from strands.hooks import AfterInvocationEvent, BeforeInvocationEvent, HookProvider, HookRegistry
class MemoryHook(HookProvider):
def __init__(self, client, memory_id, actor_id, session_id):
self.client = client
self.memory_id = memory_id
self.actor_id = actor_id
self.session_id = session_id
def add_context(self, event: BeforeInvocationEvent):
if not event.messages:
return
message = event.messages[-1]
if message["role"] != "user":
return
user_text = message["content"][0]["text"]
# Keep the clean version for this request only
event.invocation_state["original_user_text"] = user_text
memories = self.client.retrieve_memories(
memory_id=self.memory_id,
namespace=f"/support/customer/{self.actor_id}/facts/",
query=user_text,
top_k=3,
)
context = "\n".join(m["content"]["text"] for m in memories)
if context:
message["content"][0]["text"] = f"Relevant context:\n{context}\n\nUser: {user_text}"
def save_turn(self, event: AfterInvocationEvent):
user_text = event.invocation_state.get("original_user_text")
if not user_text:
return
# This hook also runs when a request fails, so only save finished replies
result = event.result
if result is None or result.stop_reason != "end_turn":
return
reply = str(result).strip()
if not reply:
return
self.client.create_event(
memory_id=self.memory_id,
actor_id=self.actor_id,
session_id=self.session_id,
messages=[(user_text, "USER"), (reply, "ASSISTANT")],
)
def register_hooks(self, registry: HookRegistry):
registry.add_callback(BeforeInvocationEvent, self.add_context)
registry.add_callback(AfterInvocationEvent, self.save_turn)
What changed:
-
The original message is kept in
invocation_state, so each request has its own copy. -
save_turnsaves that clean copy, not the rewritten message. - The reply comes from the request's result, not from a position in the message list, so tool calls don't break it.
- Failed requests aren't saved. The end-of-request hook runs whether the request succeeded or failed, so the code checks that it finished normally before saving anything.
The agent still gets the extra context while it thinks. It just doesn't write that context back into memory.
Another option: don't touch the user's message at all
If you'd rather avoid the problem completely, put the retrieved memories somewhere other than the user's message, for example in the system prompt for that turn. Then there's nothing to undo when you save. Both approaches work. The important rule is the same: memory should store what was said, not what you added.
Before you use this in production
This is still a teaching example. The hook events used here are documented in the Strands SDK, but check them against the version you have installed. A production version also needs to handle messages that aren't plain text (images, documents), structured outputs, and retries that could save the same turn twice.
Clean up after the fix
Fixing the code stops new pollution, but it doesn't remove what's already stored.
AgentCore keeps raw events and extracted long-term memory records separately. If a polluted event has already produced a memory record, deleting the event alone won't remove that record. You may need to delete both.
- For testing: start with a fresh customer ID (actor ID). That gives you a clean memory to check the fix with.
- For existing users: look at the affected events and memory records, and clean up both where needed.
Check that it worked
Run a simple two-session test with the same customer ID and different session IDs:
- Session A: "Hi, I'm Amina and I prefer email updates."
- Wait for extraction. It happens in the background, so don't rely on a fixed delay. Check the memory records until the expected facts appear.
- Session B: "What's my name, and how should you contact me?"
The agent should answer "Amina" and "email". Then look at your saved events: the USER messages should contain exactly what you typed, with no Relevant context: anywhere.
Quick checklist
- The hook saves the user's original text, not the message with context added.
- The original text is kept per request (in
invocation_state), not on the hook object. - The reply comes from the request's result, and failed requests aren't saved.
- Your retrieval namespace matches the one configured in your memory strategy.
- No saved USER message contains your context label.
- You checked both raw events and long-term memory records.
- You tested with a fresh customer ID.
- A two-session test recalls the right facts.
The takeaway
Memory bugs are quiet. Nothing crashed, and the agent still seems to work. That's exactly why they're worth checking for.
When you add context to help your agent think, make sure that context doesn't sneak back into what you save. Store what was said, not what you added.
Have you run into a strange memory bug in your own agents? Tell me in the comments.
Further reading
- AgentCore Memory strategies
- Organising long-term memory with namespaces
- Deleting AgentCore Memory events
- Deleting long-term memory records
- Strands hook events
I drafted this post with help from an AI assistant, then tested the code and edited it myself.
Top comments (0)