3. React to events with Cratis Chronicle
A reactor in Cratis Chronicle handles a recorded event to perform application work. Here you’ll react to BookReturned by calling a notification service, so the next member waiting for the book can hear that it is available. The projection from the previous chapter maintains the loan view; the reactor performs the follow-up action.
Continue with your connected client, the book’s saved event-source ID, and the events from the previous chapters. The examples show the handoff to a notification service, not an implementation of a waitlist or message delivery. Start with a service that logs the book ID so you can observe the call without sending messages.
In event-modeling, this is the automation pattern: a processor watches for an event and acts. It completes this part of the library model:
A reactor is just a class that watches for an event
Section titled “A reactor is just a class that watches for an event”In C#, implement the marker interface IReactor and give the handler BookReturned as its first parameter. Chronicle uses that type to route matching events to the method. The EventContext argument supplies the book’s event-source ID, which the service needs to identify its waitlist.
Provide the INotificationService implementation through your application’s dependency injection setup before starting the client. For the other languages, follow the service shape in the selected example:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
public interface INotificationService{ Task NotifyNextInLine(EventSourceId bookId); Task NotifyNextInLine(EventSourceId bookId, string bookTitle);}
public class WaitlistNotifier(INotificationService notifications) : IReactor{ public async Task BookReturned(BookReturned @event, EventContext context) { // context.EventSourceId is the BookId this happened to await notifications.NotifyNextInLine(context.EventSourceId); }}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.observation.Reactor
interface NotificationService { fun notifyNextInLine(bookId: String) fun notifyNextInLine(bookId: String, bookTitle: String)}
@Reactorclass WaitlistNotifier(private val notifications: NotificationService) { fun bookReturned(event: BookReturned, context: EventContext) { // context.eventSourceId is the bookId this happened to notifications.notifyNextInLine(context.eventSourceId) }}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.observation.Reactor;
interface NotificationService { void notifyNextInLine(String bookId); void notifyNextInLine(String bookId, String bookTitle);}
@Reactorclass WaitlistNotifier { private final NotificationService notifications;
WaitlistNotifier(NotificationService notifications) { this.notifications = notifications; }
void bookReturned(BookReturned event, EventContext context) { // context.getEventSourceId() is the bookId this happened to notifications.notifyNextInLine(context.getEventSourceId()); }}defmodule MyApp.NotificationService do def notify_next_in_line(_book_id), do: :ok def notify_next_in_line(_book_id, _book_title), do: :okend
defmodule MyApp.Reactors.WaitlistNotifier do use Cratis.Chronicle.Reactors.Reactor
alias MyApp.Events.BookReturned alias MyApp.NotificationService
@handles BookReturned
@impl true def handle(%BookReturned{}, %{event_source_id: book_id}) do # book_id is the id this happened to NotificationService.notify_next_in_line(book_id) :ok endendimport { EventContext, onceOnly, reactor } from '@cratis/chronicle';
async function notifyNextInLine(bookId: string): Promise<void> { console.log(`Notify next in line for book ${bookId}`);}
@reactor()class WaitlistNotifier { // 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 bookReturned(event: BookReturned, context: EventContext): Promise<void> { // context.eventSourceId is the bookId this happened to await notifyNextInLine(context.eventSourceId); }}Keep the reactor in your client’s configured discovery or registration scope. The C# client discovers IReactor implementations; the other tabs use their clients’ reactor declarations. In the TypeScript example, retain the bookReturned method name because that example discovers the handler by name.
With the client connected and the reactor registered, append a BookReturned under the same book ID used in the previous chapters. Check your logging service: it should receive that ID. The append records the event first; the notification call happens later when the reactor processes it.
Why your reactor must be safe to repeat
Section titled “Why your reactor must be safe to repeat”A reactor may handle the same event more than once, including during replay or recovery after a failure. A notification service that sends a message on every call can therefore send duplicates. Make the effect idempotent: repeating the call for the same delivery must not send another message.
Use a receipt keyed to the delivery or a notification API that accepts a stable deduplication key. Recording success only after sending leaves a failure window: the message can be sent before the receipt is saved. Decide how the service will handle that case before replacing the logging implementation with real delivery.
To exclude a C# reactor or handler from replay, mark it [OnceOnly]. This prevents replay caused by redactions, revisions, or observer rewinds from repeating its effect. It also means an intentional replay will not recreate that effect.
[OnceOnly] does not prevent ordinary retries. If the handler throws, processing pauses for that event source’s partition, the group of events being processed for that source. Recovering the partition delivers the event again. For retry protection in .NET, use the delivery identity to key a receipt or pass a stable key to an API that deduplicates. The marker alone is not an exactly-once guarantee.
using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
public class WaitlistNotifierOnceOnly(INotificationService notifications) : IReactor{ [OnceOnly] public async Task BookReturned(BookReturned @event, EventContext context) => await notifications.NotifyNextInLine(context.EventSourceId);}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.observation.OnceOnlyimport io.cratis.chronicle.observation.Reactor
interface OverdueLetterService { fun sendOverdueLetter(bookId: String)}
@Reactorclass OverdueLetterSender(private val letters: OverdueLetterService) { // A posted letter cannot be un-posted, so this handler is excluded from every replay. @OnceOnly fun bookReturned(event: BookReturned, context: EventContext) { letters.sendOverdueLetter(context.eventSourceId) }}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.observation.OnceOnly;import io.cratis.chronicle.observation.Reactor;
interface OverdueLetterService { void sendOverdueLetter(String bookId);}
@Reactorclass OverdueLetterSender { private final OverdueLetterService letters;
OverdueLetterSender(OverdueLetterService letters) { this.letters = letters; }
// A posted letter cannot be un-posted, so this handler is excluded from every replay. @OnceOnly void bookReturned(BookReturned event, EventContext context) { letters.sendOverdueLetter(context.getEventSourceId()); }}defmodule MyApp.OnceOnlyNotificationService do def notify_next_in_line(_book_id), do: :okend
defmodule MyApp.Reactors.WaitlistNotifierOnceOnly do # `once_only: true` is never replayed: use it for side effects such as notifications. use Cratis.Chronicle.Reactors.Reactor, once_only: true
alias MyApp.Events.BookReturned alias MyApp.OnceOnlyNotificationService
@handles BookReturned
@impl true def handle(%BookReturned{}, %{event_source_id: book_id}) do OnceOnlyNotificationService.notify_next_in_line(book_id) :ok endendimport { EventContext, onceOnly, reactor } from '@cratis/chronicle';
// BookReturned is the event defined earlier in the tutorial.@reactor()class WaitlistNotifierOnceOnly { @onceOnly() async bookReturned(event: BookReturned, context: EventContext): Promise<void> { await notifyNextInLine(context.eventSourceId); }}Kotlin and Java use @OnceOnly; TypeScript uses @onceOnly() on a class or handler. Elixir uses once_only: on use Chronicle.Reactors.Reactor, either for the whole reactor or selected event types. These controls exclude replay, not retries. Choose one notifier implementation as you follow the examples: registering several variants would make each react to the same return.
Read the book’s title
Section titled “Read the book’s title”BookReturned has no title. To send a message such as “The Pragmatic Programmer is back”, read the Book view using the event-source ID from the context.
The view from the previous chapter is materialized, so the lookup reads stored state with eventual consistency. The title does not change in this tutorial, but the instance can still be missing if BookAdded has not been projected yet. Handle that case before accessing the title; the C# example below assumes the instance exists:
using Cratis.Chronicle;using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
public class WaitlistNotifierWithBookTitle(IEventStore eventStore, INotificationService notifications) : IReactor{ public async Task BookReturned(BookReturned @event, EventContext context) { var book = await eventStore.ReadModels.GetInstanceById<Book>(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 Book(val title: String = "")
@Reactorclass WaitlistNotifierWithBookTitle(private val notifications: NotificationService) { // Looked up by the triggering event's event source id; a materialized read model can lag this event or be null. fun bookReturned(event: BookReturned, context: EventContext, book: Book?) { 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 Book(String title) { Book() { this(""); }}
@Reactorclass WaitlistNotifierWithBookTitle { private final NotificationService notifications;
WaitlistNotifierWithBookTitle(NotificationService 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(BookReturned event, EventContext context, Book book) { notifications.notifyNextInLine(context.getEventSourceId(), book != null ? book.title() : ""); }}defmodule MyApp.Reactors.WaitlistNotifierWithBookTitle do use Cratis.Chronicle.Reactors.Reactor
alias MyApp.Events.BookReturned alias MyApp.NotificationService alias MyApp.ReadModels.Book
@handles BookReturned
@impl true def handle(%BookReturned{}, %{event_source_id: book_id}) do case Cratis.Chronicle.read_model(Book, book_id) do {:ok, %Book{title: title}} -> NotificationService.notify_next_in_line(book_id, title) :ok
# Not projected yet, or the read failed: return an error so Chronicle # records a failed partition you can retry. {:ok, nil} -> {:error, :book_not_projected}
{:error, reason} -> {:error, reason} end endendimport { EventContext, ReactorServices, reactor } from '@cratis/chronicle';
interface TutorialBookTitleNotifier { notifyNextInLine(bookId: string, title: string): Promise<void>;}
@reactor()class WaitlistNotifierWithBookTitle { // Constructor injection requires an artifactActivator in ChronicleOptions. constructor(private readonly notifications: TutorialBookTitleNotifier) {}
async bookReturned(event: BookReturned, context: EventContext, services: ReactorServices): Promise<void> { // A read model may lag this event or not exist yet. const book = await services.readModels.findInstanceById(Book, context.eventSourceId); if (book === null) throw new Error(`Book ${context.eventSourceId} is not available yet`); await this.notifications.notifyNextInLine(context.eventSourceId, book.title); }}The clients obtain that state differently. C# looks it up through IEventStore. Kotlin and Java declare a read-model parameter, which Chronicle resolves using the triggering event’s source ID. TypeScript receives ReactorServices and uses its readModels; its constructor-injected notification service requires an artifactActivator in ChronicleOptions. Elixir calls Chronicle.read_model/2 and handles a missing instance or read error explicitly.
For state that must include the triggering event, review the consistency levels and the passive read-model option. A C# model marked [Passive] is computed from events on each read, rather than fetched from the stored view. Neither a plain stored read nor a passive read guards a later append against competing writes.
Record the notification outcome
Section titled “Record the notification outcome”If successful notification is a fact your application needs to retain, define an event for it:
using Cratis.Chronicle.Events;
[EventType]public record WaitlistNotificationSent;import io.cratis.chronicle.events.EventType
@EventTypeclass WaitlistNotificationSentimport io.cratis.chronicle.events.EventType;
@EventTyperecord WaitlistNotificationSent() {}defmodule MyApp.Events.WaitlistNotificationSent do use Cratis.Chronicle.Events.EventType, id: "waitlist-notification-sent"
defstruct []endimport { eventType } from '@cratis/chronicle';
@eventType()class WaitlistNotificationSent {}One option is to append it inside the handler after the notification call succeeds. Check the append result and report failure instead of allowing the handler to appear successful without recording the fact. The C# example throws when the append fails, pausing the partition for recovery. Retrying runs the whole handler again, including the notification call:
using Cratis.Chronicle;using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
public class NotificationWasNotRecorded(EventSourceId bookId) : Exception($"Notification for book {bookId} was not recorded");
public class WaitlistNotifierExplicitAppend(IEventStore eventStore, INotificationService notifications) : IReactor{ public async Task BookReturned(BookReturned @event, EventContext context) { await notifications.NotifyNextInLine(context.EventSourceId);
var result = await eventStore.EventLog.Append(context.EventSourceId, new WaitlistNotificationSent()); if (!result.IsSuccess) throw new NotificationWasNotRecorded(context.EventSourceId); }}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.observation.Reactor
@Reactorclass WaitlistNotifierWithExplicitAppend( private val notifications: NotificationService, private val eventStore: IEventStore,) { suspend fun bookReturned(event: BookReturned, context: EventContext) { notifications.notifyNextInLine(context.eventSourceId) eventStore.eventLog.append(context.eventSourceId, WaitlistNotificationSent()) }}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.java.BlockingEventStore;import io.cratis.chronicle.observation.Reactor;
@Reactorclass WaitlistNotifierWithExplicitAppend { private final NotificationService notifications; private final BlockingEventStore eventStore;
WaitlistNotifierWithExplicitAppend(NotificationService notifications, IEventStore eventStore) { this.notifications = notifications; this.eventStore = new BlockingEventStore(eventStore); }
void bookReturned(BookReturned event, EventContext context) { notifications.notifyNextInLine(context.getEventSourceId()); eventStore.getEventLog().append(context.getEventSourceId(), new WaitlistNotificationSent()); }}defmodule MyApp.NotificationWasNotRecorded do defexception [:message]
def exception(book_id) do %__MODULE__{message: "Notification for book #{book_id} was not recorded"} endend
defmodule MyApp.Reactors.WaitlistNotifierExplicitAppend do use Cratis.Chronicle.Reactors.Reactor
alias MyApp.Events.BookReturned alias MyApp.Events.WaitlistNotificationSent alias MyApp.NotificationService alias MyApp.NotificationWasNotRecorded
@handles BookReturned
@impl true def handle(%BookReturned{}, %{event_source_id: book_id}) do NotificationService.notify_next_in_line(book_id)
case Cratis.Chronicle.append(book_id, %WaitlistNotificationSent{}) do :ok -> :ok {:error, _reason} -> raise NotificationWasNotRecorded, book_id end endendimport { EventContext, ReactorServices, onceOnly, reactor } from '@cratis/chronicle';
@reactor()class WaitlistNotifierExplicitAppend { @onceOnly() async bookReturned(event: BookReturned, context: EventContext, services: ReactorServices): Promise<void> { await notifyNextInLine(context.eventSourceId); const result = await services.eventStore.eventLog.append(context.eventSourceId, new WaitlistNotificationSent()); if (!result.isSuccess) throw new Error(`Notification for book ${context.eventSourceId} was not recorded`); }}Use the explicit-append example in C#, TypeScript, or Elixir. Follow the Kotlin and Java returned-event example below.
You can instead return the new event as a side effect, an output Chronicle handles after your method completes. Chronicle appends it to the event log under the triggering book’s event-source ID:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
public class WaitlistNotifierSideEffect(INotificationService notifications) : IReactor{ [OnceOnly] public async Task<WaitlistNotificationSent> BookReturned(BookReturned @event, EventContext context) { await notifications.NotifyNextInLine(context.EventSourceId); return new WaitlistNotificationSent(); }}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.observation.Reactor
@Reactorclass WaitlistNotifierSideEffect(private val notifications: NotificationService) { // Returning an event appends it to the event log for you, against the triggering event's event source fun bookReturned(event: BookReturned, context: EventContext): WaitlistNotificationSent { notifications.notifyNextInLine(context.eventSourceId) return WaitlistNotificationSent() }}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.observation.Reactor;
@Reactorclass WaitlistNotifierSideEffect { private final NotificationService notifications;
WaitlistNotifierSideEffect(NotificationService notifications) { this.notifications = notifications; }
// Returning an event appends it to the event log for you, against the triggering event's event source WaitlistNotificationSent bookReturned(BookReturned event, EventContext context) { notifications.notifyNextInLine(context.getEventSourceId()); return new WaitlistNotificationSent(); }}defmodule MyApp.WaitlistSideEffectNotificationService do def notify_next_in_line(_book_id), do: :okend
defmodule MyApp.Reactors.WaitlistNotifierSideEffect do use Cratis.Chronicle.Reactors.Reactor
alias MyApp.Events.BookReturned alias MyApp.Events.WaitlistNotificationSent alias MyApp.WaitlistSideEffectNotificationService, as: NotificationService
@handles BookReturned
@impl true def handle(_event, %{event_source_id: book_id}) do NotificationService.notify_next_in_line(book_id)
# Returning {:ok, event} appends it as a side effect against the # triggering event source id — Chronicle appends it for you. {:ok, %WaitlistNotificationSent{}} endendimport { EventContext, onceOnly, reactor } from '@cratis/chronicle';
@reactor()class WaitlistNotifierSideEffect { // Returning the event appends it for you, against the triggering event's own // event source id - the book that was returned. @onceOnly() async bookReturned(event: BookReturned, context: EventContext): Promise<WaitlistNotificationSent> { await notifyNextInLine(context.eventSourceId); return new WaitlistNotificationSent(); }}In C#, the returned event is appended with an idempotency key derived from the reactor delivery, so the retry described above does not append it a second time; the notification call itself still runs again, so keep it idempotent. See Duplicate protection for returned events.
The returned-event example is available for C#, Kotlin, Java, and TypeScript. Elixir returns {:ok, event} from handle/2. After adding the new event type to your client’s discovery or registration, replace the basic notifier with this variant. Append another BookReturned, check the service call, and find WaitlistNotificationSent under the same book ID in the event log. This records completion of your service call, not proof that a member read the message.
Use the event, not a lookup
Section titled “Use the event, not a lookup”Use context.EventSourceId to identify the returned book. Querying the current loan view to discover that identity would be unreliable: it may still show the loan or may already have removed it. The event context gives you the identity regardless of the view’s progress.
Read a model for additional information, such as the title, with its freshness and missing-instance behavior in mind. Using the event’s identity avoids an unnecessary lookup; it does not by itself make the notification idempotent.
You’ve built a library
Section titled “You’ve built a library”You have the backend pattern for the library: append facts, project them into loan views, and react to a return by calling a service. Projections and reactors consume the log independently; the notification does not wait for the catalog to catch up. A working waitlist, real message delivery, and duplicate protection in that service remain application work.
Before adding those pieces, test a slice to check event appends and derived read-model state with EventScenario and ReadModelScenario. Then choose the next task:
- Use Scenarios for focused recipes such as enforcing uniqueness or evolving events.
- Add commands and a UI with Arc and Components in Build a full-stack feature.
- Review Concepts and the guides for Projections, Reactors, and Reducers when your own model needs more than this example.
- Use Troubleshooting if an append, view, or reactor does not behave as expected.