Building Correct State
This page presents complete patterns for common reader use cases. Each pattern shows the full setup, explains what guarantees it provides, and identifies the trade-offs.
Pattern 1: Mirror database (zero-drift guarantee)
Section titled “Pattern 1: Mirror database (zero-drift guarantee)”A mirror database maintains a local copy of all entities that exactly matches the server’s state. It uses ReconnectBootstrapMode.Full so that any drift caused by a disconnection is corrected automatically.
EntityMirror applies the bootstrap rules, keeps the current set in Entries, and reports each change to the list you pass to Apply. Read changes in batches with SubscribeBatchesAsync and write each batch in one transaction:
public class MirrorService(KindHandle<ClaimState> claims, AppDbContext db) : BackgroundService{ protected override async Task ExecuteAsync(CancellationToken ct) { var mirror = new EntityMirror<ulong, ClaimState>(EntityId.ToULong); var changes = new List<MirrorChange<ulong, ClaimState>>();
await foreach (var batch in claims.SubscribeBatchesAsync( maxBatch: 500, bootstrap: true, reconnectMode: ReconnectBootstrapMode.Full, ct: ct)) { changes.Clear(); foreach (var change in batch) mirror.Apply(change, changes); if (changes.Count == 0) continue;
// One transaction per batch. using var tx = db.BeginTransaction(); foreach (var c in changes) { if (c.Kind == MirrorChangeKind.Removed) db.Delete(c.Key); else db.Upsert(c.Entity); } tx.Commit(); } }}// Coming soonLive changes are reported as they arrive. At the end of each bootstrap the mirror reports the difference between its previous copy and the bootstrap’s set: Added, Updated (version or fields differ), and Removed for entities deleted while you were disconnected. A new mirror starts empty, so its first bootstrap reports every entity as Added and no removals: if the table already has rows, delete those the first bootstrap didn’t report.
Guarantees
Section titled “Guarantees”- After initial bootstrap completes, the local database contains every entity the server has.
- During live operation, every create, update, and delete is applied incrementally.
- After a disconnection, the re-bootstrap’s differences are applied, correcting any drift.
- Bootstrap rows older than a live change or delete are dropped, so a stale row never overwrites newer data or resurrects a deleted entity.
Trade-offs
Section titled “Trade-offs”- Re-bootstrap reads the entire entity kind. The server sends it only as fast as you consume it, so a large kind takes as long as your writes take.
- The mirror holds the whole kind in memory, in addition to the database.
- A batch that fails to commit is lost from the database. Fail the service (or re-bootstrap) rather than skipping it.
Pattern 2: Event-driven processing (live-only)
Section titled “Pattern 2: Event-driven processing (live-only)”An event-driven processor reacts to individual entity changes without maintaining a complete local copy. It uses ReconnectBootstrapMode.LiveOnly and does not request bootstrap.
public class InventoryEventProcessor(KindHandle<InventoryState> inventory) : BackgroundService{ protected override async Task ExecuteAsync(CancellationToken ct) { await foreach (var change in inventory.SubscribeAsync( bootstrap: false, includePrevious: true, reconnectMode: ReconnectBootstrapMode.LiveOnly, ct: ct)) { if (change.Type == NotificationType.Updated && change.PreviousEntity is { } prev) { var diff = ComputeDiff(prev, change.Entity!.Value); await ProcessInventoryChange(diff, change.Metadata); } } }}// Coming soonGuarantees
Section titled “Guarantees”- Every change that occurs while the subscriber is connected is delivered exactly once.
PreviousEntityprovides the old state for computing diffs.
Trade-offs
Section titled “Trade-offs”- Changes during disconnection are lost. This is acceptable when the subscriber processes transient events (for example, triggering a side effect for each inventory change) rather than maintaining a consistent view.
- No bootstrap means the subscriber does not know the initial state. It only reacts to changes going forward.
Pattern 3: One-shot snapshot (periodic reconciliation)
Section titled “Pattern 3: One-shot snapshot (periodic reconciliation)”A one-shot snapshot retrieves all entities at a point in time without maintaining a live subscription. Use this for periodic batch reconciliation.
// Runs on a timer (e.g., every 5 minutes)public async Task ReconcileAsync(KindHandle<Player> players, AppDbContext db){ IReadOnlyList<Player> snapshot = await players.BootstrapSnapshotAsync();
using var tx = db.BeginTransaction(); db.BulkUpsert(snapshot); db.DeleteWhereIdNotIn(snapshot.Select(p => p.EntityId)); tx.Commit();}// Coming soonGuarantees
Section titled “Guarantees”- The snapshot contains every entity as of
BootstrapComplete: live changes and deletes that arrive during the bootstrap are merged in. - After applying the snapshot, the local database matches the server’s state at that point in time.
Trade-offs
Section titled “Trade-offs”- No live updates between snapshots. Changes between reconciliation runs are not observed until the next run.
- Each snapshot scans the full entity kind. For large kinds, schedule this off-peak.
Choosing a pattern
Section titled “Choosing a pattern”| Requirement | Pattern |
|---|---|
| Local copy must match server exactly at all times | Mirror database with Full re-bootstrap |
| React to individual changes, no local copy needed | Event-driven with LiveOnly |
| Periodic sync, not real-time | One-shot snapshot |
| Real-time dashboard, accept brief gaps on reconnect | Live-only subscription with bootstrap on initial connect |
You can combine patterns. For example, use a mirror database for your primary data store and an event-driven processor for triggering side effects on changes.