The local-first engine

A local-first Soda app has no server of its own. Each person's browser runs the app's backend, in a service worker. The store holds only encrypted, signed history it can't read, so nobody but the members of a space (not the store, not its operator) can see, lose or leak what's in it.

This page is the design soda-local follows: its promises, the invariants that keep them, and how each layer does. What's built says how far the code has come.

Promises#

When they conflict, these come in this order:

  1. Integrity. Nothing anyone records is lost, changed or silently overwritten. Every member sees the same record.
  2. Clarity. Nobody is left unsure what happened: what's saved, what isn't yet, what's current, and what needs them.
  3. Speed. It feels instant.

In the words a person using the app reads:

  • Saved means the store has it, and it will reach everyone in the space. Nothing can take it back.
  • Before that, it says On this device, and for how long. You can always record what happened, online or not.
  • When what you see might be out of date, the app says as of when.
  • If two people change the same thing at once, neither change is silently lost. The second one is shown to its author, who can apply it anyway.
  • Every member's device keeps a full copy. The store is a relay and a backup.

Defaults#

The SDK decides these for every app. An app may tighten them, never loosen the integrity ones.

SituationWhat happens
Recording what happened (a dose given, a note, a payment)Always allowed, online or offline. Records never conflict.
Editing something shared (a schedule, a card)If someone changed the same thing first, theirs stands and the author is told. Planned: editing pauses after 24 hours offline.
Administration (members, devices, keys, invitations)Online only, once the device has caught up.
A critical action (giving a medicine, moving money)Planned: online, the device checks in first ("Checking…"); offline, it says when it last heard from the space.
The view may be out of date (not live for 2 minutes)"as of 2:14 PM" beside the title; "Catching up…" after time away.
Changes only on this deviceA count ("3 on this device"). Planned: plainer warnings at 24 and 72 hours offline.
A new version is outIt installs in the background and takes over when nothing is being typed.
A change arrives more than an hour late (a phone offline on a trip)Its device makes it again if it still applies. If someone changed the same thing since, only its author is told.
The device's clock is more than 2 minutes offA warning. Records keep the device's time: the store's clock is never trusted to date anything.
The browser might clear the site's data (Safari, no passkey)The engine asks the browser to keep it. If it won't, the app suggests Add to Home Screen and a passkey.
A space's address fills upThe owner's device moves the space to a new key and address by itself once 6 MB are stored there, before the store's 10 MB limit. A change the store refuses anyway is kept, never dropped.
Something in the history can't be appliedListed calmly in the history. Never a badge or an error.

Words people see: Saved, Saving, On this device, Offline, Catching up, as of, Checking. Words they never see: store, row, entry, fork, epoch, refused, signature, instance, worker.

Layers#

LayerIts one jobWhere (src/engine/)
FactsKeep and exchange bytes: every row received, every row this device wrote. Knows nothing of meaning.wire, formats, persist, load, outbox, sync, hooks
TrustWho signed this, and were they allowed: key histories, signatures, membership, space keys.kels, account, rotations, pairing, restore, keyring, key_change, key_share
InterpretationA pure function from facts to each space's state, and what its history says about itself.space_rec, interpret, recover, checkpoints, closes
ChangesTurn a person's command into signed facts.act, spaces, offers
AppThe app's own rules, as pure functions.the app
StateThe instance's one state, and what it refuses and says, typed. Apps word it.state, refused, notice
LifecycleWhat runs: which version, when it switches, crashes, locking.keeping, tick, view, presence, peers, browser

Pages only render and collect input. One service worker per site means one instance per device, so each device has exactly one writer.

Invariants#

The simulator checks these, and code that can't keep one doesn't merge.

I1. Facts are kept; everything else is a cache. A device stores every row it received or wrote, as signed. Positions, checkpoints and state are derived: dropping them and recomputing gives the same result.

I2. Interpretation is a pure function of facts, key histories, the rules version and an explicit now. Same facts and rules, same result. Only named rules read now (an entry dated more than a day ahead waits).

I3. Signatures cover bytes, not interpretations. An older version verifies a newer version's entry, applies what it understands, and holds the rest until it updates.

I4. Signed history only grows. Events gain kinds, variants and optional fields, never lose or change them (events.lock, checked by cargo test and the build).

I5. Every entry says which rules signed it (v). A device seeing a higher v than its own knows it's behind.

I6. Nothing honest is ever stranded. No entry, however malformed, misdated or forked, stops others from counting. Two versions of one entry resolve by the store's order, and the loser is made again where nothing has changed since.

I7. No silent overwrite. An edit names the revision it changes. If the thing has changed since, the edit doesn't apply anywhere, and its author is told.

I8. Nothing signed is ever dropped. A signed change stays in the outbox until the store has it. Failures are retried, parked and surfaced.

I9. "Saved" means stored. Saved shows only once the store has the row. A change is in IndexedDB before the action returns.

I10. One writer per device chain, never signing behind itself. A device restored from an old copy reads its own chain back first.

I11. The engine never speaks to people. It reports typed status; apps choose the words.

I12. Bounded under attack. What one author can make a device keep or compute is capped (rows per address, bytes per row, unknown rows per author), and no cap loses honest facts.

Facts#

What a device keeps, in one IndexedDB object store (kv), every record sealed with the device key:

KeyHolds
secretsWho this device is, its spaces and their keys.
fact:…Every row of history it holds, one record each, exactly as written, with its address, its store row id and when this device first had it. A row that won't open where it was found isn't kept.
positionsWhere reading each address resumes. Moved only past rows that were kept.
out:<hash>Each row waiting for the store (I8).
cache:<space>, cache:kelsEach space and the key histories as last folded. Disposable.
sigs:<space>, decided:<space>The signatures already checked there, and what this device decided about its own entries that never counted.

A flush writes all of it in one transaction, so no part is ever ahead of another.

Sync uses the store's append, read, latest and signal; realtime pushes are only hints. Members' open pages also trade rows directly.

  • A refused row is parked with a typed reason and offered again, backing off from a minute to six hours. The only refusal an honest device meets is "address full".
  • Sizes are checked at signing: a change too big for the store is refused when it's submitted ("That's too long to save"), never sent to fail later.
  • Each store response's Date header gives the clock check.

Trust#

Key histories are KERI-shaped. Every valid version is kept, and one is chosen the same way everywhere: recovery beats passkey beats devices, then the one the store had first, then the lower digest. Membership is decided while replaying history, and owners are pinned. Trust answers one question, from facts alone: was this validly signed, by whom, and was that device allowed then?

Interpretation#

A pipeline of pure stages, each cached by hash:

  1. Decode. Open the row with the space key for its address and parse the entry, keeping its bytes.
  2. Verify. Check the signature over those bytes.
  3. Order. Chain each device's entries by sequence and previous hash. Resolve two versions of one entry by the store's order, and drop what carried on from the loser. Place misdated entries after their device's previous one (I6). The shared order is Lamport time, then hash.
  4. Authorize. Against key histories and key changes, as of that point in the replay.
  5. Fold. Run the app's evolve, checking each edit's revision (I7).

The output is each space's state, plus what its history says about itself: versions that lost, edits that didn't apply, entries from a newer version, entries nobody validly signed. Only history screens show these.

Checkpoints are caches (I1). A copy at the store lets a new device start without replaying everything. It's trusted only from the device's own account, or from the space's owner (for someone new to the space). The owner's devices close a space's history about hourly (SpaceEvent::HistoryClosed). A change from before a close that arrives after it counts nowhere, and its device makes it again if it still applies. So no checkpoint is ever undone, and the store can let old rows go.

Rules versions. The engine has its RULES; each app adds its own (LocalFirst::RULES on a model, App::RULES on an App), raised when evolve would read existing events differently. When either changes, the device refolds from its facts on start, offline, in a few hundred milliseconds even for a year of history.

Changes#

Every change is one of three kinds:

  • Records: facts about the world (a dose given, a note, a reading). Always allowed; never conflict.
  • Edits: changes to a shared thing, named by the app's target (card:7f/title). The engine signs each edit with the target's revision it saw (base). At fold, it applies only if nothing at, under or above that target changed since. Otherwise it's a conflict, the same everywhere, and its author can apply theirs anyway (Engine::apply_anyway).
  • Admin: membership, devices, keys, sharing. Online and caught up only.

Planned: an app marks critical commands, and the engine reads the space before deciding them when online. Edits pause after App::OFFLINE_EDITS (24 hours by default) without hearing from the store.

Versions and lifecycle#

  • Older code verifies newer entries (I3), applies what it knows and holds the rest. Nothing leaves its fact store (I1), so after updating it just refolds.
  • Switching. A new worker installs in the background. The page reloads into it once nothing is half typed and no sheet is open.
  • Crashes. If the instance panics, pages reload into a fresh one, with a loop guard. Facts are already on disk.
  • Locking. A device kept with a passkey can lock: its device key is forgotten, and everything stays encrypted until the passkey unlocks it.

What the engine reports#

The engine reports state, never sentences (I11):

  • Refusals and notices are typed: Refused and Notice, one variant per reason. An app's own words are Refused::App.
  • State::as_of gives the last full read once it's over two minutes old. While State::catching_up, the page holds still (at most 12 s), then shows the result in one step.
  • DeviceStatus counts unsent and parked rows, gives the clock skew, and says whether the browser may clear the site's data.

Security and privacy#

  • The store sees encrypted rows at secret addresses, their sizes and their timing. Nothing else.
  • Every change is signed by the device that made it.
  • Members can't forge each other's history, rewrite it, or show different people different versions without it resolving the same way everywhere.
  • At rest, facts stay encrypted under space keys, which are sealed under the device key, which a lock forgets.
  • Caps (I12) bound what a hostile member can make others store or compute.
  • A page runs only the site's own scripts and Datastar's expressions (by the page's own nonce): never a string as code, a script that came with an update, or another site's.

Performance budgets#

These are requirements, not hopes:

Budget
An action's result in the page (local fold), whatever the network50 ms
Another member's open page shows it1 s through the store, about 50 ms directly
A warm start paints the last state (marked "as of" until caught up)300 ms
Refold of a year-long space after a rules change, on a mid-range phone1 s
Catching up after a week away, on a normal connection3 s
Download sizeNo bigger than today (Care under 900 KB compressed, the board under 550 KB)

What an app writes#

Most apps write a soda::Model (the same one a server runs, see events.md) and name what a space is called:

impl soda_local::LocalFirst for Board {
    const NOUN: &'static str = "board";

    // What an edit changes; None for what always counts.
    fn target(&self, _by: &str, event: &Event) -> Option<String> {
        match event {
            // Adding under an id that's taken changes nothing (see `evolve`), so it claims nothing.
            Event::CardAdded { card, .. } if self.cards.contains_key(card) => None,
            Event::CardAdded { card, .. } | Event::CardDeleted { card } => Some(format!("card:{card}")),
            Event::CardRenamed { card, .. } => Some(format!("card:{card}/title")),
            Event::CardMoved { .. } | Event::Renamed { .. } => None,
        }
    }
}

soda_local::app!(board::Board);

An app whose rules read the space itself (its members, its owner) implements soda_local::App instead. The engine handles conflicts, late changes, catching up and status. local-first.md builds an app.

How it's tested#

The simulator (src/sim) runs whole simulated lives, a third of them with an attacker, and checks the invariants after each:

InvariantCheck
I1Drop every cache mid-life and restart: the state is unchanged.
I2, I3Planned: two engine versions in one life, the newer adding a field and an event kind (today a unit test checks an older version verifying a newer entry).
I6Devices rolled back to old copies, misdated and malformed entries: nothing honest waits.
I7Concurrent edits of one target: every device agrees which applied, and each loser's author is told.
I8, I9A store that refuses, rate-limits and loses pushes: nothing leaves an outbox, and nothing shows Saved, before the store has it.

Alongside: the SDK's tests and each app's end-to-end suite. Planned: an upgrade test per release.

What's built#

PartState
Facts: the fact store, an outbox that never drops, size checks, cached signature checks, storage persistence, the clock checkBuilt
Status: typed refusals and notices, "as of", "Catching up"Built (one status model for every app to come)
Edits with a base: targets, revisions, conflictsBuilt (undo and late changes still use the model's step and travel)
Layers: src/engine/ split by layerBuilt
Versions: v on entries (I5)Planned
Offline rules: the 24-hour edit window, critical commandsPlanned
LaterSocial recovery (social-recovery.md), timed locks, a verifiable export, moving a space to another store

Not in scope#

  • Character-by-character co-editing of the same text.
  • Spaces of more than about fifty people.
  • Search or notifications that need a server to read across people.
  • Apps whose value is aggregation across users.

Decided#

Revisit these only with a reason:

  • The store's order breaks ties in exactly four places:
    • two versions of one entry;
    • two history closes built on the same one;
    • two equally strong versions of one step in a key history;
    • an older entry found under two keys.
  • "Saved" means the store has it.
  • Of two conflicting edits, the second in the shared order doesn't apply, and its author decides.
  • Records are always allowed. Admin needs the network.

This page is docs/architecture.md in the SDK, built into this site as it is.

Esc