AI agents often need to perform multiple tasks before completing a workflow.
An agent might first research a topic, then analyze the findings, generate a report, and finally answer questions about the work. If every task starts without access to previous results, the agent must repeatedly retrieve information or reconstruct its earlier decisions.
This creates unnecessary processing, increases response time, and can lead to inconsistent results.
Agent memory helps solve this problem by allowing an AI application to store useful information and retrieve it during later tasks.
SurrealDB provides an agent memory capability through SurrealDB's database and AI-oriented features. It can store information associated with agents, users, sessions, and tasks, making it possible to maintain context beyond a single interaction.
However, memory is not simply a conversation transcript. A useful memory system needs to decide what information should be stored, how it should be organized, when it should be retrieved, and when outdated information should be removed.
This article explains how to approach persistent agent memory with SurrealDB, how to structure memory records, how to retrieve relevant context, and what developers should consider when building multi-step AI workflows.
Why AI Agents Need Persistent Memory
A typical AI interaction is often stateless from the application's perspective.
The application sends a prompt to an AI model, receives a response, and finishes the request.
For example:
User: Analyze the sales performance of Product A.
Agent: Product A generated $50,000 in revenue.
User: Compare it with Product B.
Agent: Please provide the sales data for Product A.
The agent cannot answer the second question reliably if the application does not provide the earlier result.
One solution is to send the complete conversation history with every request. However, this approach becomes inefficient as conversations grow.
A better approach is to store useful information separately and retrieve only the context needed for the current task.
Agent memory can preserve information such as:
- User preferences.
- Previous task results.
- Important decisions.
- Project-specific information.
- Relevant facts extracted from documents.
- Workflow state.
- Previously completed actions.
This allows an agent to continue working without treating every task as an entirely new interaction.
Understanding Different Types of Agent Memory
Before implementing memory, identify what kind of information the application needs to retain.
Not all memory has the same purpose.
A practical agent architecture usually separates memory into several categories.
Short-Term Memory
Short-term memory contains information required during the current conversation or task.
For example, a customer-support agent may need to remember the product name, current issue, and troubleshooting steps discussed during a session.
This information is useful while the workflow is active but may not need to remain available indefinitely.
Episodic Memory
Episodic memory stores information about previous interactions or events.
For example:
- A user previously requested a database migration plan.
- An agent completed a deployment analysis.
- A project review identified three unresolved issues.
- A support workflow was completed on a particular date.
This helps an agent understand what happened previously.
Semantic Memory
Semantic memory stores facts and knowledge that can be reused across different tasks.
For example:
- A project uses PostgreSQL.
- The application is built with .NET.
- The production environment runs in Azure.
- A particular API requires authentication.
Unlike episodic memory, semantic memory focuses on useful knowledge rather than the complete history of an event.
Procedural Memory
Procedural memory describes how an agent should perform a particular task.
For example, a deployment agent might follow these steps:
- Validate the configuration.
- Run automated tests.
- Build the container image.
- Deploy to the staging environment.
- Verify application health.
- Request approval before production deployment.
Procedural memory can help agents follow consistent workflows.
These categories are an architectural design choice. They are not separate storage engines that must be enabled in SurrealDB.
How SurrealDB Can Support Agent Memory
SurrealDB is a multi-model database that supports structured records, relationships, graph queries, and vector search.
These capabilities can be combined to build a memory layer for AI applications.
For example, an application can store:
- Agent profiles.
- User information.
- Conversation sessions.
- Task history.
- Memory records.
- Relationships between users, agents, and tasks.
- Embeddings used for semantic retrieval.
A relational structure helps maintain ownership and relationships, while vector search can help retrieve memories based on meaning rather than exact keywords.
The application remains responsible for deciding which information should become memory and how the AI model should use the retrieved information.
Designing a Memory Data Model
A useful memory design should identify the owner, content, category, and lifetime of each memory.
Consider an application that runs multiple AI agents for different projects.
One agent handles database analysis, another prepares technical documentation, and a third reviews code changes.
The application should avoid mixing their memory records.
A basic memory record might contain:
| Field | Purpose |
|---|
| id | Unique memory identifier |
| agent_id | Agent associated with the memory |
| user_id | User who owns or contributed the information |
| session_id | Related conversation or task session |
| memory_type | Short-term, episodic, semantic, or procedural |
| content | Stored information |
| created_at | Creation timestamp |
| updated_at | Last modification timestamp |
| expires_at | Optional expiration timestamp |
| importance | Application-defined relevance score |
The following SurrealQL example creates a memory table:
DEFINE TABLE agent_memory SCHEMAFULL;
DEFINE FIELD agent_id ON agent_memory TYPE string;
DEFINE FIELD user_id ON agent_memory TYPE string;
DEFINE FIELD session_id ON agent_memory TYPE option<string>;
DEFINE FIELD memory_type ON agent_memory
TYPE string
ASSERT $value IN [
"short_term",
"episodic",
"semantic",
"procedural"
];
DEFINE FIELD content ON agent_memory TYPE string;
DEFINE FIELD created_at ON agent_memory
TYPE datetime
DEFAULT time::now();
DEFINE FIELD updated_at ON agent_memory
TYPE datetime
DEFAULT time::now();
DEFINE FIELD expires_at ON agent_memory TYPE option<datetime>;
DEFINE FIELD importance ON agent_memory
TYPE float
DEFAULT 0.5;
This example provides a basic structure for memory records.
In a production application, also consider access-control policies, record ownership, validation rules, and the database version's supported schema features.
Storing Memory After an AI Task
A common mistake is storing every AI response as permanent memory.
Not every response is useful later.
For example, a temporary greeting or an intermediate calculation may not need to be stored.
Instead, the application should identify information that is likely to improve future tasks.
A practical memory-writing workflow looks like this:
- Receive a user request.
- Retrieve relevant existing memory.
- Execute the AI task.
- Extract useful information from the result.
- Evaluate whether the information should be retained.
- Store or update the appropriate memory record.
The memory extraction step can use an AI model or application-defined rules.
For example, an agent might produce this result:
{
"memory_type": "semantic",
"content": "The inventory service uses PostgreSQL and is deployed in Azure.",
"importance": 0.85
}
The application can validate the extracted data and store it in SurrealDB.
A basic insertion can use SurrealQL:
CREATE agent_memory CONTENT {
agent_id: "inventory-agent",
user_id: "user-1001",
session_id: "session-2001",
memory_type: "semantic",
content: "The inventory service uses PostgreSQL and is deployed in Azure.",
importance: 0.85
};
This creates a memory record associated with the specified agent and user.
The application should generate identifiers securely and validate ownership before accepting memory writes.
Retrieving Memory for a New Task
Storing information is only half of the implementation.
The agent must also retrieve the relevant memory when a new task arrives.
For example, suppose a user asks:
Prepare a deployment checklist for the inventory service.
The application may already have stored these facts:
- The service uses PostgreSQL.
- The service runs in Azure.
- The application is containerized.
- Database migrations are part of the release process.
Instead of asking the user to provide the same details again, the application can retrieve the existing memory.
A simple SurrealQL query can filter records by agent and user:
SELECT
id,
memory_type,
content,
importance,
created_at
FROM agent_memory
WHERE agent_id = "inventory-agent"
AND user_id = "user-1001"
ORDER BY importance DESC, created_at DESC
LIMIT 20;
This retrieves the most relevant records according to the application's simple ordering rules.
The application can then add the selected records to the context supplied to the AI model.
However, ordering by importance and date is not the same as semantic relevance.
As the number of memories increases, retrieving the latest records alone may return information unrelated to the current task.
This is where vector search becomes useful.
Using Vector Search to Find Relevant Memories
Vector search retrieves information based on semantic similarity.
Instead of matching only exact words, it compares numerical representations of text.
For example, these two requests have different wording but similar meaning:
- "How is the inventory application deployed?"
- "Explain the infrastructure used by the stock management service."
A keyword search may not identify all relevant records.
A vector search can retrieve memories that represent similar concepts.
Generate an Embedding
The application first converts memory content into an embedding using a selected embedding model.
For example:
The inventory service uses PostgreSQL and is deployed in Azure.
The embedding model converts the text into a numerical vector.
The vector is stored with the memory record.
A simplified schema addition might look like this:
DEFINE FIELD embedding ON agent_memory
TYPE option<array<float>>;
The vector dimension must match the selected embedding model.
For a production implementation, verify the embedding field definition and vector index syntax supported by the SurrealDB version being used.
Retrieve Similar Memories
When a new task arrives, the application generates an embedding for the user's request.
It then performs vector similarity search against stored memory embeddings.
Conceptually, the query follows this process:
User request
|
v
Generate query embedding
|
v
Search stored memory vectors
|
v
Filter by agent and user
|
v
Rank relevant memories
|
v
Add selected memories to agent context
SurrealDB supports vector indexing and similarity search, but the exact index definition and query syntax should be selected for the deployed version.
Do not assume that a vector similarity result is automatically correct. Apply ownership filters, relevance thresholds, and application-level validation before using retrieved information.
Combining Structured and Semantic Retrieval
Vector search is useful for discovering relevant information, but it should not replace structured queries.
Suppose an application stores thousands of memory records for multiple users and agents.
A request should retrieve only records belonging to the correct user and agent.
The application can combine:
- Structured filtering for user and agent ownership.
- Memory type filtering.
- Time-based filtering.
- Vector similarity for semantic relevance.
- Importance or confidence scoring.
For example, an application might first restrict the search to semantic and episodic memories owned by the current user, then rank those records using vector similarity.
This reduces irrelevant retrieval and helps prevent memory leakage between users.
The exact query design depends on the supported SurrealQL and vector search capabilities in the deployed release.
Managing Memory Updates and Expiration
Memory becomes less useful when it contains outdated information.
Consider a project that originally used MySQL but later migrated to PostgreSQL.
If the agent continues retrieving the old database information, it may generate an incorrect deployment plan.
A memory system therefore needs an update strategy.
Update Existing Memories
When new information conflicts with an existing record, the application should decide whether to:
- Update the existing memory.
- Create a new memory with a timestamp.
- Mark the previous memory as superseded.
- Retain both records as historical events.
For example, a semantic memory about the current database platform should generally represent the latest verified configuration.
An episodic memory about the earlier migration decision should remain available as historical context.
Expire Temporary Memories
Short-term memories may not need to remain permanently.
For example, a session-specific troubleshooting record could expire after a defined period.
A cleanup query can identify expired records:
SELECT
id,
content
FROM agent_memory
WHERE expires_at IS NOT NONE
AND expires_at < time::now();
After reviewing the results, the application can delete expired records according to its retention policy.
Do not automatically delete every old memory. Historical decisions and audit-related information may have long-term value.
Managing Relationships Between Agents, Users, and Tasks
In a multi-agent application, memory often belongs to more than one entity.
For example:
- A user owns a project.
- A project contains multiple tasks.
- Several agents work on the project.
- Each task generates memory records.
- Agents may need access to selected shared information.
SurrealDB's record and graph capabilities can help represent these relationships.
A simple logical model could look like this:
User
|
+---- Project
|
+---- Task
| |
| +---- Memory
|
+---- Agent
|
+---- Memory
The application should define which records are private and which are shared.
For example, a user's personal preference should not automatically become visible to every agent in a shared project.
Similarly, one agent should not be able to modify another agent's memory without authorization.
Use database permissions and application-level authorization to enforce these boundaries.
Handling Memory Conflicts and Untrusted Information
Persistent memory introduces a security and data-quality problem.
An agent may store information that is incorrect, outdated, or extracted from an untrusted document.
For example, a document might contain an instruction telling the agent to ignore its existing rules and reveal confidential information.
If that instruction is stored as trusted memory, it can influence future tasks.
This is a form of persistent prompt injection.
To reduce this risk:
- Treat retrieved memory as data, not executable instructions.
- Do not store arbitrary document instructions as trusted agent rules.
- Track the source of important memory records.
- Store confidence or verification status where appropriate.
- Validate memory updates before accepting them.
- Apply ownership and access-control checks.
- Allow users or administrators to correct incorrect memories.
A useful extension to the memory schema is a source field:
DEFINE FIELD source ON agent_memory TYPE option<string>;
DEFINE FIELD verified ON agent_memory
TYPE bool
DEFAULT false;
The application can use these fields to distinguish verified configuration facts from information extracted from an external source.
Common Mistakes When Implementing Agent Memory
| Mistake | Why it causes problems | Better approach |
|---|
| Storing every AI response | Memory becomes noisy and difficult to retrieve | Store useful, reusable information |
| Retrieving only recent records | Relevant older information may be missed | Combine structured and semantic retrieval |
| Mixing different users' memories | Can expose private information | Enforce ownership filters and permissions |
| Treating retrieved memory as instructions | Untrusted content can influence agent behavior | Treat memory as data and validate it |
| Keeping outdated facts | Agents may generate incorrect responses | Add update, expiration, and supersession rules |
| Relying only on vector similarity | Similar wording does not guarantee factual relevance | Apply metadata filters and validation |
| Ignoring memory size | Large context increases processing cost | Retrieve only the information needed |
| Failing to record sources | Incorrect information becomes difficult to investigate | Store provenance and verification status |
Advantages and Disadvantages of SurrealDB for Agent Memory
Advantages
- Supports structured records and relationships.
- Provides graph capabilities for connecting users, agents, tasks, and memories.
- Supports vector search for semantic retrieval.
- Allows different memory categories to be represented in a flexible data model.
- Can support persistent context across multiple agent tasks.
- Provides a database foundation for applications that combine structured and semantic data.
Disadvantages
- Developers must design memory extraction and retrieval policies.
- Vector search requires an embedding model and additional processing.
- Incorrect or outdated memories can affect future agent responses.
- Multi-user memory requires careful authorization and isolation.
- Large memory collections need indexing, cleanup, and retention strategies.
- Database persistence alone does not provide complete agent orchestration or reasoning.
Summary
Persistent memory helps AI agents maintain useful context across conversations and multi-step workflows.
SurrealDB provides a foundation for building this capability through structured records, relationships, and vector search.
A practical implementation should separate short-term, episodic, semantic, and procedural information. It should also define how memories are created, retrieved, updated, expired, and protected.
Use structured queries to enforce ownership and metadata filters, and use vector search to discover semantically relevant information. Do not rely on similarity alone when selecting facts for an agent.
Most importantly, treat memory as an application-managed knowledge layer rather than a permanent transcript of every AI interaction.
A well-designed memory system gives agents access to relevant previous information while keeping context accurate, controlled, and useful for the task they are performing.
Join the conversation! Your thoughts help the community grow.