Architecture
MLambda.Data is layers of actors on MLambda.Actor. Each layer is a folder of MLambda.Data/src.
Layer overview
| Layer | Folder | What it holds |
|---|---|---|
| API | Api/, Auth/ |
REST routes, live channels, tokens, users and permissions |
| ORM | Orm/ |
Entities, repositories, specifications, replicated repositories |
| Distributed | Distributed/ |
The ring, replicas, the coordinator |
| Engine | Engine/ |
The engine, tables’ stores, the query planner, joins |
| Table | Table/ |
Schemas, builders, constraints, evolution, the schema registry |
| Index | Index/ |
B-tree, hash, bloom and inverted indexes |
| Storage | Storage/ |
Write-ahead log, memtable, SSTables, compaction, snapshots, the manifest |
| Filesystem | Filesystem/ |
Namespaces, files and blocks |
| Format | Format/ |
Columns and the binary codecs |
| Management | Management/ |
Failure kinds, guardians, the compaction breaker |
Engine layer
The DataEngine (route engine) routes each request to its table’s TableStore (store/{database}/{table}),
made on first use under the engine’s data root. A write or a read is forwarded with the asker’s own reply, so the
engine never waits on a store: a new store learns its table’s newest stamp from a fiber, and what comes for that table
meanwhile waits in order (every other table goes on).
A table opens on a background thread (System.Background): its log replayed and its tables read never hold the
process’s one fiber thread. What comes meanwhile is stashed and taken back in order. A table unused for
MLAMBDA_IDLE_MS (five minutes) is flushed and closed, and opens again at its next message; a table whose open failed
is tried again after a wait (1 s, doubling to a minute). EngineStop flushes and closes every table.
Write path
- The store appends the write to the log and syncs it. Writes that arrive together share one sync: a batch is committed at 64 rows or 2 ms after its first, whichever comes first.
- The write goes into the memtable, and the table’s indexes change.
- Past its size (4 MiB by default) the memtable is written out as a new SSTable (with a bloom filter of its keys), the table’s index file is written, and the log is emptied.
- When a size tier is due, the store asks the process’s compactions for a permit (at most two merges at once, paced by the breaker) and the merge runs on a background thread, streaming its inputs block by block; the store keeps answering and swaps the merged table in when it is done.
Read path
- The memtable, newest first.
- Each SSTable, newest first, skipped when its bloom block says the key is not there.
- The newest item wins; a tombstone means the key was removed.
Query path
The planner answers one filter through an index (a hash lookup, a B-tree point, range or prefix scan) and checks the others on the rows it found, or scans the table when no index fits. The result is ordered and paged, and says how many rows matched in all and whether more follow.
On a ring, a query is read page by page: each replica answers at most about 256 KiB (rows and the tombstones in the page’s span, in key order after the key the page starts after), and only the keys it is among the first owners of that the level needs (One: one copy, Quorum and Linearizable: a majority, All: every copy). The coordinator merges each key’s newest copy and cuts the page at the smallest last key of the replicas that have more.
A caller reads a page at a time too. POST /api/tables/:name/rows answers a table’s rows in key order, pageSize at
a time (100, at most 1,000), gathered from as many of the ring’s pages as it takes, with a nextPageToken. A SELECT
whose rows pass its maxRows answers the first of them with a nextPageToken; sent back with the same statement, it
gives the rows after those (the statement is run again, so rows written between pages may move them). A page token
says where the next page starts (after a key, or after so many rows) and is signed (HS256) with a key of its own
derived from the node’s signing key, so it is good on any node of the ring; it is bound to its caller and to its
table or statement and lasts an hour (Api.PageTokens). The desk’s Query grid shows 200 rows at a time and goes on
to the node’s next page with Next.
Joins
EngineJoin asks both tables’ stores for their rows and matches a left column with the right rows’ keys, the right
side bucketed by key.
Table layer
SchemaRegistry (tables/schema)
Every table’s definition by database and table, kept in one file and given a new version on each change. It refuses a table that exists, or an evolution that would break old rows, with the reason.
TableActor (tables/{database}/{table})
A table’s directories and its schema file.
Index layer
| Actor | Route | Answers |
|---|---|---|
BTreeIndexActor |
index/btree/{table}/{column} |
Points, ranges, prefixes |
HashIndexActor |
index/hash/{table}/{column} |
Equality |
BloomFilterActor |
index/bloom/{table}/{column} |
“Maybe here” or “certainly not” |
InvertedIndexActor |
index/inverted/{table}/{column} |
Rows holding every word of a query |
Storage layer
Write-ahead log
entry = u32 body length · u32 CRC-32 of the body · body
body = i64 sequence · i64 timestamp · u8 kind (0 value, 1 tombstone) · key · value
Every write is appended and synced before it is in the memtable, so a crash loses nothing acknowledged. A replay stops at the first entry that is short (a torn write) or whose CRC does not match.
A log begun while the node has a data key (below, Sealed at rest) starts with MLW1, and each entry’s body is sealed
(nonce · ChaCha20-Poly1305; the CRC is the sealed bytes’). An entry that does not open ends the replay as a corrupt
one does. A plain log stays plain until a flush empties it, then begins again sealed.
Memtable
Sorted writes in memory, by key, the newest item per key.
SSTable
data blocks · index block · bloom block (optional) · footer
A memtable’s items written once, in key order, and never changed. Format 2: each data block, the index and the bloom
block is framed u8 codec · payload · u32 CRC-32 (of the codec and the payload). The codec’s bit 0 says the payload is
deflated (u32 the body's size · a zlib stream, kept only when it is smaller), bit 1 that it is sealed under the
node’s data key: 0 stored, 1 deflated, 2 sealed, 3 deflated then sealed. A frame whose CRC does not match, that does
not open, or of a codec the reader does not know marks its table bad and the read is refused (CorruptBlock), never
answered; a corrupt index keeps the table from opening. A version 1 table (no frames) is still read. Each open table
keeps its last 16 blocks read, parsed.
The index file
INDEXES holds each secondary index (name, kind, columns, then each value and its row keys) as of the last flush or
merge, with the manifest number it goes with. A table opens with its indexes from it and indexes only its memtable’s
rows again; when the file does not go with the manifest, or lacks an index, the indexes are built from the rows.
Open tables
A table opens at its first message and closes when unused for MLAMBDA_IDLE_MS (five minutes). The process holds at
most MLAMBDA_OPEN_TABLES (256) open, whatever its engines: when one more opens, the tables used longest ago are asked
to close, and each closes when nothing holds it (a backup’s pin, a merge, writes pending). Its next message opens it
again.
Compaction
Size-tiered: tables of about the same size (the same power-of-4 tier above 4 KiB) are merged once a tier holds four of them, by themselves after a flush. For each key the newest item wins. A tombstone is dropped only when the merge covers every table and, on a ring of several nodes, it is older than the table’s last completed repair (and than its backup horizon, when it has one); before any repair, every tombstone is kept. An SSTable the manifest does not name (a crash between writing a table and naming it) is removed at open.
Snapshots and the manifest
A snapshot is a memtable saved whole with the log sequence it holds up to. The manifest lists a table’s SSTables and its latest snapshot.
Sealed at rest
A node given key material (DATA_AT_REST_KEY, or the file DATA_AT_REST_KEY_FILE names; at least 32 characters, and
required on a ring of more than one node) derives its data key with HKDF-SHA256 and seals what it writes with
ChaCha20-Poly1305 (Storage.AtRest): each log entry, SSTable block, index and bloom block as a piece (nonce (12
random bytes) · ciphertext · tag), and each manifest, change list, index file and schema whole (MLSF · piece). The
kind of piece is its associated data, so a piece moved into another place does not open. Every nonce is drawn at
random for each piece written (pieces are written once and replaced, never rewritten in place). Files written before a
key was set are read as they are, by what they begin with; a sealed file read where no key is set is refused, never
read as plain. The kernel chart makes the material once per client (data-rest-key in the data Secret).
Each piece begins with its key’s id (4 bytes derived from the material), so a node can hold several keys: it seals
only under DATA_AT_REST_KEY and opens what any of its keys sealed, the older ones given as
DATA_AT_REST_KEY_PREVIOUS (; apart). A key changes without a stop:
- Give the nodes the new material as
data-rest-keyand the old one asdata-rest-key-previous, and restart them. POST /api/cluster/reseal: every node writes each table again under the new key (its log begun again, its memtable flushed, its whole files written again at once; its SSTables merged into one off the store’s turn), and its registry.GET /api/cluster/keyscounts each node’s files by key; whenolderis 0, dropdata-rest-key-previous.
A piece under a key the node does not hold is refused, never taken for a torn write: a log whose entry is under such a key does not open (before, the replay stopped there and the log was cut).
On disk
<root>/data/<database>/<table>/MANIFEST
<root>/data/<database>/<table>/INDEXES the secondary indexes as of the last flush or merge
<root>/data/<database>/<table>/REPAIRED the start of the table's last completed repair
<root>/data/<database>/<table>/wal/wal-<database>-<table>.log
<root>/data/<database>/<table>/sstables/sstable-<database>-<table>-<n>.sst
<root>/data/<database>/<table>/snapshots/snapshot-<database>-<table>-<sequence>.sst
<root>/RING the ring a node settled on last (read before DATA_NODES)
Filesystem
NamespaceActor (the catalog: every file’s type, whether it can be appended to, whether it is sealed, its size),
FileActor (a file’s blocks) and BlockActor (one block on disk). Table storage writes its files directly today;
the filesystem layer is there to hold them as replicated blocks.
Supervision
Management.Failures names each failure (DiskFullException, …) and gives it a parent kind, up to Exception.
Guardians are rules on those kinds, turned into MLambda.Actor deciders: storage restarts on I/O, compaction, snapshot
and memory failures.
Cluster layer
The ring
Each node holds 256 tokens (FNV-1a of node#i) on a consistent-hash ring. A key belongs to the first token at or
after its hash; its replicas are the next distinct nodes.
Replicas and the coordinator
Each node hosts its own Replica (replica/<node>, up to 64 instances at once). The coordinator sends a request to
the replicas that own its key and waits for as many as the consistency level needs, retrying a replica that failed
after a short, uneven pause. Every request carries when its asker stops waiting; a replica it reaches more than 5 s
after that does not carry it out (Expired).
| Level | What it does |
|---|---|
Linearizable (default) |
the ABD register: a write learns the key’s newest stamp from a majority and writes above it; a read writes the newest copy back until a majority holds it. See Consistency Model |
Quorum (Fast) |
one round, the coordinator’s clock’s stamp; a read answers the newest of a majority |
All, One, Available |
every owner, one owner, every owner hinted with one read |
A coordinator’s stamps come from Distributed.Clock (raised past every stamp given or seen, its lease kept in its
node’s engine); a stamp more than 5 s ahead of a calendar clock is refused (ClockAhead).
writeIf writes only if the key is as it was read (its newest stamp, or absent): a single-decree Paxos round among
the key’s owners, whose acceptors keep their promises in the node’s engine (_paxos.state). The ORM (saveIf,
removeIf), REST (POST /api/tables/:name/writeIf and deleteIf, with the expectedTimestamp a read answered) and
SQL (UPDATE ... IF STAMP = n, DELETE ... IF STAMP = n, INSERT ... IF NOT EXISTS) all reach it.
A busy node says so at once. Each node counts the requests its replica is carrying out; past
MLAMBDA_REPLICA_ADMITTED (60) at once it answers Overloaded instead of queueing them: queries over many rows first
(from three quarters of it), single keys next, and the ring’s own requests (repair, moves, hints) last (four times
it). The asker counts an Overloaded owner as one that failed and retries after its pause.
Repair
On a ring of several nodes, the first node repairs every table every MLAMBDA_REPAIR_MS (an hour): each node answers
its digest of the table by group (a key’s owners and one of 16 buckets of its hash); only the groups whose digests
differ are fetched, and each key’s newest copy is written back where an owner is behind. A repair every node took
part in sets the table’s repair horizon on every node. An operator repairs every table now with
POST /api/cluster/repair (the desk’s Cluster page, Repair now); a table’s storage tells when it was last repaired
(repairedAt).
A ring that changes
ringMoved adds, removes or replaces one node: every node of both rings is told the ring is moving (a key’s owners
are then its owners on both, and every majority is counted over them), each table is repaired over the new ring, and
every node is told it settled (and keeps it in RING). An operator moves it with POST /api/cluster/ring
({"nodes": "a;b;c"}; the desk’s Cluster page, Change the ring). A move that stopped halfway (a node that did not
answer) leaves the nodes that took it moving; moving to the ring the node is on calls it off, every node settled where
it was.
Membership
Nodes find each other through MLambda.Actor’s gossip and its phi accrual failure detector, over the actor host the service starts (standalone, cluster or hybrid).
Recovery flow
- The manifest names the table’s SSTables and its latest snapshot; SSTables it does not name are removed.
- The snapshot loads into the memtable.
- The log entries after the snapshot’s sequence are replayed.
- The indexes come from the index file, and the memtable’s rows are indexed again over it (or, when the file does not go with the manifest, the indexes are built from the rows).
REST and live API
Api.Gateway serves the REST API in API Spec; Api.Hubs serves five live channels (/ws/metrics,
/ws/ring, /ws/cluster, /ws/alerts, /ws/compaction) over SignalR’s JSON protocol on WebSockets. Requests carry a
JWT (Api.Tokens); Auth.Permissions decides each one by the most specific permission that matches.
Admin calls are kept in the audit (system.audit). Reads are too: each read through the API (a record’s read, a
SELECT) is counted by who read and which table, and kept once a window (MLAMBDA_READ_AUDIT_MS, a minute) as one
entry, Read on default.people: 12 reads, 340 rows; a read refused is kept at once.