Skip to content

Build a separate Cratis Chronicle reducer

A separate Cratis Chronicle reducer keeps state-transition code outside the read model. That code is the fold: it combines an event with current state to produce the next state. Use the .NET IReducerFor<T> form when the fold needs injected services, instance behavior during replay, or separation from a shared model contract. This guide builds an order summary from creation and item changes, then reads it by order ID.

If the transitions can live on the model, start with a self-reducing model instead. If you have not yet chosen between mappings and reducer code, compare the read-model styles first.

Use an application already configured with Chronicle and its event types. Append all events for one order with the same event source ID, and use that ID when reading its summary. An OrderId property in an event does not replace the event source ID used to route the fold.

The summary holds the order’s total amount, item count, and last update time. Define the shape the caller needs, rather than storing another copy of every event:

public record ReducersGettingStartedOrderSummary(
Guid OrderId,
decimal TotalAmount,
int ItemCount,
DateTimeOffset LastUpdated);

View C# snippet source on GitHub

In .NET, implement IReducerFor<TReadModel> for this one model and add methods for its events. Creation initializes the summary; item changes calculate the next total and count:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record ReducersGettingStartedOrderCreated(Guid OrderId);
[EventType]
public record ReducersGettingStartedItemAddedToOrder(decimal Price, int Quantity);
[EventType]
public record ReducersGettingStartedItemRemovedFromOrder(decimal Price, int Quantity);
public class ReducersGettingStartedOrderSummaryReducer : IReducerFor<ReducersGettingStartedOrderSummary>
{
public ReducersGettingStartedOrderSummary Created(ReducersGettingStartedOrderCreated @event, ReducersGettingStartedOrderSummary? current, EventContext context) =>
new(
OrderId: @event.OrderId,
TotalAmount: 0m,
ItemCount: 0,
LastUpdated: context.Occurred);
public ReducersGettingStartedOrderSummary? ItemAdded(ReducersGettingStartedItemAddedToOrder @event, ReducersGettingStartedOrderSummary? current, EventContext context)
{
if (current is null) return null; // Skip if order not created yet
return current with
{
TotalAmount = current.TotalAmount + (@event.Price * @event.Quantity),
ItemCount = current.ItemCount + @event.Quantity,
LastUpdated = context.Occurred
};
}
public ReducersGettingStartedOrderSummary? ItemRemoved(ReducersGettingStartedItemRemovedFromOrder @event, ReducersGettingStartedOrderSummary? current, EventContext context)
{
if (current is null) return null; // Skip if order not created yet
return current with
{
TotalAmount = current.TotalAmount - (@event.Price * @event.Quantity),
ItemCount = current.ItemCount - @event.Quantity,
LastUpdated = context.Occurred
};
}
}

View C# snippet source on GitHub

The item handlers return null if creation has not produced a summary yet. Once state exists, each returns an updated copy. context.Occurred sets LastUpdated from the recorded event time, so replaying the history does not substitute today’s time.

The event context also supplies the event source ID and sequence number. TypeScript handlers can take it as a third argument after the event and current state.

The following signatures describe .NET instance methods. Chronicle selects a handler from its event parameter type, not its method name, and awaits an asynchronous result before applying the next event.

using Cratis.Chronicle.Events;
public interface IReducersGettingStartedSyncSignatures<TReadModel, TEvent>
where TReadModel : class
{
// Without context
TReadModel? WithoutContext(TEvent @event, TReadModel? current);
// With context
TReadModel? WithContext(TEvent @event, TReadModel? current, EventContext context);
}

View C# snippet source on GitHub

using Cratis.Chronicle.Events;
public interface IReducersGettingStartedAsyncSignatures<TReadModel, TEvent>
where TReadModel : class
{
// Without context
Task<TReadModel?> WithoutContext(TEvent @event, TReadModel? current);
// With context
Task<TReadModel?> WithContext(TEvent @event, TReadModel? current, EventContext context);
}

View C# snippet source on GitHub

Kotlin and Java also match the first parameter’s event type; Kotlin awaits suspend handlers. TypeScript discovers camelCase event-class names or explicitly marked handlers, passes (event, current, context), and awaits the result. Elixir uses a reduce/3 callback pattern-matched by event struct. Use the selected client’s examples rather than translating a .NET signature.

In .NET, the event must be the first parameter and the nullable current read model the second. An optional third parameter must be EventContext. Return the model or Task<TReadModel>, including a nullable result. Returning null deletes or leaves the instance absent. Classic plain Task is also accepted, but yields null state; a mutation-only Task handler does not retain current state. A method taking the current model first and object second is not dispatched.

The .NET analyzers report unsupported signatures as CHR0006 and event parameters without [EventType] as CHR0007, including object event parameters. If none of a reducer’s methods can be dispatched, the client skips its kernel registration and logs a warning naming the reducer and explaining why its public reducer-like methods were skipped. The application still starts; correct the signatures so the reducer can observe events.

You can customize the reducer using the [Reducer] attribute:

using Cratis.Chronicle.Reducers;
public record ReducersGettingStartedAttributeOrderSummary(Guid OrderId);
[Reducer(id: "order-summary", eventSequence: "order-events")]
public class ReducersGettingStartedAttributeOrderSummaryReducer : IReducerFor<ReducersGettingStartedAttributeOrderSummary>;

View C# snippet source on GitHub

.NET parameter Effect
id Identifies the reducer; defaults to its fully qualified type name.
eventSequence Selects the sequence to observe. Without it, Chronicle infers the event log or the inbox for one foreign source store from the handled event types. More than one source store is rejected.
isActive Enables active observation; defaults to true.

The example explicitly selects order-events. Omit that selection when the normal inferred sequence is what you need; see Event sequences before choosing a different one.

Use the client tab’s configuration shape. TypeScript expresses identity and sequence through the reducer() decorator; Kotlin and Java use @Reducer.

Read the summary with the event source ID used to append the order’s events:

using Cratis.Chronicle;
using Cratis.Chronicle.ReadModels;
public class ReducersGettingStartedOrderService(IEventStore eventStore)
{
public async Task<ReducersGettingStartedOrderSummary?> GetOrderSummary(Guid orderId) =>
await eventStore.ReadModels.GetInstanceById<ReducersGettingStartedOrderSummary>(orderId);
}

View C# snippet source on GitHub

For an active reducer, this returns materialized state, the result already stored by the observer. It does not wait for the latest append to be reduced. Expect no instance before creation has been processed; after creation, additions increase the total and count, while removals decrease them. For an executable check of those transitions, use ReadModelScenario.

Chronicle keeps each order’s state separate and applies its events in sequence order. The first call in a delivered batch starts from the stored state, which can be null. Each later call receives the previous call’s result, not a fresh read from storage. The batch’s final successful result is what gets persisted.

Return current unchanged to ignore an event. Return null only when the state should remain absent or an existing instance should be removed.

Compute state from recorded facts. An injected clock or live rate service can return different values during replay; put time and rates in events when they determine the result. Keep external side effects out of the fold because retries and replay can invoke it again.

Create new state rather than mutating current, and copy nested collections before changing them. Test events that arrive without prior state as well as the expected order history. This catches missing null handling before an observer encounters it.

Continue with Event Processing when you need handler-selection rules, collection updates, or failure behavior. If stored state is not the read behavior you need, Passive Reducers explains how to fold on demand.