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.
Key Concepts
Section titled “Key Concepts”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.
When to Use Reducers
Section titled “When to Use Reducers”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.
Start with transitions on the model
Section titled “Start with transitions on the model”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;}Kotlin does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851Java does not support this workflow yet.Track self-reducing read model support: https://github.com/Cratis/Chronicle/issues/4851This Chronicle client does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before using self-reducing read models from Elixir.TypeScript does not support this workflow yet.Track https://github.com/Cratis/Chronicle/issues/4851 before using this API from this language.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); }}import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.observation.Reducerimport io.cratis.chronicle.readModels.ReadModelimport java.time.Instant
@EventTypedata class ReducersIndexDepositMade(val amount: Double)
@EventTypedata class ReducersIndexWithdrawalMade(val amount: Double)
@ReadModeldata class ReducersIndexAccountBalance(val balance: Double = 0.0, val lastUpdated: Instant = Instant.EPOCH)
@Reducerclass ReducersIndexAccountBalanceReducer { fun deposited(event: ReducersIndexDepositMade, current: ReducersIndexAccountBalance?): ReducersIndexAccountBalance { val currentBalance = current?.balance ?: 0.0 return ReducersIndexAccountBalance(currentBalance + event.amount, Instant.now()) }
fun withdrawalMade(event: ReducersIndexWithdrawalMade, current: ReducersIndexAccountBalance?): ReducersIndexAccountBalance { val currentBalance = current?.balance ?: 0.0 return ReducersIndexAccountBalance(currentBalance - event.amount, Instant.now()) }}import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.observation.Reducer;import io.cratis.chronicle.readModels.ReadModel;import java.time.Instant;
@EventTyperecord ReducersIndexDepositMade(double amount) {}
@EventTyperecord ReducersIndexWithdrawalMade(double amount) {}
@ReadModelrecord ReducersIndexAccountBalance(double balance, Instant lastUpdated) { ReducersIndexAccountBalance() { this(0.0, Instant.EPOCH); }}
@Reducerclass ReducersIndexAccountBalanceReducer { ReducersIndexAccountBalance deposited(ReducersIndexDepositMade event, ReducersIndexAccountBalance current) { double currentBalance = current != null ? current.balance() : 0.0; return new ReducersIndexAccountBalance(currentBalance + event.amount(), Instant.now()); }
ReducersIndexAccountBalance withdrawalMade(ReducersIndexWithdrawalMade event, ReducersIndexAccountBalance current) { double currentBalance = current != null ? current.balance() : 0.0; return new ReducersIndexAccountBalance(currentBalance - event.amount(), Instant.now()); }}defmodule MyApp.Events.ReducersIndexDepositMade do use Cratis.Chronicle.Events.EventType, id: "reducers-index-deposit-made"
defstruct [:amount]end
defmodule MyApp.Events.ReducersIndexWithdrawalMade do use Cratis.Chronicle.Events.EventType, id: "reducers-index-withdrawal-made"
defstruct [:amount]end
defmodule MyApp.ReadModels.ReducersIndexAccountBalance do defstruct balance: 0, last_updated: nilend
defmodule MyApp.Reducers.ReducersIndexAccountBalanceReducer do use Cratis.Chronicle.Reducers.Reducer, model: MyApp.ReadModels.ReducersIndexAccountBalance
alias MyApp.Events.{ReducersIndexDepositMade, ReducersIndexWithdrawalMade} alias MyApp.ReadModels.ReducersIndexAccountBalance
@handles ReducersIndexDepositMade @handles ReducersIndexWithdrawalMade
@impl true def reduce(%ReducersIndexDepositMade{} = event, current, context) do current_balance = if current, do: current.balance, else: 0
%ReducersIndexAccountBalance{ balance: current_balance + event.amount, last_updated: Map.get(context, :occurred) } end
def reduce(%ReducersIndexWithdrawalMade{} = event, current, context) do current_balance = if current, do: current.balance, else: 0
%ReducersIndexAccountBalance{ balance: current_balance - event.amount, last_updated: Map.get(context, :occurred) } endendimport { eventType, reducer } from '@cratis/chronicle';
@eventType()class ReducersIndexDepositMade { amount = 0;}
@eventType()class ReducersIndexWithdrawalMade { amount = 0;}
class ReducersIndexAccountBalance { balance = 0; lastUpdated: Date = new Date(0);}
// Without @handles(EventType), handler method names must be the exact camelCase of the// event's class name - Chronicle discovers undecorated handlers by name, not by parameter type.@reducer('', undefined, ReducersIndexAccountBalance)class ReducersIndexAccountBalanceReducer { reducersIndexDepositMade( event: ReducersIndexDepositMade, current: ReducersIndexAccountBalance | undefined ): ReducersIndexAccountBalance { const currentBalance = current?.balance ?? 0; return { balance: currentBalance + event.amount, lastUpdated: new Date() }; }
reducersIndexWithdrawalMade( event: ReducersIndexWithdrawalMade, current: ReducersIndexAccountBalance | undefined ): ReducersIndexAccountBalance { const currentBalance = current?.balance ?? 0; return { balance: currentBalance - event.amount, lastUpdated: new Date() }; }}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.
Topics
Section titled “Topics”- Getting Started - Build a separate reducer when you need injected services or separation from the model
- Self-reducing read models - Keep static transitions on the read model
- Choose how to build a read model - One decision path with worked examples and switching costs
- Subscribe to External Event Stores - Configure outbox-to-inbox subscriptions for reducers
- Passive Reducers - Control when reducers actively observe events
- Event Processing - Understand how reducers process events
- Reducing Events in Batches - Fold all of a partition’s events in one method
- Event Sequence - Specify which event sequence a reducer observes
- Filtering by appended event metadata - Limit reducers to specific tags, event source types, or event stream types
- Tagging Reducers - How to use tags with reducers
Reading Your Reducer-Based Read Models
Section titled “Reading Your Reducer-Based Read Models”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.
- Getting a Single Instance - Retrieve a specific instance by key
- Getting a Collection of Instances - Retrieve all instances for reporting and analysis
- Getting Snapshots - Historical projection snapshots;
GetSnapshotsByIdcurrently returns no reducer history - Watching Read Models - Use
Watchfor reducer changes;GetWatcherForis projection-only