Skip to content

Cratis Chronicle reducers for state-dependent read models

A Cratis Chronicle reducer builds a read model by applying events to its previous state. Use one when a view’s rules are clearer as state transitions in code than as property mappings, such as updating a displayed total only while an account is active.

For direct mappings, start with model-bound projection attributes; use fluent mappings when the definition needs more structure. Counters and sums alone do not require reducer code. If you are still choosing, compare the read-model styles before writing a fold, the function that combines each event with the state so far.

A reducer observes events for each event source, such as an order or account, and keeps that source’s state separate. In the per-event form, Chronicle calls the selected method for each event in sequence order. Its return value becomes current for the next event, even when several events arrive in one batch. A batch reducer instead receives the partition’s events in one call.

Active reducers maintain materialized state: a stored result you can query without folding the history again. A passive reducer computes state when you ask for it. Neither form gives you historical reducer snapshots through GetSnapshotsById.

Choose a reducer when the next result depends on the previous result and a rule. An account balance can ignore deposits after closure; an order summary can calculate a value differently depending on its status. These transitions are explicit in your code and can be tested with an event history.

Reducers fold one event source at a time. If your view needs joins across sources or a total shared by many sources, consider a projection rather than adding that coordination to a reducer.

In .NET, put public static Reduce methods on the model so Chronicle can discover its fold without a marker or separate class. This balance model defines addition and clearing transitions:

using Cratis.Chronicle.Events;
[EventType]
public record SelfBalanceAdded(decimal Amount);
[EventType]
public record SelfBalanceCleared;
public record SelfAccountBalance(decimal Balance)
{
public static SelfAccountBalance Reduce(SelfBalanceAdded @event, SelfAccountBalance? current) =>
new((current?.Balance ?? 0m) + @event.Amount);
public static SelfAccountBalance? Reduce(SelfBalanceCleared @event, SelfAccountBalance? current) => null;
}

View C# snippet source on GitHub

An addition creates or updates the balance; clearing it returns null, removing the state. Start with this form for new reducer code, then follow self-reducing read models to register and test it.

Use IReducerFor<T> when the fold needs injected services, instance behavior during replay, or must live apart from a shared model contract. See the separate-reducer guide.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record ReducersIndexDepositMade(decimal Amount);
[EventType]
public record ReducersIndexWithdrawalMade(decimal Amount);
public record ReducersIndexAccountBalance(decimal Balance, DateTimeOffset LastUpdated);
public class ReducersIndexAccountBalanceReducer : IReducerFor<ReducersIndexAccountBalance>
{
public ReducersIndexAccountBalance Deposited(ReducersIndexDepositMade @event, ReducersIndexAccountBalance? current, EventContext context)
{
var currentBalance = current?.Balance ?? 0m;
return new ReducersIndexAccountBalance(currentBalance + @event.Amount, context.Occurred);
}
public ReducersIndexAccountBalance WithdrawalMade(ReducersIndexWithdrawalMade @event, ReducersIndexAccountBalance? current, EventContext context)
{
var currentBalance = current?.Balance ?? 0m;
return new ReducersIndexAccountBalance(currentBalance - @event.Amount, context.Occurred);
}
}

View C# snippet source on GitHub

In .NET, a reducer class must target only one read model. Implementing two closed IReducerFor<TReadModel> interfaces, including through inheritance, throws TypeMustImplementOnlyOneReducer during default artifact discovery. Split the class into one reducer per read model. CHR0057 reports this before runtime.

If a contract assembly cannot reference Chronicle, the .NET client can explicitly nominate a plain instance reducer and infer its single read model from supported method signatures. The existing RegisterReducer APIs accept that form and a self reducer; follow explicit artifact registration for setup.

Use IReadModels to read the result by event source ID or retrieve a collection. Active maintenance is asynchronous, so a stored result may lag the latest append. Choose passive reads when you need to fold on demand, or decision reads when an admitted reducer must participate in guarding a later append.