Cratis Chronicle: react to an event
A reactor in Cratis Chronicle runs a side effect in response to a recorded event. Use one when returning a book should notify the next member on the waitlist, or when a reservation should produce a follow-up stock event. Unlike a projection that builds state, a reactor does work because a fact has happened.
Write the reactor
Section titled “Write the reactor”With a Chronicle client configured in your C# application, define a class implementing IReactor. This marker interface has no methods to implement. Instead, write a handler whose first parameter is the event type you want to handle:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
[EventType]public record ScenariosReactBookReturned(string Isbn);
public interface IScenariosReactNotificationService{ Task NotifyNextInLine(EventSourceId bookId); Task NotifyNextInLine(EventSourceId bookId, string bookTitle);}
public class ScenariosReactWaitlistNotifier(IScenariosReactNotificationService notifications) : IReactor{ public async Task BookReturned(ScenariosReactBookReturned @event, EventContext context) { // context.EventSourceId is the source the event happened to (the book) await notifications.NotifyNextInLine(context.EventSourceId); }}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.observation.Reactor
@EventTypedata class ScenariosReactBookReturned(val isbn: String)
interface ScenariosReactNotificationService { fun notifyNextInLine(bookId: String) fun notifyNextInLine(bookId: String, bookTitle: String)}
@Reactorclass ScenariosReactWaitlistNotifier(private val notifications: ScenariosReactNotificationService) { fun bookReturned(event: ScenariosReactBookReturned, context: EventContext) { // context.eventSourceId is the source the event happened to (the book) notifications.notifyNextInLine(context.eventSourceId) }}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.observation.Reactor;
@EventTyperecord ScenariosReactBookReturned(String isbn) {}
interface ScenariosReactNotificationService { void notifyNextInLine(String bookId);
void notifyNextInLine(String bookId, String bookTitle);}
@Reactorclass ScenariosReactWaitlistNotifier { private final ScenariosReactNotificationService notifications;
ScenariosReactWaitlistNotifier(ScenariosReactNotificationService notifications) { this.notifications = notifications; }
void bookReturned(ScenariosReactBookReturned event, EventContext context) { // context.getEventSourceId() is the source the event happened to (the book) notifications.notifyNextInLine(context.getEventSourceId()); }}defmodule MyApp.Events.ScenariosReactBookReturned do use Cratis.Chronicle.Events.EventType, id: "scenarios-react-book-returned"
defstruct [:isbn]end
defmodule MyApp.ScenariosReactNotificationService do def notify_next_in_line(_book_id), do: :ok def notify_next_in_line(_book_id, _book_title), do: :okend
defmodule MyApp.Reactors.ScenariosReactWaitlistNotifier do use Cratis.Chronicle.Reactors.Reactor
alias MyApp.Events.ScenariosReactBookReturned alias MyApp.ScenariosReactNotificationService
@handles ScenariosReactBookReturned
@impl true def handle(%ScenariosReactBookReturned{}, context) do # context.event_source_id is the source the event happened to (the book) ScenariosReactNotificationService.notify_next_in_line(Map.get(context, :event_source_id)) :ok endendimport { EventContext, eventType, onceOnly, reactor } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class ScenariosReactBookReturned { @field(String) readonly isbn: string;
constructor(isbn: string) { this.isbn = isbn; }}
interface ScenariosReactNotificationService { notifyNextInLine(bookId: string): Promise<void>; notifyNextInLine(bookId: string, bookTitle: string): Promise<void>;}
@reactor()class ScenariosReactWaitlistNotifier { constructor(private readonly notifications: ScenariosReactNotificationService) {}
// Without @handles(EventType), the method name must be the exact camelCase of the // event's class name - Chronicle discovers undecorated handlers by name, not by parameter type. @onceOnly() async scenariosReactBookReturned(event: ScenariosReactBookReturned, context: EventContext): Promise<void> { // context.eventSourceId is the source the event happened to (the book) await this.notifications.notifyNextInLine(context.eventSourceId); }}Chronicle discovers the reactor among the application types configured for its client and routes matching events to the handler. Here context.EventSourceId identifies the returned book, so the notification service can find its waitlist. Provide that service through your application’s dependency injection setup.
Be safe to repeat
Section titled “Be safe to repeat”A reactor may handle the same event again during replay or recovery. Make external effects idempotent: repeating the request must not send a second notification or charge a payment twice. Use the delivery identity as a stable key for the remote system or for your own effect receipts. A local receipt alone does not make a remote call atomic with recording that receipt.
If an effect should be skipped during replay, mark its handler or the whole class with [OnceOnly]. This excludes it from replays, not from every possible redelivery. See OnceOnly before using it for a payment or notification.
In C#, Chronicle gives returned events idempotency keys when the connected kernel supports idempotent appends. Those keys prevent the same delivery’s output from being appended again during recovery or catch-up. An older kernel without that capability appends the returned events without keys. If you change the returned output and deliberately want replay to append the new shape, raise the reactor’s effect epoch, the version number included in its returned-event keys. Do not raise it just to retry unchanged output.
Need state? Pick the right consistency
Section titled “Need state? Pick the right consistency”Use the event’s data first. If the notification also needs the book’s title, read the model that holds it, using context.EventSourceId as the key.
A materialized read model is stored state maintained by a projection or reducer. It is the default and is eventually consistent, so it may not yet include the event being handled. Calling IReadModels.GetInstanceById or accepting the model as a handler parameter does not change that consistency.
When the reaction needs state that includes the triggering event, mark the read model [Passive]. Chronicle then computes it from the event log on demand rather than relying on the stored model. Make that choice on the read model definition before using the lookup below; the lookup alone does not request a strongly consistent read.
using Cratis.Chronicle;using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
public record ScenariosReactBook(string Title);
public class ScenariosReactWaitlistNotifierWithTitle(IEventStore eventStore, IScenariosReactNotificationService notifications) : IReactor{ public async Task BookReturned(ScenariosReactBookReturned @event, EventContext context) { // Strongly consistent — rebuilt from the event log, includes this event var book = await eventStore.ReadModels.GetInstanceById<ScenariosReactBook>(context.EventSourceId); await notifications.NotifyNextInLine(context.EventSourceId, book.Title); }}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.observation.Reactorimport io.cratis.chronicle.readModels.ReadModel
@ReadModeldata class ScenariosReactBook(val title: String = "")
@Reactorclass ScenariosReactWaitlistNotifierWithTitle(private val notifications: ScenariosReactNotificationService) { // Looked up by the triggering event's event source id; a materialized read model can lag this event or be null. fun bookReturned(event: ScenariosReactBookReturned, context: EventContext, book: ScenariosReactBook?) { notifications.notifyNextInLine(context.eventSourceId, book?.title ?: "") }}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.observation.Reactor;import io.cratis.chronicle.readModels.ReadModel;
@ReadModelrecord ScenariosReactBook(String title) { ScenariosReactBook() { this(""); }}
@Reactorclass ScenariosReactWaitlistNotifierWithTitle { private final ScenariosReactNotificationService notifications;
ScenariosReactWaitlistNotifierWithTitle(ScenariosReactNotificationService notifications) { this.notifications = notifications; }
// Looked up by the triggering event's event source id; a materialized read model can lag this event or be null. void bookReturned(ScenariosReactBookReturned event, EventContext context, ScenariosReactBook book) { notifications.notifyNextInLine(context.getEventSourceId(), book != null ? book.title() : ""); }}defmodule MyApp.ReadModels.ScenariosReactBook do use Cratis.Chronicle.ReadModels.ReadModel
defstruct title: ""end
defmodule MyApp.Reactors.ScenariosReactWaitlistNotifierWithTitle do use Cratis.Chronicle.Reactors.Reactor
alias MyApp.Events.ScenariosReactBookReturned alias MyApp.ReadModels.ScenariosReactBook alias MyApp.ScenariosReactNotificationService
@handles ScenariosReactBookReturned
@impl true def handle(%ScenariosReactBookReturned{}, %{event_source_id: book_id}) do # Strongly consistent — rebuilt from the event log, includes this event {:ok, book} = Cratis.Chronicle.read_model(ScenariosReactBook, book_id) ScenariosReactNotificationService.notify_next_in_line(book_id, book.title) :ok endendimport { EventContext, ReactorServices, readModel, reactor } from '@cratis/chronicle';
@readModel()class ScenariosReactBook { title = '';}
@reactor()class ScenariosReactWaitlistNotifierWithTitle { // Constructor injection requires an artifactActivator in ChronicleOptions. constructor(private readonly notifications: ScenariosReactNotificationService) {}
async scenariosReactBookReturned(event: ScenariosReactBookReturned, context: EventContext, services: ReactorServices): Promise<void> { // Eventually consistent: this read may not yet include the triggering event. const book = await services.readModels.findInstanceById(ScenariosReactBook, context.eventSourceId); if (book === null) throw new Error(`Book ${context.eventSourceId} is not available yet`); await this.notifications.notifyNextInLine(context.eventSourceId, book.title); }}For collection reads or live changes instead of one book’s state, continue with Get read models.
Appending an event
Section titled “Appending an event”To translate a reservation into a stock change in C#, return the follow-up event from the handler. Chronicle appends it to the event log against the triggering event’s EventSourceId:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
[EventType]public record ScenariosReactBookReserved(string Isbn);
[EventType]public record ScenariosReactStockDecreased(string Isbn, int Quantity);
public class ScenariosReactStockKeeping : IReactor{ // Without [OnceOnly], a replay of this reactor appends StockDecreased again. [OnceOnly] public ScenariosReactStockDecreased BookReserved(ScenariosReactBookReserved @event, EventContext context) => new(@event.Isbn, 1);}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.observation.Reactor
@EventTypedata class ScenariosReactBookReserved(val isbn: String)
@EventTypedata class ScenariosReactStockDecreased(val isbn: String, val quantity: Int)
// Returning an event from a handler appends it as a side effect - against the event source that// triggered the reactor - with no event log dependency in sight.@Reactorclass ScenariosReactStockKeeping { fun bookReserved(event: ScenariosReactBookReserved, context: EventContext): ScenariosReactStockDecreased = ScenariosReactStockDecreased(event.isbn, 1)}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.observation.Reactor;
@EventTyperecord ScenariosReactBookReserved(String isbn) {}
@EventTyperecord ScenariosReactStockDecreased(String isbn, int quantity) {}
// Returning an event from a handler appends it as a side effect - against the event source that// triggered the reactor - with no event log dependency in sight.@Reactorclass ScenariosReactStockKeeping { ScenariosReactStockDecreased bookReserved(ScenariosReactBookReserved event, EventContext context) { return new ScenariosReactStockDecreased(event.isbn(), 1); }}defmodule MyApp.Events.ScenariosReactReturnBookReserved do use Cratis.Chronicle.Events.EventType, id: "scenarios-react-return-book-reserved"
defstruct [:isbn]end
defmodule MyApp.Events.ScenariosReactReturnStockDecreased do use Cratis.Chronicle.Events.EventType, id: "scenarios-react-return-stock-decreased"
defstruct [:isbn, :quantity]end
defmodule MyApp.Reactors.ScenariosReactReturnStockKeeping do # Without `once_only`, a replay of this reactor appends StockDecreased again. use Cratis.Chronicle.Reactors.Reactor, once_only: [MyApp.Events.ScenariosReactReturnBookReserved]
alias MyApp.Events.{ScenariosReactReturnBookReserved, ScenariosReactReturnStockDecreased}
@handles ScenariosReactReturnBookReserved
# The returned event is appended to the same event source as a side effect. @impl true def handle(%ScenariosReactReturnBookReserved{isbn: isbn}, _context) do {:ok, %ScenariosReactReturnStockDecreased{isbn: isbn, quantity: 1}} endendimport { EventContext, eventType, onceOnly, reactor } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class ScenariosReactBookReserved { @field(String) readonly isbn: string;
constructor(isbn: string = '') { this.isbn = isbn; }}
@eventType()class ScenariosReactStockDecreased { @field(String) readonly isbn: string; @field(Number) readonly quantity: number;
constructor(isbn: string = '', quantity: number = 0) { this.isbn = isbn; this.quantity = quantity; }}
@reactor()class ScenariosReactStockKeeping { // Without @onceOnly(), a replay of this reactor appends StockDecreased again. // Returning an event appends it for you, targeting the triggering event's own // event source id, stream, and subject - the simplest way to record a follow-up fact. @onceOnly() async scenariosReactBookReserved(event: ScenariosReactBookReserved, context: EventContext): Promise<ScenariosReactStockDecreased> { return new ScenariosReactStockDecreased(event.isbn, 1); }}Task<StockDecreased> and collections of events work too. Returning side effects explains the supported return shapes and how to choose a different target event source. The example’s [OnceOnly] skips the handler during replay; Duplicate protection explains the separate key-based protection for returned output. A ReactorScenario records returned events by default; configuring it with the real side-effect handlers also exercises their keyed appends.
Use an explicit append when you need to inspect the result yourself, or when following a client’s explicit-append example. Check the AppendResult and throw if it failed, so the reactor partition pauses rather than treating a missing follow-up fact as success:
using Cratis.Chronicle;using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
public class ScenariosReactStockCouldNotBeDecreased(string isbn) : Exception($"Stock could not be decreased for ISBN {isbn}");
public class ScenariosReactStockKeepingExplicit(IEventStore eventStore) : IReactor{ public async Task BookReserved(ScenariosReactBookReserved @event, EventContext context) { var result = await eventStore.EventLog.Append( context.EventSourceId, new ScenariosReactStockDecreased(@event.Isbn, 1)); if (!result.IsSuccess) { throw new ScenariosReactStockCouldNotBeDecreased(@event.Isbn); } }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.ScenariosReactBookReserved do use Cratis.Chronicle.Events.EventType, id: "scenarios-react-book-reserved"
defstruct [:isbn]end
defmodule MyApp.Events.ScenariosReactStockDecreased do use Cratis.Chronicle.Events.EventType, id: "scenarios-react-stock-decreased"
defstruct [:isbn, :quantity]end
defmodule MyApp.ScenariosReactStockCouldNotBeDecreased do defexception [:message]
def exception(isbn) do %__MODULE__{message: "Stock could not be decreased for ISBN #{isbn}"} endend
defmodule MyApp.Reactors.ScenariosReactStockKeepingExplicit do use Cratis.Chronicle.Reactors.Reactor
alias MyApp.Events.{ScenariosReactBookReserved, ScenariosReactStockDecreased} alias MyApp.ScenariosReactStockCouldNotBeDecreased
@handles ScenariosReactBookReserved
@impl true def handle(%ScenariosReactBookReserved{isbn: isbn}, %{event_source_id: event_source_id}) do case Cratis.Chronicle.append(event_source_id, %ScenariosReactStockDecreased{isbn: isbn, quantity: 1}) do :ok -> :ok {:error, _reason} -> raise ScenariosReactStockCouldNotBeDecreased, isbn end endendimport { EventContext, ReactorServices, onceOnly, reactor } from '@cratis/chronicle';
@reactor()class ScenariosReactStockKeepingExplicit { @onceOnly() async scenariosReactBookReserved(event: ScenariosReactBookReserved, context: EventContext, services: ReactorServices): Promise<void> { const result = await services.eventStore.eventLog.append( context.eventSourceId, new ScenariosReactStockDecreased(event.isbn, 1)); if (!result.isSuccess) { throw new Error(`Stock could not be decreased for ISBN ${event.isbn}`); } }}See also
Section titled “See also”Use Reactors to configure filtering and inspect reactor behavior. If you are deciding whether this work belongs in a reactor at all, Projections, reducers, and reactors compares reacting to a fact with building state from it.