Skip to main content

Module snapshot

Module snapshot 

Source
Expand description

Snapshotting support — a performance optimisation for long event streams.

Snapshots are never the source of truth. They are always rebuildable by replaying the full event stream. The engine must function correctly if all snapshots are discarded.

§Policy

A common policy is to take a snapshot every N events (e.g. N = 100). Use Snapshot::should_take to check whether enough events have accumulated since the last snapshot.

use mako_engine::snapshot::Snapshot;

// Take a snapshot every 100 events.
// second argument is the sequence_number of the last snapshot (0 = none).
assert!(!Snapshot::should_take(99,  0, 100));
assert!( Snapshot::should_take(100, 0, 100));
// Non-exact counts still trigger once the threshold is exceeded:
assert!( Snapshot::should_take(101, 0, 100));
// After a snapshot at seq 100, next triggers at 200+:
assert!(!Snapshot::should_take(101, 100, 100));
assert!( Snapshot::should_take(200, 100, 100));
// interval = 0 disables snapshotting (never returns true):
assert!(!Snapshot::should_take(1000, 0, 0));

§Using the store

use mako_engine::snapshot::{Snapshot, SnapshotStore};

// After executing a command:
let event_count = process.event_count().await?;
let last_snap   = snap_store.load(process.stream_id()).await?
    .map_or(0, |s| s.sequence_number);
if Snapshot::should_take(event_count, last_snap, 100) {
    let state   = process.state().await?;
    let payload = serde_json::to_value(&state)?;
    let snap    = Snapshot::new(process.stream_id().clone(), event_count, 1, payload);
    snap_store.save(&snap).await?;
}

Structs§

NoopSnapshotStore
A SnapshotStore that never persists anything.
Snapshot
A point-in-time snapshot of an aggregate’s state.

Traits§

SnapshotStore
Storage contract for aggregate snapshots.