Architecture
Brain is one Rust binary with a strict one-way crate graph — an mmap arena, a WAL, redb, HNSW, tantivy, and bundled models, sharded thread-per-core. No external database.
The single rule that governs every change: dependencies flow downward, never sideways. brain-core has zero I/O dependencies. The write path (brain-ops) depends on storage, metadata, index, and the embed/rerank/llm helpers. The server binary depends on the write and read paths. There is no path from a leaf back up to a binary, and the extraction crates (brain-extractors, brain-llm) are never depended on at the wire or storage layer.
The one-process picture
Brain ships as one binary, brain-server, in one Docker image (brain). There is no Postgres, no pgvector, no Neo4j, no external cache — each process owns its own storage. The connection layer runs on Tokio and accepts TCP; every request is routed to one of N shards. Each shard runs a Glommio executor (thread-per-core, io_uring) and owns the full per-shard state from byte zero.
Parallelism is sharding, not a thread pool. Adding cores means adding shards; each shard is single-writer, so writes take no locks and reads use ArcSwap + crossbeam-epoch. Per-shard types are deliberately !Send — the discipline is what makes the lock-free path sound.
The concurrency model, and why it's shaped this way
"Shard-per-core" is a conclusion, not a starting point. The starting point is a pair of priorities that most of the design falls out of.
Avoid contention rather than synchronise it. The levers, in order of preference: single-writer-per-shard removes writer-vs-writer contention entirely; sharding partitions the workload so any remaining contention is local; lock-free reads keep readers off the writer's mutable state. Atomics are the fallback for the rare genuinely-shared counter, and locks are close to a last resort.
Predictable latency over peak throughput. A p99 of 25 ms at 5K RPS is preferred to a p99 of 100 ms at 10K. That single preference rules out a whole family of standard optimisations — aggressive batching that delays small requests to fill a batch, and any resource sharing that produces contention spikes.
Four mechanisms implement it:
Cooperative schedulingone thread per shardEvery task on a shard shares one thread and yields at await points. No OS context switches, no preemption. Long synchronous stretches are rare, and where they exist they yield explicitly to stay fair.
Immutable reader viewssnapshots, not locksA read transaction is a consistent snapshot; an ArcSwap load is a stable
reference whose underlying data will not change. The writer may be mutating
— the reader's particular view is frozen.
Atomic publicationno half-statesNew state is built elsewhere, then published with one atomic swap. Readers from before the swap continue on the old view; readers after it see the new one. There is never a partially-published state to observe.
Deferred reclamationepoch-basedSuperseded state isn't freed immediately — it's freed once no reader holds a reference, via refcounting or epoch-based reclamation. Use-after-free without taking a lock.
Shards share no mutable state at all. They communicate by cross-executor calls in-process, or over the wire out of it — so one shard's contention is invisible to another, and a slow shard degrades its own tail latency rather than the cluster's.
This is the trade worth being explicit about: Brain spends throughput to buy tail-latency predictability. If your workload is a nightly bulk import where only total wall-clock matters, that trade is the wrong way round — and the batched encode path exists precisely so you can opt back out of it for that case.
What each shard owns
| Subsystem | Backed by | Holds |
|---|---|---|
| Vector arena | mmap file (brain-storage) | 384-dim f32 vectors in fixed 1600-byte slots |
| WAL | pwritev + fdatasync group commit | The durability barrier — no ack before fsync |
| Metadata | redb B-tree (brain-metadata) | Memory rows, entities, statements, relations, predicates, audit |
| Vector search | HNSW in RAM (hnsw_rs) | Three indexes: memory, entity, statement |
| Lexical search | tantivy | Two indexes: memory text, statement text |
| Embeddings | BGE-small via candle | Text → 384-dim vector, in-process |
| Rerank | cross-encoder (bge-reranker-base) | Read-time reordering — not in the published image, off by default |
| Extraction cache | separate redb | LLM extractor cache |
There is no dimension-1536 vector column and no vector() type anywhere — vectors live in the arena as raw bytes; the metadata store is redb, not SQL.
Sizing follows from that table rather than from guesswork. A slot is fixed at 1600 bytes, so a million memories is ~1.5 GiB of arena; add the HNSW graphs, redb and the text indexes and a working shard is around 2.5 GiB per million memories, or roughly 20 GiB per million at production retention once daily snapshots are kept. A node serving a hundred shards sits near 20 GiB resident at warm steady state, which is why a 64 GiB commodity box is the reference tier rather than an aspiration.
What a shard is, on disk
A shard is not an abstraction — it is a directory, and knowing its shape makes backup, sizing and recovery concrete:
data/
└── <shard_uuid>/
├── arena.bin # the vector arena, 1600 bytes per slot
├── wal/
│ ├── segment-00001.bin
│ └── segment-00002.bin # …
├── metadata.redb # memories, entities, statements, relations, audit
└── hnsw_snapshot.bin # optional — speeds restart, rebuildableListing the data directory lists your shards. Alongside those files a shard owns in-memory state (the arena's mmap, the HNSW graphs, the cue cache, the writer's pending state) and running tasks (its Glommio executor, its single writer, its background workers, and its connection handlers).
Routing is arithmetic rather than lookup: a space maps to a shard by
hash(space_id) % shard_count, and a MemoryId carries a 16-bit shard id in
its high bits — so finding the shard that owns a memory is a bit extraction,
not an index read. The durable identity on disk is a UUID, which is what lets
the runtime id be reassigned without rewriting data.
One node today, the shape for more later
Today every shard lives in one process, separated by code-level isolation and one executor per core. The wire protocol and the identifiers already reserve room for shards on different machines with networked cross-shard calls — so clustering is a later version rather than a different architecture, and nothing in the client contract changes when it lands.
The practical consequence now: a shard is the unit of scaling, and the recommended range is 1–10M memories each. Past that, TLB pressure on the arena starts to matter and the answer is more shards, not bigger ones.
The crate graph
The workspace ships exactly these crates. Adding one requires justification in the commit message.
| Crate | Role |
|---|---|
brain-core | Shared types — MemoryId, EntityId, StatementId, EdgeKind, Error. Zero I/O deps. |
brain-protocol | Wire protocol — frame, opcodes, CBOR codec, schema DSL parser. |
brain-storage | mmap arena + WAL + recovery. The only crate allowed unsafe (for mmap). |
brain-metadata | redb wrapper — memory / entity / statement / relation / predicate / audit tables. |
brain-index | HNSW (memory + entity + statement) and tantivy integration. |
brain-embed | BGE-small embedding service (candle, 384-dim). |
brain-rerank | Cross-encoder reranker (bge-reranker-base) for the read path. |
brain-planner | Query planner + executor — the read pipeline (recall / plan / reason). |
brain-ops | The one write path: handlers/ per opcode → apply/ per table → writer/submit, plus the retrievers and extractor writes. |
brain-workers | Background workers — auto-edge, temporal-edge, extractor, decay, consolidation, HNSW maintenance, and the rest. |
brain-extractors | Pattern + classifier extractor tiers. |
brain-llm | LLM client + cache + budget (the LLM extractor tier and write-time HyPE). |
brain-plugins | Plugin surface (enricher + connector) for the knowledge layer. |
brain-http | HTTP transport for the operator admin listener. |
brain-server (bin) | The server binary — wires everything together. |
This repo ships the server only. There is no first-party SDK or CLI here; clients speak the wire protocol directly or via the sibling SDK packages. Operators administer over the HTTP edge (brain-http).
The one write path
There is one Write { phases } model, one writer (submit), and one apply layer that dispatches every phase variant. Capabilities differ by which state they touch — memories, entities, statements, relations, edges, schema, audit — not by which "layer" they belong to. A write that references a declared type is accepted; one that references an undeclared type is rejected (explicit create) or dropped (extractor best-effort). The seeded brain: system namespace is active from byte zero, so every shard always has a schema present.
See Write pipeline for the phase-by-phase walk.
Boot requirements
Two things are mandatory at startup, and the shard refuses to spawn without them:
- A credential broker. Write-time HyPE (hypothetical-question generation) and the LLM extractor tier depend on an LLM, but the serving credential belongs to a namespace and is not known until a write names one. So the shard gates on
[llm.broker]—urlplusservice_key, which is Brain's identity to the broker and not a provider key.[llm] api_keyis not a substitute. The check is configuration-only, so the broker must be configured, not reachable. A namespace with no registered provider key is a separate, non-fatal matter: its writes still land, with the LLM tier reporting it could not run. - The bundled models. The embedder (BGE-small) and the classifier (GLiNER) are hard boot requirements. A capability that fails to load at shard spawn is a hard spawn failure (
ShardError::*InitFailed) — the shard refuses to start rather than run with a quietly-missing capability.
The one thing you can turn off at deploy time is the cross-encoder reranker ([rerank] enabled) — and it is off by default, with no cross-encoder model in the published image. Disabled, no model loads and the read pipeline returns RRF-only ordering; enabled without a model on disk is a hard spawn failure rather than a silent downgrade. Everything else on the write and read paths is always-on by design — a write step that populated the graph could not be a toggle without silently breaking graph-backed reads. See Policies for the full enable/disable model.
Module rules in one breath
brain-corehas no I/O — no runtime, no storage, no network.- Shards use Glommio; the connection layer uses Tokio. Never mix them: no Tokio inside a shard, no
tokio::fsin shard code, no thread pool for parallel work. - Per-shard types are
!Send. Don't addSend + Syncto them. - No lock held across
.await; no allocation in the encode/recall hot path. thiserrorin libraries,anyhowin binaries. No.unwrap()outside tests.unsafeonly inbrain-storage, only for mmap, always with a// SAFETY:comment.
Those are not style preferences. Each one is load-bearing for a property above:
the Glommio/Tokio separation is what keeps the shard's cooperative scheduling
sound; !Send is what makes the lock-free read path checkable by the compiler
rather than by review; no-lock-across-await is what prevents a yield from
turning a fast path into a stall; and confining unsafe to one crate is what
makes the mmap invariants auditable in one place.
Was this page helpful?
Concepts
Mental models for Brain — typed memory, the write/read pipelines, identity-by-key, the entity graph, and the single-binary architecture.
Write pipeline
How encode works — a synchronous fast path (validate → embed → reserve → persist) split from asynchronous derivation by the WAL-fsync acknowledgement barrier.