React to Chronicle Read Model Changes
A Chronicle read model reactor runs application code when a read model instance is added, modified, or removed. Use one when a change to derived state should trigger a notification or downstream update, without managing a watch subscription yourself.
In .NET, name a handler Added, Modified, or Removed and Chronicle dispatches matching changes to it. This convenience uses the watch stream; it does not add transactional delivery. Choose your client tab for its handler and registration syntax.
Write the reactor
Section titled “Write the reactor”For .NET, implement the IReadModelReactor marker interface and add a method named Added, Modified, or Removed. The method name selects the change, and the first parameter selects the read model to watch:
using Cratis.Chronicle.ReadModels;
public class AccountNotifier : IReadModelReactor{ public Task Added(Account account) => SendWelcome(account);
public Task Modified(Account account) => SendUpdated(account);
public Task Removed(Account account) => SendClosed(account);
Task SendWelcome(Account account) => Task.CompletedTask; Task SendUpdated(Account account) => Task.CompletedTask; Task SendClosed(Account account) => Task.CompletedTask;}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.readModels.ReadModelReactorsimport kotlinx.coroutines.Jobimport io.cratis.chronicle.readModels.IReadModelReactorimport io.cratis.chronicle.readModels.ReadModel
@ReadModeldata class ReactingReactorAccount(val name: String = "", val balance: Double = 0.0)
class AccountNotifier : IReadModelReactor { fun added(account: ReactingReactorAccount) = sendWelcome(account) fun modified(account: ReactingReactorAccount) = sendUpdated(account) fun removed(account: ReactingReactorAccount?) = sendClosed(account)
private fun sendWelcome(account: ReactingReactorAccount) { /* ... */ } private fun sendUpdated(account: ReactingReactorAccount) { /* ... */ } private fun sendClosed(account: ReactingReactorAccount?) { /* ... */ }}
// JVM read model reactors are registered explicitly; cancel the job on shutdown.fun startAccountNotifier(store: IEventStore): Job = ReadModelReactors(store.readModels, store.eventLog).register(AccountNotifier())import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.readModels.ReadModelReactors;import kotlinx.coroutines.Job;import io.cratis.chronicle.readModels.IReadModelReactor;import io.cratis.chronicle.readModels.ReadModel;
@ReadModelclass ReactingReactorAccount { private String name = ""; private double balance = 0;
public String getName() { return name; } public void setName(String name) { this.name = name; }
public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; }}
class AccountNotifier implements IReadModelReactor { public void added(ReactingReactorAccount account) { sendWelcome(account); } public void modified(ReactingReactorAccount account) { sendUpdated(account); } public void removed(ReactingReactorAccount account) { sendClosed(account); }
private void sendWelcome(ReactingReactorAccount account) { } private void sendUpdated(ReactingReactorAccount account) { } private void sendClosed(ReactingReactorAccount account) { }
// JVM read model reactors are registered explicitly; cancel the job on shutdown. static Job start(IEventStore store) { return new ReadModelReactors(store.getReadModels(), store.getEventLog()).register(new AccountNotifier()); }}defmodule MyApp.Reactors.AccountNotifier do use Chronicle.ReadModels.Reactor, model: MyApp.ReadModels.Account
@impl true def on_added(account, _changeset), do: send_welcome(account)
@impl true def on_modified(account, _changeset), do: send_updated(account)
@impl true def on_removed(key, _changeset), do: send_closed(key)
defp send_welcome(_account), do: :ok defp send_updated(_account), do: :ok defp send_closed(_key), do: :okendTypeScript does not support this workflow yet.The .NET client discovers and starts these reactors automatically, then closes their subscriptions when the client is disposed. To handle another model or change type, add a matching method.
Handle a single instance or a collection
Section titled “Handle a single instance or a collection”A .NET handler can return void, Task, or Task<T>. Its first parameter accepts either a single read model or a collection. The collection form contains the changed instance, or is empty when a removal has no instance. It does not batch several changes:
using Cratis.Chronicle.ReadModels;
public class AccountBatchProjector : IReadModelReactor{ public async Task Modified(IEnumerable<Account> accounts) { foreach (var account in accounts) { await Sync(account); } }
Task Sync(Account account) => Task.CompletedTask;}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.readModels.ReadModelReactorsimport kotlinx.coroutines.Jobimport io.cratis.chronicle.readModels.IReadModelReactorimport io.cratis.chronicle.readModels.ReadModel
@ReadModeldata class ReactingCollectionAccount(val name: String = "", val balance: Double = 0.0)
class AccountBatchProjector : IReadModelReactor { fun modified(accounts: List<ReactingCollectionAccount>) { accounts.forEach { sync(it) } }
private fun sync(account: ReactingCollectionAccount) { /* ... */ }}
// JVM read model reactors are registered explicitly; cancel the job on shutdown.fun startAccountBatchProjector(store: IEventStore): Job = ReadModelReactors(store.readModels, store.eventLog).register(AccountBatchProjector())import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.readModels.ReadModelReactors;import kotlinx.coroutines.Job;import io.cratis.chronicle.readModels.IReadModelReactor;import io.cratis.chronicle.readModels.ReadModel;
import java.util.List;
@ReadModelclass ReactingCollectionAccount { private String name = ""; private double balance = 0;
public String getName() { return name; } public void setName(String name) { this.name = name; }
public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; }}
class AccountBatchProjector implements IReadModelReactor { public void modified(List<ReactingCollectionAccount> accounts) { accounts.forEach(this::sync); }
private void sync(ReactingCollectionAccount account) { }
// JVM read model reactors are registered explicitly; cancel the job on shutdown. static Job start(IEventStore store) { return new ReadModelReactors(store.getReadModels(), store.getEventLog()).register(new AccountBatchProjector()); }}Elixir does not support this workflow yet.TypeScript does not support this workflow yet.Take dependencies
Section titled “Take dependencies”In .NET, parameters after the read model are resolved from the service container, with EventContext supplied separately by the dispatcher. For a projection-backed watch, that context identifies the causing event’s sequence number, occurrence time, and correlation ID. Reducer and materialized observations have less context, as described below.
Use constructor injection, method parameters, or both for your services:
using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.ReadModels;
public interface IAccountNotifications{ Task Notify(string accountId);}
public interface IAccountAuditLog{ void Record(string accountId, EventSequenceNumber sequenceNumber);}
public class AccountAuditor(IAccountNotifications notifications) : IReadModelReactor{ public Task Modified(Account account, EventContext context, IAccountAuditLog audit) { audit.Record(account.Id, context.SequenceNumber); return notifications.Notify(account.Id); }}Kotlin does not support this workflow yet.Java does not support this workflow yet.Elixir does not support this workflow yet.TypeScript does not support this workflow yet.Return side effects
Section titled “Return side effects”A .NET handler can return events for Chronicle to append, using the same return shapes as a reactor side effect: a single event, a collection, an EventForEventSourceId, or a mix. The dispatcher honors [EventStreamType] and [EventSourceType] on the reactor. These appends are best-effort, not part of a transaction with the read model change.
using Cratis.Chronicle.Events;using Cratis.Chronicle.ReadModels;
[EventType]public record AccountFlagged(string AccountId);
public class AccountReviewer : IReadModelReactor{ public Task<AccountFlagged> Modified(Account account) => Task.FromResult(new AccountFlagged(account.Id));}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.readModels.ReadModelReactorsimport kotlinx.coroutines.Jobimport io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.readModels.IReadModelReactorimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class AccountFlagged(val accountId: String = "")
@ReadModeldata class ReactingSideEffectsAccount(val id: String = "", val balance: Double = 0.0)
class AccountReviewer : IReadModelReactor { /** * Returning an event from a handler appends it, using the changed instance's key as the * event source id by default. */ fun modified(account: ReactingSideEffectsAccount): AccountFlagged = AccountFlagged(account.id)}
// JVM read model reactors are registered explicitly; cancel the job on shutdown.fun startAccountReviewer(store: IEventStore): Job = ReadModelReactors(store.readModels, store.eventLog).register(AccountReviewer())import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.readModels.ReadModelReactors;import kotlinx.coroutines.Job;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.readModels.IReadModelReactor;import io.cratis.chronicle.readModels.ReadModel;
@EventTyperecord AccountFlagged(String accountId) {}
@ReadModelclass ReactingSideEffectsAccount { private String id = ""; private double balance = 0;
public String getId() { return id; } public void setId(String id) { this.id = id; }
public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; }}
class AccountReviewer implements IReadModelReactor { // Returning an event from a handler appends it, using the changed instance's key as the // event source id by default. public AccountFlagged modified(ReactingSideEffectsAccount account) { return new AccountFlagged(account.getId()); }
// JVM read model reactors are registered explicitly; cancel the job on shutdown. static Job start(IEventStore store) { return new ReadModelReactors(store.getReadModels(), store.getEventLog()).register(new AccountReviewer()); }}Elixir does not support this workflow yet.TypeScript does not support this workflow yet.The three change types
Section titled “The three change types”| Method | Reacts to |
|---|---|
Added |
The watched instance was added, or first seen by an observation that infers changes locally. |
Modified |
The read model instance changed. |
Removed |
The read model instance was removed. |
For projection-backed read models watched through the change stream, the server supplies the change type and causing event context. This distinguishes an addition from a modification. Reducer-backed and materialized observations infer changes locally instead.
Watch through the materialized read model
Section titled “Watch through the materialized read model”In .NET, apply [Materialized] to observe stored state instead of the projection change stream. Chronicle observes the complete materialized collection, without the API’s default 50-instance page limit, and compares successive snapshots to infer changes.
using Cratis.Chronicle.ReadModels;
[Materialized]public class AccountSnapshotReactor : IReadModelReactor{ public Task Added(Account account) => Task.CompletedTask;}Kotlin does not support this workflow yet.Java does not support this workflow yet.Elixir does not support this workflow yet.TypeScript does not support this workflow yet.Use this when the reaction should follow what is stored in the sink. It cannot preserve every intermediate state: SQL polling and snapshot delivery can combine several writes into one observed change.
When the fit is imperfect
Section titled “When the fit is imperfect”The .NET dispatcher logs handler and append failures without pausing a partition or retrying the failed dispatch. Rapid changes can run handlers concurrently, so completion order is not guaranteed.
Materialized comparison uses serialized values keyed by id, _id, or Id. Its EventContext carries the model key but no causing event sequence number. Existing instances in the first snapshot are reported as Added; that does not mean they were just created.
For reducer-backed models, the .NET reactor tracks keys locally to infer additions. The first observed non-removal for a key is Added; later ones are Modified, and removals remain Removed. This does not supply the original event context.
If ordered, replayable processing is a requirement, react to the domain event rather than the derived read model. That page explains event-reactor delivery and partition handling so you can choose the appropriate processing model.
Related topics
Section titled “Related topics”- Watching Read Models — the lower-level change stream this builds on
- Reactors — event-based processing and partition handling
- Reactor Side Effects — the append model reused here