Arc Labs
BrainDocsPricing
GitHubSign inGet Started
Blogpost

Lessons from building Brain in Rust

Arc Labs·April 28, 2026·5 min read

We built Brain's core in Rust. This is a blunt account of why, what worked, and what we'd reconsider.

Why Rust

Two properties drove the choice:

  • Predictable latency. Memory retrieval sits on the critical path of every agent turn. Garbage-collected runtimes introduce p99 spikes that compound across a multi-retriever fan-out. Rust's deterministic deallocation gives us flat tail latency.
  • Zero-copy serialization. Vectors are large; copying them between layers adds up. Rust's ownership model lets us pass references through the pipeline without paying for serialization at every stage.

rkyv + bytemuck give us zero-copy storage

Brain runs its own storage engine — a memory-mapped vector arena, a write-ahead log with group-commit fsync, and a redb B-tree for metadata — not an external database. Records serialize with rkyv and cast with bytemuck, so hot reads deref straight out of the mmap with no deserialization copy. CRC32C on every WAL record and arena slot catches corruption at read time and fails stop.

The HNSW implementation decision

We considered four options for approximate nearest-neighbor search:

  1. Pure Rust, in-process (hnsw_rs, usearch): maximum control, we maintain the index ourselves
  2. pgvector: Postgres extension, mature, SQL-compatible, but couples us to Postgres ops
  3. Qdrant: dedicated vector database, fast, but adds a network boundary and a separate service
  4. Weaviate/Pinecone: managed services, adds latency and external dependency

We chose the pure-Rust, in-RAM index (hnsw_rs). The reasoning:

Durability is our own, not the index's. The write path makes decisions (deduplicate, supersede, persist) that must be atomic. We get that from Brain's own write path: single-writer-per-shard plus WAL-before-acknowledge — nothing returns success until its WAL record is fsynced, and recovery replays the log. That means we don't need a SQL transaction boundary around the vector store, so the vector index can live in RAM purely for speed.

Keeping HNSW in the process removes the network boundary. An external vector DB (pgvector or Qdrant) puts a socket, serialization, and a separate failure domain between the retriever and the index. An in-process hnsw_rs index in each shard is a function call.

Operational simplicity: there is no second service to run, scale, or back up. The whole shard — arena, WAL, redb, HNSW, tantivy — is one process with one data directory.

We scale by sharding (thread-per-core Glommio executors, each owning its own indexes), not by moving the embedding layer to an external vector database. Adding capacity means adding shards, not adopting a new storage system.

redb and typed, zero-copy metadata access

There's no SQL anywhere in Brain. Metadata lives in redb, an embedded B-tree, and records are serialized with rkyv — so instead of a query language verified against a live database, we get typed table access verified by the Rust compiler. It matters particularly for a system where the schema evolves alongside the pipeline.

Here's what it looks like in practice:

// The table's key/value types are part of its definition, so a
// mismatched key or a wrong value type fails to compile — no query
// string to get wrong, no column names to typo.
const MEMORIES: TableDefinition<MemoryKey, &[u8]> = TableDefinition::new("memories");

let read_txn = db.begin_read()?;
let table = read_txn.open_table(MEMORIES)?;

let mut memories = Vec::new();
for entry in table.range(MemoryKey::user_prefix(user_id))? {
    let (_, bytes) = entry?;
    // Zero-copy: deref straight out of the mmap, no deserialization.
    let row = rkyv::access::<ArchivedMemoryRow, _>(bytes.value())?;
    if row.valid_until.is_none() {
        memories.push(row);
    }
    if memories.len() == limit { break; }
}

The table's key and value types are baked into the TableDefinition, so a mismatched key type or a wrong value type is a compile error — there is no query string to get wrong and no column names to typo. Ordering, tombstone (valid_until) filtering, and confidence ranking are plain Rust over the archived struct, which the borrow checker also checks. Because reads deref straight out of the memory-mapped file via rkyv, there's no deserialization copy on the hot path.

The trade-off versus a SQL engine: we write the range scans and filters ourselves instead of leaning on a planner. In exchange we get an embedded store with no separate service, no DATABASE_URL, no migrations tool, and no live database required at build time — the schema is Rust types, checked at cargo build.

Ownership model and concurrent retrieval

The retriever fan-out is the critical performance path, and Rust's ownership model makes writing it safely straightforward:

pub async fn retrieve(&self, query: &ParsedQuery) -> Result<Vec<RankedMemory>> {
    let (semantic, bm25, entity_graph, temporal, type_filter) = tokio::join!(
        self.semantic_retriever.retrieve(query),
        self.bm25_retriever.retrieve(query),
        self.entity_graph_retriever.retrieve(query),
        self.temporal_retriever.retrieve(query),
        self.type_filter_retriever.retrieve(query),
    );

    // All five complete; now fuse with RRF
    let candidates = merge_results([semantic?, bm25?, entity_graph?, temporal?, type_filter?]);
    Ok(self.rrf_fuse(candidates))
}

Each retriever holds a cheap handle to the shard's in-RAM indexes — the HNSW graph, the tantivy reader, the redb snapshot — read through ArcSwap so readers never block the single writer. The compiler verifies the ownership discipline: the borrow checker enforces at compile time what would be a runtime concern (and a code-review comment) in Python or Go.

Because the indexes live in the process and reads are lock-free (ArcSwap + epoch reclamation), all the lanes run concurrently against the same snapshot with no explicit synchronization code and no connection pool to contend on. The result: genuinely parallel retrieval with no locking ceremony on our side.

One subtlety: tokio::join! waits for the slowest lane, not the sum of all of them. Since the vector lane is normally the slowest, the fan-out tail is that lane's tail plus fusion overhead. This is the right model for retrieval — the bottleneck determines the tail, not the accumulation.

Linux only, on purpose

The storage engine is built on io_uring, O_DIRECT, madvise(MADV_RANDOM | MADV_DONTDUMP) and fallocate(FALLOC_FL_KEEP_SIZE). That makes Linux (kernel 5.15 or newer) a hard requirement rather than a default — macOS and Windows are not supported targets, and development on those hosts happens in the container.

This was a real decision and not an oversight. Abstracting those facilities would either leak platform differences into tail latency or bloat the codebase with parallel backends, and for a system whose value proposition is latency, one optimized backend wins. The cost is a narrower set of places Brain can run; the benefit is that the fast path has no portability layer in it.

What we'd reconsider

Async story is heavier than it needs to be

The Rust async ecosystem is great in production but heavyweight to learn. Send bounds, lifetime gymnastics inside async fn, and the runtime split cost new contributors real setup time.

Error type design needs more discipline

Rust's Result<T, E> is wonderful — until you have ten error types and every boundary between layers requires explicit conversions. We've consolidated to a single BrainError enum at the public API; internally, thiserror keeps things readable.

Would we pick Rust again? Yes — but knowing the costs. The right rule of thumb: pick Rust when the workload is latency-critical and when the team has at least one Rust-experienced senior. Pick Go or TypeScript for everything else.

Closing

Rust is the right call for the core of an agent memory system. The investment compounds: predictable latency, fewer 3am pages. The investment is real: longer ramp time, more careful API design, more discipline around error types and async shapes.

The specific wins — flat p99 tail latency, zero-copy vector reads straight out of the mmap arena, thread-safety guarantees enforced by the borrow checker, CRC-checked fail-stop storage integrity — are not things you can retrofit onto a Go or Python codebase later. They emerge from the ownership model at every layer of the architecture. If you're building something where those properties matter, the ramp cost is worth paying. If you're prototyping or working on a batch job, pick the language your team already knows.

The core is open source. Read the code.

Updates from the lab.

Engineering notes, research drops, occasional product updates. Roughly monthly.

Arc Labs

Cognitive infrastructure for AI agents. Open core in Rust. Composable primitives you own.

GitHubX / TwitterDiscussions

Brain

  • Memory Layer
  • Documentation
  • Pricing
  • Changelog
  • Status

Developers

  • Start here
  • TypeScript SDK
  • Python SDK
  • Rust SDK
  • MCP Server

Company

  • About
  • Careers
  • Blog
  • Security
  • Contact
Encode"Priya lives in Berlin."mem_7f3a · storedRecall"where does Priya live?"→ BerlinSupersede"Priya moved to Lisbon."mem_9c21 ⊃ mem_7f3aBerlin→ LisbonARC LABSARC LABSARC LABS
© 2026 ARC LABS · BANGALOREPrivacyTermsDPAApache 2.0