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.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Beginner Three ways to remember

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 shapeExampleNatural store
Exact lookupWhat is this user's preferred language?Relational or key-value
Filtered list or countOpen tasks assigned this weekRelational
Current state of a jobWhich step is the refund workflow on?Relational or document
Loose recall by meaningHave we discussed something like this before?Vector search
Exact words and codesFind the note mentioning error E-4042Full-text search
Chains of relationshipsWho owns the service my project depends on?Graph
Large raw recordsThe full transcript from MarchObject 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.

Agentasks to remember, recall, correct or forget
Memory interfacescope, policy, provenance, deletion
Relational or documentfacts and state: source of truth
Vector indexsearch by meaning: rebuildable
Graphrelationships: derived or curated
Put one interface in front, so that stores can change without changing the agent.
Intermediate Strengths, limits and record design

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

ColumnPurpose
id, versionReference, correction and citation
tenant, user or agent scopeIsolation
typePreference, fact, event or procedure
subject and keyFinding and replacing the current value
contentThe memory itself, short and self-contained
source and confidenceTrust decisions
created, effective, expiresFreshness and retention
statusActive, superseded or quarantined
embedding and model nameMeaning 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.

A graph does not require a graph database

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?

AspectVector indexKnowledge graph
Input effortLow: embed textHigh: extract and resolve entities
Query styleSimilar to thisConnected to this, in these ways
Multi-step questionsWeakStrong
Explaining a resultA similarity score and the textThe path of relationships
Updating a factFind and replace itemsChange an edge, keeping history
Typical errorPlausible but irrelevant hitConfident 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.

Expert Choosing products and running them

When to use which

Must it be exact, updated or audited?yes: relational or document table first
Must it be found by loose wording?yes: add an embedding column or vector index
Do answers chain several relationships?yes: add graph tables or a graph engine
Is the item large and rarely read?yes: object storage with a short summary indexed
Add capability only when a real question requires it.

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.

ProjectShapeLicense familyConsider when
pgvectorPostgreSQL extensionPostgreSQL licenseYou already run PostgreSQL
QdrantDedicated serverApache 2.0Rich filtering and a focused engine
MilvusDistributed system, lighter modes tooApache 2.0Very large collections
WeaviateDedicated serverBSD 3-Clause coreBuilt-in hybrid search and modules
ChromaEmbedded or serverApache 2.0Prototypes and smaller applications
LanceDBEmbedded, file basedApache 2.0Local and data-lake style use
OpenSearchSearch engineApache 2.0Strong keyword search plus vectors
FAISSLibrary, not a databaseMITYou 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:

  1. Write the record and an outbox event in one transaction.
  2. A worker updates the vector index and graph, safely repeatable if retried.
  3. Recall fetches identifiers from the index, then reads current records from the system of record, which drops deleted or superseded items.
  4. Deletion removes the record first and verifies that derived copies follow.
  5. 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

Illustrative example: a project assistant

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.

ConcernDecision to makeHow to test it
AccessWhich service identities may read or write each scopeAttempt cross-scope reads and expect refusal
EncryptionAt rest, in transit and for backupsConfiguration checks in the pipeline
Backup and restoreHow far back, and how fast to recoverRehearse a restore and compare counts
Deletion in backupsHow erased items stay erased after a restoreReplay the deletion log after restoring
Schema changeHow records are versioned and migratedRun old and new readers side by side
CapacityGrowth per user per month and index rebuild timeLoad test with projected volume
ObservabilityLatency, empty results, write failures, lag to searchableAlert 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

Next steps