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.
Event sourcing for distributed Rust apps
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.
cargo add happenstance
What you get
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.
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.
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.
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
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.
Each device keeps a SQLite log and syncs it with Neon or Postgres when the network returns.
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.
One store per workspace, case or tenant, and each client syncs just the ones it holds.
A million records in a server-side read model, queried over HTTP, with read-your-writes answered honestly while the view catches up.
A projection reads the central log and keeps a small read model in local SQLite, rebuildable at any time.
Some commands go straight to the server, where the full history lives, and the rest stay local.
The device prunes history the hub has confirmed, while Neon keeps everything.
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 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.
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.
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.
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(())
}Measured, not claimed
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.
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.
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.
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
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.
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.
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.
The SQLite store on wasm32, as the offline end of sync.
The plan, phase by phase, is in the runbook.
How it compares
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.
History, audit and rebuildable views, but on one server, usually behind aggregates and sagas, and sometimes a vendor's server too.
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
Send
A Durable Object on wasm32, and Postgres over one-shot HTTP with no connection to hold — both running the same conformance suite.
Adapter author
I am bringing my own storage
The order to read what already exists, and the suite that decides whether your adapter is one.
How we know it works
event_store_conformance!
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
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
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.
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.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.