Skip to content
rhodeyPublic

About

Write apps that survive cosmic radiation.

Topics

Resources

Contributing

Stars

19 stars

Watchers

2 watching

Forks

Repository files navigation

MonsterFt

MonsterFt is a fixed-membership replicated SQLite state machine. For each command (request), every available node executes the application and captures its database change as an SQLite Session Extension patchset. The command succeeds when a configured quorum agrees on the database change and the return value.

MonsterFt is built on top of standard, unmodified Raft. Raft orders commands; MonsterFt adds SQLite agreement above it. Why? Cosmic Ray Bit-flips plus faulty hard drives.

Minimal example

Create at least three nodes with the same membership IDs:

import { Gate, MonsterProc, MonsterApply } from 'monsterft'

const nodeIds = ['1', '2', '3']
const nodesById = new Map()

function createNode(id) {
  const send = (to, frame) => {
    return nodesById.get(to).onReceive(frame)
  }

  const apply = (db, data, term, seq, index) => {
    if (seq === 0n) {
      db.exec(`
        CREATE TABLE IF NOT EXISTS counters (
          name TEXT PRIMARY KEY NOT NULL,
          value INTEGER NOT NULL
        ) STRICT
      `)
      return
    }

    const command = JSON.parse(data.toString())
    if (command.type !== 'increment') {
      throw new Error(`unknown command: ${command.type}`)
    }

    db.prepare(`
      INSERT INTO counters (name, value) VALUES (?, 1)
        ON CONFLICT (name) DO UPDATE SET value = value + 1
    `).run(command.name)

    return db.prepare(
      'SELECT value FROM counters WHERE name = ?',
    ).get(command.name).value
  }

  const local = new Map()
  const localSend = (from) => (to, frame) => {
    return local.get(to).onReceive(frame, from)
  }

  const gate = new Gate(id, nodeIds, send, localSend('gate'))
  local.set('gate', gate)

  const databasePath = `/tmp/node${id}.db`
  for (const role of ['procA', 'procB', 'procC']) {
    local.set(role, new MonsterProc(
      role, id, nodeIds, localSend(role), databasePath,
    ))
  }
  local.set('apply', new MonsterApply(
    id, localSend('apply'), databasePath, apply,
  ))

  nodesById.set(id, gate)
  return gate
}

const nodes = nodeIds.map(createNode)
await Promise.all(nodes.map((node) => node.open()))
await Promise.all(nodes.map((node) => node.awaitLeader()))

const command = Buffer.from(JSON.stringify({
  type: 'increment',
  name: 'count',
}))
const [cmdSeq, value] = await nodes[0].append(command)
console.log('count =', value)

What's going on here is important and also easy to miss: this is a 3 node Raft cluster but every node is made up of a "gate", three protocol engines, and one "apply" worker. These are to be run as five linux processes and this architecture maximizes correctness. The three protocol engines per node turn "strong leader" Raft into "strong correct leader" in the presence of cosmic bit flips.

send(to, frame) and localSend(to, frame) allow MonsterFt to be fully transport-agnostic. send is allowed to be lossy and unordered but localSend is required to be reliable and ordered. frame is Buffer for both. See example2/ for a demo using TCP between nodes and Unix Domain Sockets between local processes.

Application and patchset rules

apply(db, data, term, seq, index) runs inside an SQLite transaction and may be synchronous or async. When seq === 0n create the application schema and return, MonsterFt ignores seq 0 result.

MonsterFt uses SQLite's Session extension, so its standard rules apply:

  • Give every replicated table a declared, non-NULL primary key.
  • Create schema during the sequence-zero callback; patchsets capture row changes, not schema changes.
  • Keep replicated state in the main database. Temporary, virtual, and attached tables are not captured.
  • Keep triggers and foreign-key behavior deterministic across nodes.

Nodes must produce matching patchsets and outcomes. Return a MessagePack-encodable value or throw an error. When apply coordinates external work, use a protocol that gives every node the same stable observation; see FETCH.md.

Commands

const [cmdSeq, value] = await node.append(buffer)
const [cmdSeq, outcomes] = await node.appendBatch(buffers)

Commands (buffers) may be appended through any node (gate). appendBatch() returns one Promise.allSettled()-style outcome for each command, in the same order. A command with error is rolled back without discarding successful commands; singular append() throws its application error instead.

Useful public state includes .id, .state, and .isOpen. Public events include change, warn, and error.

Retention, Repair, Scrub

MonsterFt can be configured to limit growth of the Raft log to target limits and this is called retention. MonsterFt also detects when nodes in a cluster disagree and then queues repair. Additionally data scrubbing in the background can also queue repair:

// library defaults
const opts = {
  keepTarget: 100_000,
  keepTrigger: 102_000,
  scrubPages: 1_024,
  scrubIntervalCmd: 100,
  scrubIntervalMs: 30_000,
  repairPages: 256,
  repairTimeout: 600_000,
}
const proc = new MonsterProc(
  'procA', id, nodeIds, localSend, databasePath, opts
)

At Raft log entry 102,000 nodes will shrink the logs so only 100,000 entries remain, and then again after the next 2,000. Also every 100 commands (or batches) the next 1,024 SQLite pages will be scrubbed. Or every 30s if 30s is first. Also at repair time SQLite pages will be compared in groups of 256 and a total repair budget of 10min is allowed.

Repair is an online protocol and commands don't stop being accepted or applied. SQLite WAL mode allows a reader to keep a read-only view of the pages needed for repair while writing moves on. WAL "checkpointing" is paused by read-only views and repairTimeout addresses this.

Examples

  • example1/: in-process MonsterFt cluster.
  • example2/: supervised child processes, Unix sockets, and TCP.
  • example3/: supervised MonsterFt with HTTP side effects.
./nix/run.sh example1/entry.sh
./nix/run.sh example2/entry.sh
./nix/run.sh example3/entry.sh

SQLite needs SQLITE_ENABLE_DBPAGE_VTAB at compile time for page level repairs. Nodejs bundled SQLite lacks this and so Nix was added to close the gap. If you look in run.sh you'll see Docker is used to give Nix.

Roadmap

A thorough reading of DRAM Errors in the Wild: A Large-Scale Field Study will reveal that even server-grade ECC RAM has an error rate of 1 error per 100 server-years (Earth). Thus a 100 server fleet is 1 error per 1 year. What we're aiming for is on the order of 1 error per 100 Billion server-years and we think our current direction can get us there. MonsterFt has these users in mind: space, aerospace, defense, fintech, ai (autonomy).

Latency (rust (p95))

Batch size Same-AZ Multi-AZ
1 0.948ms 1.798ms
256 2.073ms 2.840ms
512 3.113ms 3.864ms
1024 5.293ms 5.954ms

Throughput (rust)

Batch size Same-AZ Multi-AZ
1 1,603/s 906/s
256 146,533/s 114,073/s
512 182,466/s 156,168/s
1024 205,916/s 188,450/s

Collaborations

The work is licensed AGPL-3.0-only to encourage collaborations while leaving open a path for negotiating commercial licenses and support packages. I incorporated Lock Host, Inc for some works years ago and led to this. Write to hello@lock.host for commercial licenses and other inquiries. Opening GitHub issues is also encouraged.

Install

This software is on NPM with version 0.9.0. The primary purpose of this README is introductory, not exhaustive. 1.0.0 will aim for exhaustive doc.

npm install monsterft

Copyright

LOCK HOST, INC. 2026.

About

Write apps that survive cosmic radiation.

Topics

Resources

Contributing

Stars

19 stars

Watchers

2 watching

Forks

Contributors

Languages