Memory Storage: Vector, SQL or Knowledge Graph
Each kind of store answers a different kind of question. Pick by the questions your agent must ask, not by what is fashionable.
Use a relational or document database for exact facts, state and anything you must update, count or delete reliably. Add vector search when the agent must find memories by meaning. Use a knowledge graph when answers depend on chains of relationships. Many agents need only one database with a vector extension, and should add a second engine only when a measured need appears.
What you will learn: what each storage type does well and badly, how to model memory records, how to choose, what open-source options exist and how to keep several stores consistent.
Prerequisites: Agent Memory Types and Persistence. Basic familiarity with databases helps.
Start from the questions
Before choosing a product, write down the questions the agent will ask its memory. They tend to fall into a few shapes:
| Question shape | Example | Natural store |
|---|---|---|
| Exact lookup | What is this user's preferred language? | Relational or key-value |
| Filtered list or count | Open tasks assigned this week | Relational |
| Current state of a job | Which step is the refund workflow on? | Relational or document |
| Loose recall by meaning | Have we discussed something like this before? | Vector search |
| Exact words and codes | Find the note mentioning error E-4042 | Full-text search |
| Chains of relationships | Who owns the service my project depends on? | Graph |
| Large raw records | The full transcript from March | Object or file storage |
The same facts can be stored three ways, and each answers a different question well.
"""The same memories in SQL, a similarity index and a graph."""
import math
import re
import sqlite3
from collections import Counter
FACTS = [("Priya", "manages", "Atlas project"),
("Atlas project", "depends_on", "billing service"),
("billing service", "owned_by", "Marco"),
("Priya", "prefers", "short written summaries"),
("Marco", "prefers", "calls in the morning")]
# 1. SQL: exact, filtered, countable
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE fact (subject TEXT, relation TEXT, object TEXT)")
db.executemany("INSERT INTO fact VALUES (?,?,?)", FACTS)
sql = db.execute("SELECT object FROM fact WHERE subject=? AND relation=?",
("Priya", "prefers")).fetchall()
print("SQL :", [r[0] for r in sql])
# 2. Similarity search: loose wording. Word counts stand in for embeddings.
def vec(text):
return Counter(re.findall(r"[a-z]+", text.lower().replace("_", " ")))
def cosine(a, b):
dot = sum(a[w] * b[w] for w in a)
norm = math.sqrt(sum(v * v for v in a.values()) * sum(v * v for v in b.values()))
return dot / norm if norm else 0.0
query = vec("written summaries style for Priya")
best = max(FACTS, key=lambda f: cosine(query, vec(" ".join(f))))
print("VECTOR :", " ".join(best))
# 3. Graph: follow relationships across several facts
edges = {}
for s, r, o in FACTS:
edges.setdefault(s, []).append((r, o))
def path(start, goal):
queue, seen = [(start, [start])], {start}
while queue:
node, trail = queue.pop(0)
if node == goal:
return trail
for relation, nxt in edges.get(node, []):
if nxt not in seen:
seen.add(nxt)
queue.append((nxt, trail + [f"-{relation}->", nxt]))
print("GRAPH :", " ".join(path("Priya", "Marco")))
Output:
SQL : ['short written summaries']
VECTOR : Priya prefers short written summaries
GRAPH : Priya -manages-> Atlas project -depends_on-> billing service -owned_by-> Marco
SQL returns an exact preference. The similarity search finds a relevant fact from loosely worded text; here, word counts stand in for a real embedding model, which would also match words that differ but mean the same. The graph walks from a person to a colleague through a project and a service, a question that no single stored sentence answers.
Relational and document stores
A relational database is the least glamorous choice and often the best first one. It gives you transactions, constraints, precise filters, joins, backups, access control and deletion that you can prove. Agent state such as task status, approvals and idempotency keys belongs here; a similarity score is no way to decide whether a payment was already sent.
Document databases suit records whose shape varies, such as tool results or evolving profiles. Key-value stores suit session state that is read by a single key and expires. Many relational databases also store JSON and provide full-text search, which covers a surprising amount of ground.
A practical memory record
| Column | Purpose |
|---|---|
| id, version | Reference, correction and citation |
| tenant, user or agent scope | Isolation |
| type | Preference, fact, event or procedure |
| subject and key | Finding and replacing the current value |
| content | The memory itself, short and self-contained |
| source and confidence | Trust decisions |
| created, effective, expires | Freshness and retention |
| status | Active, superseded or quarantined |
| embedding and model name | Meaning search, and knowing when to rebuild |
Vector databases for semantic memory
An embedding model turns text into a list of numbers so that similar meanings land near each other. A vector index finds the nearest stored items to a query. This is useful for recalling past conversations, similar cases or notes whose wording you cannot predict.
What it does badly
- Exactness. Codes, names and numbers may be missed or confused. Pair it with keyword search, as in Embeddings, Vector and Hybrid Search, Reranking.
- Negation and time. "I no longer eat meat" sits close to "I eat meat". Similarity does not know which is current.
- Aggregation. It cannot count or total.
- Guaranteed completeness. Approximate indexes trade some recall for speed.
Filtering matters
Memory searches almost always need a filter: this tenant, this user, not expired. With some approximate indexes the filter is applied after the index has returned candidates, so a selective filter can leave few results. The pgvector documentation gives the example of a condition matching ten percent of rows yielding about four results at the default search setting, and describes iterative index scans, partial indexes and partitioning as remedies. Whatever engine you use, test recall with your filters on.
Knowledge graphs for structured memory
A graph stores entities as nodes and relationships as edges. It makes multi-step questions natural, shows why things are connected and can attach dates and sources to each relationship, so that you can ask what was true at a given time. Some agent memory projects build such temporal graphs automatically from conversations.
The cost is in construction. Someone, or a model, must extract entities, decide that two names refer to one thing, choose relationship types and repair mistakes. A wrong edge looks authoritative. Start with a small set of relationship types that answer real questions, keep a link from every edge to its source, and read Building and Governing Knowledge Graphs before committing.
Two tables, one for entities and one for relationships, handle modest graphs and one or two hops well. Move to a dedicated engine when traversals become deep, frequent or hard to express.
Vector database or knowledge graph?
| Aspect | Vector index | Knowledge graph |
|---|---|---|
| Input effort | Low: embed text | High: extract and resolve entities |
| Query style | Similar to this | Connected to this, in these ways |
| Multi-step questions | Weak | Strong |
| Explaining a result | A similarity score and the text | The path of relationships |
| Updating a fact | Find and replace items | Change an edge, keeping history |
| Typical error | Plausible but irrelevant hit | Confident wrong link |
They combine well: use similarity to find the starting entities, then follow edges. GraphRAG and Hybrid Graph Retrieval applies the same idea to document retrieval.
When to use which
Open-source vector options
These are widely used choices. Licenses and features change, so confirm them on each project's own site before adopting one.
| Project | Shape | License family | Consider when |
|---|---|---|---|
| pgvector | PostgreSQL extension | PostgreSQL license | You already run PostgreSQL |
| Qdrant | Dedicated server | Apache 2.0 | Rich filtering and a focused engine |
| Milvus | Distributed system, lighter modes too | Apache 2.0 | Very large collections |
| Weaviate | Dedicated server | BSD 3-Clause core | Built-in hybrid search and modules |
| Chroma | Embedded or server | Apache 2.0 | Prototypes and smaller applications |
| LanceDB | Embedded, file based | Apache 2.0 | Local and data-lake style use |
| OpenSearch | Search engine | Apache 2.0 | Strong keyword search plus vectors |
| FAISS | Library, not a database | MIT | You build storage and filtering yourself |
Compare candidates with your own data: recall under your filters, latency at your load, write-to-searchable delay, deletion behavior, backup and restore, memory use and the skill your team has to operate it. Published benchmarks rarely match your filters and document sizes.
Sizing the vector part
Raw vector storage is easy to estimate: items multiplied by dimensions multiplied by bytes per value. One million memories at 1,536 dimensions in four-byte floats come to about 6.1 GB before index overhead and replicas. Shorter embeddings, half-precision or binary representations reduce this, with some loss of accuracy that you should measure. Most per-user memory is far smaller, and a search limited to one user's few thousand items can be exact and still fast, avoiding approximate-index surprises altogether.
Keeping several stores consistent
The moment a memory exists in two places, it can disagree with itself. Name one system of record, normally the relational or document store. Treat indexes and graphs as derived copies:
- Write the record and an outbox event in one transaction.
- A worker updates the vector index and graph, safely repeatable if retried.
- Recall fetches identifiers from the index, then reads current records from the system of record, which drops deleted or superseded items.
- Deletion removes the record first and verifies that derived copies follow.
- A periodic job compares counts and identifiers and repairs differences.
Record the embedding model and version with each vector. Changing models means embedding everything again, ideally into a new index that you switch to after testing.
A sensible starting point
A team starts with PostgreSQL: a memory table with scope, type, source and expiry, full-text search, and a vector column. Six weeks of logs show that missed recall comes mostly from outdated duplicates, which they fix with write rules and supersession, not a new database. A small relationship table later answers "who depends on this" questions. No second engine has yet been justified.
Operating a memory store
A store that works in a demonstration still has to be run. Decide these points before real users arrive, because changing them later usually means migrating data.
| Concern | Decision to make | How to test it |
|---|---|---|
| Access | Which service identities may read or write each scope | Attempt cross-scope reads and expect refusal |
| Encryption | At rest, in transit and for backups | Configuration checks in the pipeline |
| Backup and restore | How far back, and how fast to recover | Rehearse a restore and compare counts |
| Deletion in backups | How erased items stay erased after a restore | Replay the deletion log after restoring |
| Schema change | How records are versioned and migrated | Run old and new readers side by side |
| Capacity | Growth per user per month and index rebuild time | Load test with projected volume |
| Observability | Latency, empty results, write failures, lag to searchable | Alert on thresholds you can act on |
Two measurements deserve a place on the first dashboard. The first is the delay between writing a memory and being able to find it, since a user who corrects a fact expects the correction immediately. Reading very recent items from the system of record covers the gap while indexes catch up. The second is the number of recalls that return nothing, which may reveal a filter mistake, an embedding mismatch or a simple lack of useful writes.
Cost drivers
Memory cost comes from embedding calls on write and query, index memory, storage replicas and the extra model input created by whatever is recalled. The last is often the largest over time, because it is paid on every call. Short, self-contained memories and a strict limit on how many are recalled usually save more than switching database products.
Migrating later
If you do move to another engine, the single memory interface pays off. Write to both stores for a period, replay recorded queries against each, compare results and latency, then switch reads and retire the old copy after confirming that deletions reached both.
Common mistakes
- Storing everything as vectors, including balances and task status.
- No scope columns, so isolation depends on the query writer.
- Deleting a record but leaving its embedding searchable.
- Mixing embeddings from two models in one index.
- Building a graph before knowing which questions it must answer.
Checklist
- The memory questions are written down with examples.
- One store is named as the system of record.
- Records carry scope, type, source, dates and status.
- Recall is tested with real filters turned on.
- Deletion reaches every derived copy and is verified.
- Backups can restore a consistent state.
- A second engine is added only on measured need.
Frequently asked questions
Do I need a vector database for agent memory?
Not always. If memory is a handful of profile fields and recent events, ordinary queries are simpler and exact. Add meaning search when you cannot predict the wording of what must be found.
Can the context window replace a store?
It holds working material for one run. Anything that must survive sessions, be corrected or be deleted needs persistent storage.
Is a managed memory service a good idea?
It can save work. Check how you export data, delete it, isolate tenants and inspect why something was recalled before you rely on it.
Which store should hold conversation transcripts?
Keep raw transcripts in cheap storage with a retention period, and index short extracted memories or summaries that link back to them.
References and further reading
- pgvector: vector similarity search for PostgreSQL
- Qdrant documentation
- Milvus documentation
- Packer et al.: MemGPT, towards LLMs as operating systems
- Sumers et al.: Cognitive architectures for language agents
- Rasmussen et al.: Zep, a temporal knowledge graph for agent memory
Next steps
Memory Write, Recall and Forgetting Policies
Decide what gets written, recalled and removed.
Build and Evaluate a Memory Layer
Build a persistent layer and measure it.
Knowledge Graphs and Ontologies
Go further with entities and relationships.