0.7.0
GitHub

Event sourcing for distributed Rust apps

Your data stays true, everywhere it lives.

happenstance is the data layer for Rust apps that run on devices, at the edge and in the cloud. Every change is kept, every business rule is checked, and every answer can be explained, whether the data sits in SQLite on a laptop that is offline, in a Cloudflare Durable Object near your users, or in Postgres and Neon.

Nothing lost. Nothing wrong. Nothing unexplained.

Get started
cargo add happenstance

What you get

Data you can trust, on every device and every database

True offline

Every device keeps its own log and keeps working without a network. When it reconnects, every change syncs, and nothing is lost or overwritten, because a change is a fact rather than a row to fight over.

True to your rules

Seat limits, balances, quotas and unique names are checked at the moment of the write, across every record the rule touches, with no locks and no sagas. When two places act at once, you are told, with an event, never left with a silent mistake.

True to its history

The log is the source of truth. See why any record looks the way it does, rebuild a view that went wrong, add a new one over years of data, and change your event format without a migration.

True wherever it lives

SQLite on the device, Durable Objects at the edge, Postgres or Neon in the middle. The same Rust code runs on each, every store passes the same published test suite, and there is no sync service in the middle.

New to event sourcing? Start with the background: four short pages, from what an event is to why the boundary can be drawn per decision.

What you can build

Design your data topology, not your sync code

Pick the pieces your app needs: where each log lives, which logs sync, where each view lives and where each decision is made. Every arrangement keeps the same guarantees.

A device's SQLite log, an edge Durable Object and a central Postgres or Neon database, linked by sync, each holding the views it needs
Works today
Works offline, syncs when back

Each device keeps a SQLite log and syncs it with Neon or Postgres when the network returns.

Works today
Many clients, one source of truth

Every device syncs to a central store, and a conflict arrives as an event you can see and act on, or that a merge rule answers as it syncs, from 0.7.

Works today
Each client holds only its workspace

One store per workspace, case or tenant, and each client syncs just the ones it holds.

Works today
Huge views stay on the server

A million records in a server-side read model, queried over HTTP, with read-your-writes answered honestly while the view catches up.

Works today
A local view of just my cases

A projection reads the central log and keeps a small read model in local SQLite, rebuildable at any time.

Works today
Thin clients for the big decisions

Some commands go straight to the server, where the full history lives, and the rest stay local.

On the roadmap
A lean device, a complete cloud

The device prunes history the hub has confirmed, while Neon keeps everything.

On the roadmap
Edge hubs close to your users

A Durable Object per tenant syncs the devices nearby and forwards to Neon.

Choose a topology explains each shape and the rule it keeps, and choosing a store walks through where each piece can run.

How your rules stay true

A decision that spans two things

01The rule

A course holds thirty seats. A student takes at most five courses. Subscribing one student to one course has to respect both limits — and the two limits are about different things.

02The answer you know

Most event-sourced systems split events into fixed groups chosen up front, such as one per course or one per student, and only keep a rule consistent inside one group. A rule about a course and a student fits neither, so it ends up enforced by extra machinery: a separate copy of the data to check against, and a background process to undo the mistakes that slip through.

03The answer here

With a dynamic consistency boundary (DCB) there are no fixed groups. Each decision reads the events it needs, here the seats taken on this course and the courses this student holds, and its write is accepted only if no new event matching that read has been added since. Both limits hold, with one read and one write.

docs/first-encounter.md · step 3
use happenstance::{AppendCondition, AppendError, Event, EventStore};
use happenstance::{MemoryEventStore, Query, QueryItem, Tags};
use happenstance::read_decision_model;

#[tokio::main]
async fn main() -> Result<(), Box<dyn core::error::Error>> {
    let store = MemoryEventStore::new();
    let held = Tags::from_pairs([("course", "c1")])?;
    let item = QueryItem::new(["SeatHeld"], held.clone())?;
    let seats = Query::from_items([item])?;
    let seat = Event::new("SeatHeld", &b"{}"[..])?.with_tags(held);
    store.append(&[seat.clone()], None).await?; // already held
    let (_taken, upto) = read_decision_model(&store, &seats).await?;
    store.append(&[seat.clone()], None).await?; // another writer
    let condition =
        AppendCondition::new(seats).after_every_guard_opt(upto);
    match store.append(&[seat], Some(&condition)).await {
        Err(AppendError::ConditionViolated(_)) => {
            println!("guarded above {upto:?}: ConditionViolated");
        }
        ok => panic!("the boundary did not hold: {ok:?}"),
    }
    Ok(())
}
cargo run
guarded above Some(SequencePosition(1)): ConditionViolated
Another writer lands a seat between the read and the write, so the store refuses the append. This program is copied from the tutorial, and the repository's gate compiles and runs it on every change; remove the condition and watch it fail.

Measured, not claimed

Fast where it matters

~34 µs to check a two-thing rule

The SQLite store checks a condition spanning a course and a student in about 34 µs, and the cost stays flat as the log grows from a thousand events to a million.

~57,000 events a second

Appended to SQLite in batches of 128, about 6,900 a second one at a time. The in-memory store reaches about 4.8 million.

~189,000 events a second, rebuilt

A read model catches up from an empty start over SQLite at that rate, so rebuilding a view over a large log is minutes, not hours.

64 writers, one winner, no errors

Sixty-four requests race for the same decision. Exactly one is accepted, the other sixty-three are told to decide again, and nothing fails.

One run on one Linux machine, in September 2026; read them as orders of magnitude. The full results carry the method, the raw output and what the numbers do not show.

Where it is going

On the road to 1.0

Shipped
Sync between stores

Replicate a log between SQLite, Postgres, Neon and Durable Objects, one edge at a time, with conflicts recorded as ordinary events rather than lost. The runner and network peers ship from 0.6.0; merge rules and the retention-gap report from 0.7.0.

In progress
Keeping less, on purpose

Devices that keep less history than the hub. 0.7.0 settles what a store may forget and reports a peer that has been away longer than the hub remembers; pruning a device without resurrecting what it pruned is next.

Planned · 1.0
Sync across many edges

A runner that links several edges, so a device, an edge hub and a central database form one system, and a stable promise for every surface.

Exploring
SQLite in the browser

The SQLite store on wasm32, as the offline end of sync.

The plan, phase by phase, is in the runbook.

How it compares

Both halves, in one library

Sync engines

Fast and offline, but conflicts are merged away or the last write wins, and most keep no history. Your business rules live in backend code you write yourself.

Event-sourcing frameworks

History, audit and rebuildable views, but on one server, usually behind aggregates and sagas, and sometimes a vendor's server too.

happenstance

Offline devices, edge and central databases syncing one history, with every rule checked where its history is complete and every view rebuildable. A library over your own databases.

Looking for collaborative text editing, or a reactive local database for a JavaScript web app? A CRDT library or a JavaScript sync engine will suit you better.

Choose your path

Start from the question you arrived with

How we know it works

Every claim names what would falsify it

event_store_conformance!
A published conformance suite

An adapter that has not passed happenstance-testkit is not an adapter. Each rule is paired with a wrong store that fails it, so no rule is decorative.

ES-25
A specification in numbered clauses

Each clause carries a maturity marker — frozen, provisional or deferred — and names the conformance rule that checks it. The tutorial above cites one.

cargo xtask ci
Documentation the gate compiles

Every Rust example in this guide is compiled against the real crates, and run, before a change merges. A page that stopped being true fails the build, not the reader.

Status

Early, and worth being precise about. 0.7.0 is published. EventStore has been frozen since 0.2.0 and ProjectionStore since 0.3.0; the rest of the road to 1.0 is in the runbook, phase by phase.

About the name

In everyday use the word means chance, and that is not the sense meant here. The sense meant is the one in as it happened: a DCB boundary is not fixed when the schema is written — it is whatever the handler's query matched. The handler designs that query on purpose; what it does not do is inherit a boundary someone drew earlier.