SQLite FTS5 Agent Memory vs. Mem0: Setup, Benchmarks & Costs
Build a drop-in SQLite FTS5 agent memory store with read-only MCP tools, see why it beat Mem0 by 15 points on DolphinBench, and learn when to go hybrid.
A plain SQLite database with full-text search just outperformed dedicated memory stacks by a wide margin. In Hatchery's December 2, 2026 study, The Bitter Lesson for Agent Memory, author Arjun Kumar showed that an immutable raw-log SQLite FTS5 agent memory store scored 85.7% on DolphinBench for $4.73 total. Mem0 scored 70.7% at $96.21, while Supermemory reached 59.2%, sending the benchmark straight to the top of Hacker News with 287 points.
Key Takeaways
- Raw Logs Beat Upfront Extraction: Storing immutable event logs with SQLite FTS5 beat Mem0 by 15 percentage points on DolphinBench at roughly one-twentieth the cost.
- Minimal Three-Layer Schema: One append-only
eventstable, one trigger-syncedevents_ftsvirtual table, and two lightweight indexes cover most coding-agent workflows.- Query-Time Compression: Exposing three read-only tools lets frontier models run targeted BM25 and date queries instead of ingesting bloated top-k chunks every turn.
- Know the Lexical Limits: Exact token matching struggles with paraphrases, cross-lingual recall, and unpartitioned multi-million-row tables, where thin hybrid layers help.
Why Pre-Consolidation Memory Frameworks Pay a Hidden Tax
Pre-consolidation memory frameworks charge a steep hidden tax because they force an LLM to guess which details will matter long before any future query exists. Every turn triggers extraction prompts, graph updates, or rolling summaries that quietly strip away exact wording, timestamps, and tool arguments.
Hatchery's December 2026 analysis evaluated this tradeoff on the DolphinBench agent memory benchmark, an Apache-2.0 suite created by Mem0. DolphinBench measures history-dependent execution across 600 tool-using tasks, three user personas, and roughly 500,000 tokens of dated event history per user.
| Memory Architecture | DolphinBench Accuracy | Total Benchmark Cost | Write-Time Consolidation |
|---|---|---|---|
| Immutable Raw-Log SQLite + FTS5 | 85.7% | $4.73 | None (append-only) |
| Mem0 | 70.7% | $96.21 | Per-turn fact extraction |
| Supermemory | 59.2% | Not reported in study | Managed memory indexing |
When a task asks for an exact parameter from three weeks ago or a subtle constraint buried inside a tool output, summarized memory often returns a blurred paraphrase. An append-only log preserves the original ground truth so the model can inspect the exact record on demand.
The study also tested idle-time consolidation, often called "dreaming," where background passes synthesize raw logs into structured notes. While background consolidation helped smaller models cope with long histories, it flattened or slightly regressed accuracy on frontier models that can already reason directly over raw evidence.
The Three-Layer Minimalist Agent Memory Schema in SQLite
A production-grade SQLite FTS5 agent memory store requires three database layers: an append-only events table, a trigger-synced events_fts virtual table, and lightweight time and session indexes. Keeping the entire store inside one local file removes external network hops and keeps backups trivial.
Before creating tables, configure WAL mode and sane busy timeouts so concurrent agent reads never collide with incoming event writes. The official SQLite FTS5 documentation recommends external-content virtual tables when you want full-text search without duplicating the raw text payload on disk.
-- schema.sql
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA busy_timeout = 5000;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
user_id TEXT NOT NULL,
role TEXT NOT NULL,
tool_name TEXT NOT NULL DEFAULT '',
content TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);
CREATE INDEX IF NOT EXISTS idx_events_user_time
ON events (user_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_events_session_id
ON events (session_id, id);
CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(
content,
role,
tool_name,
content='events',
content_rowid='id',
tokenize='unicode61'
);
CREATE TRIGGER IF NOT EXISTS events_ai AFTER INSERT ON events BEGIN
INSERT INTO events_fts(rowid, content, role, tool_name)
VALUES (new.id, new.content, new.role, new.tool_name);
END;
CREATE TRIGGER IF NOT EXISTS events_ad AFTER DELETE ON events BEGIN
INSERT INTO events_fts(events_fts, rowid, content, role, tool_name)
VALUES ('delete', old.id, old.content, old.role, old.tool_name);
END;
CREATE TRIGGER IF NOT EXISTS events_au AFTER UPDATE ON events BEGIN
INSERT INTO events_fts(events_fts, rowid, content, role, tool_name)
VALUES ('delete', old.id, old.content, old.role, old.tool_name);
INSERT INTO events_fts(rowid, content, role, tool_name)
VALUES (new.id, new.content, new.role, new.tool_name);
END;Save this file as schema.sql and initialize your database once; every subsequent insert into events updates the full-text index atomically inside the same transaction.
Ranking and Extracting Compact Evidence With BM25
Returning entire historical messages floods an agent's context window fast. Instead, combine SQLite's built-in bm25() scorer with snippet() so your search query returns short, highlighted excerpts ranked by lexical relevance.
SELECT
e.id,
e.session_id,
e.role,
e.created_at,
snippet(events_fts, 0, '[', ']', '...', 24) AS excerpt,
bm25(events_fts, 1.0, 0.2, 0.5) AS score
FROM events_fts
JOIN events e ON e.id = events_fts.rowid
WHERE events_fts MATCH ?
AND e.user_id = ?
AND e.created_at >= ?
ORDER BY score ASC
LIMIT 10;The three weights inside bm25() prioritize matches in content first, tool_name second, and role third, while snippet() caps each preview at 24 tokens.
Pro Tip
In SQLite FTS5,
bm25()returns negative numbers where more negative values represent stronger matches. Always sort withORDER BY score ASCso the best evidence lands at the top.
Exposing Read-Only SQL and FTS5 Tools to Your Coding Agent
Exposing three narrow, read-only tools lets your agent investigate memory actively instead of passively absorbing injected vector chunks on every turn. Each tool enforces strict row and character budgets so a broad query can never blow up the prompt.
search_memory: Runs FTS5MATCHqueries with optional date filters and returns compact BM25-ranked snippets.get_event_window: Fetches a small slice of surrounding rows around a specificevent_idwhen the agent needs full conversational context.query_events_sql: Executes validated read-onlySELECTqueries for counts, date ranges, or tool-call audits.
The TypeScript helper below wraps memory.db using a dedicated read-only connection with PRAGMA query_only = ON and hard output caps.
import Database from "better-sqlite3";
const db = new Database("./memory.db", { readonly: true, fileMustExist: true });
db.pragma("query_only = ON");
db.pragma("busy_timeout = 3000");
export function search_memory(args: {
userId: string;
query: string;
since?: string;
limit?: number;
}) {
const cap = Math.min(Math.max(args.limit ?? 10, 1), 20);
return db
.prepare(
`SELECT e.id, e.session_id, e.role, e.created_at,
snippet(events_fts, 0, '[', ']', '...', 24) AS excerpt,
bm25(events_fts, 1.0, 0.2, 0.5) AS score
FROM events_fts
JOIN events e ON e.id = events_fts.rowid
WHERE events_fts MATCH ? AND e.user_id = ? AND e.created_at >= ?
ORDER BY score ASC LIMIT ?`
)
.all(args.query, args.userId, args.since ?? "1970-01-01", cap);
}
export function get_event_window(args: {
sessionId: string;
centerId: number;
radius?: number;
}) {
const r = Math.min(Math.max(args.radius ?? 3, 1), 10);
return db
.prepare(
`SELECT id, role, tool_name, created_at, substr(content, 1, 600) AS content
FROM events
WHERE session_id = ? AND id BETWEEN ? AND ?
ORDER BY id ASC`
)
.all(args.sessionId, args.centerId - r, args.centerId + r);
}
export function query_events_sql(sql: string) {
const clean = sql.trim().replace(/;+$/, "");
if (!/^\s*(SELECT|WITH)\b/i.test(clean) || clean.includes(";")) {
throw new Error("Only single read-only SELECT statements are permitted.");
}
const rows = db.prepare(clean).all().slice(0, 25);
const serialized = JSON.stringify(rows);
return serialized.length > 6000 ? `${serialized.slice(0, 6000)}...` : serialized;
}Even if a model writes an overly broad filter, the read-only pragma blocks mutations at the SQLite engine level while the 25-row and 6,000-character guards protect your context budget.
Wrapping the Store as a Local MCP Server
Registering these three functions behind a tiny stdio MCP server makes the same memory.db file immediately available to Claude Code or any MCP-compatible harness. Add a project-level entry in .mcp.json to wire the reader in seconds.
{
"mcpServers": {
"agent-memory": {
"command": "node",
"args": ["./scripts/memory-mcp-server.js", "./memory.db"]
}
}
}Keeping the tool schema lean matters because every extra MCP tool definition consumes prompt tokens on every turn. For tighter server setups and token budgets, see our guide to the Best MCP Servers for Claude Code: Lean Setup & Token Tradeoffs, or compare local harness workflows in Cursor vs. Windsurf vs. Claude Code: 2026 Pricing & Setup Guide.
This pattern shifts compression to query time. Rather than stuffing top-k vector matches into every prompt whether the agent needs them or not, the model fires two or three targeted lexical or date queries only when historical evidence is actually required.
Cost, Latency, and Token Tradeoffs: SQLite FTS5 vs. Mem0 and Vector DBs
Deferring memory work from write time to query time strips out per-turn extraction calls, embedding API bills, and separate vector hosting. Most engineering teams overlook how fast write-time LLM calls compound across long sessions with hundreds of tool outputs.
| Dimension | SQLite + FTS5 Raw Log | Mem0 / Extraction Frameworks | Standalone Vector DB |
|---|---|---|---|
| Write-time LLM cost | Zero (plain SQL insert) | High ($96.21 on DolphinBench) | Embedding API per chunk |
| Query-time cost | $4.73 total on DolphinBench | Lower per read, high upfront tax | Embedding + top-k token injection |
| Infrastructure footprint | Single local .db file |
Hosted service or self-hosted stack | Separate vector service + sync pipeline |
| Evidence fidelity | Verbatim raw events | Summarized or extracted facts | Chunked text, often missing context |
| Benefit from stronger LLMs | Improves automatically | Limited by past lossy extractions | Limited by chunking and embedding quality |
This asymmetry captures the bitter lesson for agent memory. Every time frontier models become better at formulating search queries and token costs decline, an untouched raw log gets more accurate with zero re-indexing.
Pre-extracted memory stores face the opposite trajectory. When a stronger model ships, your old extracted facts remain frozen at the reasoning quality of whichever smaller or older model wrote them.
If you want to verify these numbers against your own prompts before migrating, clone DolphinBench and run its 600-task, three-persona evaluation harness. Track both task pass rate and combined write-plus-read token spend per task so write-time extraction fees cannot hide outside your retrieval metrics.
When Raw SQLite FTS5 Breaks Down (And Hybrid Fixes)
Pure lexical retrieval is fast, cheap, and lossless, yet exact token matching has predictable blind spots. Teams evaluating SQLite alternatives to Mem0 should map these failure modes upfront before rolling raw FTS5 into every environment.
- Synonym and paraphrase mismatches: Querying for "billing outage" misses an event logged as "Stripe webhook 502 error" because the two strings share no lexical tokens.
- Cross-lingual recall: The
unicode61tokenizer indexes terms cleanly across scripts, yet an English query still cannot retrieve a note originally written in Spanish or Japanese. - Multi-million-row latency: A single unpartitioned FTS5 table slows down once multi-tenant histories grow into millions of rows without date partitioning or archival rollups.
Thin Hybrid Upgrades Without Lossy Extraction
You can close most lexical gaps without sliding back into expensive per-turn summarization. Start with zero-infrastructure LLM query expansion: instruct the agent to issue two or three parallel FTS5 queries using domain synonyms or OR clauses whenever a first search comes up empty.
If paraphrase recall or cross-lingual search remains a recurring requirement, add a thin embedding sidecar that points directly back to events.id. Combine BM25 candidates with semantic candidates at query time while keeping the append-only events table as the single source of truth.
Watch Out
When adding semantic fallback, embed raw event windows rather than LLM-rewritten summaries. Reintroducing lossy write-time extraction brings back both the accuracy drop and the per-turn token tax.
Solo Coding Agents vs. Multi-Tenant SaaS Agents
Use this quick checklist to pick the right AI agent memory architecture for your workload:
- Solo coding agents and local workflows: Ship raw SQLite + FTS5 in WAL mode with read-only MCP tools. One local file handles years of developer sessions with zero external services.
- Small team internal bots: Keep raw SQLite + FTS5 with strict
user_idscoping and prompt-level query expansion, then benchmark on your real logs before adding vectors. - Multi-tenant production SaaS agents: Preserve the append-only raw event log, partition histories by tenant or date window, and add a semantic sidecar only for cross-lingual or paraphrase-heavy workloads.
Frequently Asked Questions
Why Did Raw SQLite FTS5 Outperform Mem0 on DolphinBench?
On DolphinBench, an immutable raw-log SQLite FTS5 store scored 85.7% at $4.73 compared to Mem0's 70.7% at $96.21 because it preserved verbatim history instead of summarizing turns upfront. Frontier models can search exact timestamps, tool outputs, and wording at query time without losing task-critical nuance during write-time extraction.
How Do You Prevent SQLite FTS5 Queries From Flooding an AI Agent's Context Window?
Use snippet() and bm25() in search_memory so initial searches return short, ranked excerpts instead of full rows. Pair that with hard LIMIT clauses, character truncation in query_events_sql, and a narrow get_event_window tool that fetches full surrounding messages only around confirmed hits.
When Do You Still Need a Vector Database or Semantic Search Alongside SQLite FTS5?
Semantic search becomes necessary when users frequently retrieve memories via loose paraphrases, synonyms, or different languages than the original log entry. Even then, pairing a thin embedding layer with an append-only raw event table avoids the accuracy loss of write-time summarization.
Can You Connect a Local SQLite FTS5 Event Log to Claude Code via MCP?
Yes. Wrap a read-only SQLite connection (PRAGMA query_only = ON) in a lightweight stdio MCP server exposing search_memory, get_event_window, and query_events_sql, then register it in your project's .mcp.json file so Claude Code can query past sessions on demand.
Engineering workflows, AI coding tools, and developer guides published on DuneBook.