Skip to content

Process events with Cratis Chronicle reducers

Cratis Chronicle reducers apply each event to the state produced by the previous event for the same event source. Use this guide when implementing a fold, the function that combines an event with current state to produce the next state. Choose the handler shape and decide what a missing state means, then return new state without mutating a result another reader may hold.

The examples use C# and .NET dispatch rules. TypeScript handlers also receive context as (event, current, context); Kotlin and Java can accept EventContext as a third parameter, and Elixir receives a context map through reduce/3. Follow Getting started with reducers for each client’s handler conventions rather than copying C# syntax into another language.

For a .NET instance reducer, Chronicle matches methods by parameter type, not method name. Put the known event type first, the nullable current read model second, and an optional EventContext third. Return the model or Task<TReadModel>, including nullable results. A descriptive name helps readers find the transition but does not affect event matching.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingOrderCreated(Guid OrderId);
[EventType]
public record EventProcessingItemAdded(decimal Price);
public record EventProcessingOrderSummary(Guid OrderId, decimal Total, DateTimeOffset LastUpdated);
public class EventProcessingOrderSummaryReducer : IReducerFor<EventProcessingOrderSummary>
{
public EventProcessingOrderSummary Created(EventProcessingOrderCreated @event, EventProcessingOrderSummary? current, EventContext context)
{
return new EventProcessingOrderSummary(@event.OrderId, 0m, context.Occurred);
}
public EventProcessingOrderSummary? ItemAdded(EventProcessingItemAdded @event, EventProcessingOrderSummary? current, EventContext context)
{
if (current is null) return null; // Skip if no order exists
return current with
{
Total = current.Total + @event.Price,
LastUpdated = context.Occurred
};
}
}

View C# snippet source on GitHub

This section describes classic instance reducers. Self reducers use public static Reduce methods and uniquely most-specific dispatch; ambiguity fails rather than using method-name or context-overload tie-breaking.

A helper with the same reducer-shaped parameters can become a candidate for the same event. For .NET instance reducers, Chronicle selects one method per event type using this precedence:

  1. A public method takes precedence over a non-public method.
  2. At the same accessibility, a method with more parameters takes precedence, so the context overload wins.
  3. A remaining tie is resolved by method name in ordinal order, not reflection order.

A private method is still a valid reducer method when nothing else handles that event type — the precedence only decides between candidates, it does not disqualify any of them. If a helper is not meant to take part in dispatch at all, change its parameters so it no longer has the reducer shape.

Each event source has independent state. An order event receives that order’s current model, not another order’s model. Events for the same source are processed sequentially; this isolation does not provide ordering or coordination between different sources.

Within a delivered batch, Chronicle applies events in sequence-number order. Each return value becomes current for the next event. Retries and replay can deliver events again, so the fold must not rely on being invoked only once.

The simplest pattern accepts the event and current state:

public interface IEventProcessingBasicSyncPattern<TReadModel, TEvent>
where TReadModel : class
{
// Process event and return new state
TReadModel Process(TEvent @event, TReadModel? current);
}

View C# snippet source on GitHub

Add EventContext when the result depends on recorded metadata, such as occurrence time:

using Cratis.Chronicle.Events;
public interface IEventProcessingPatternWithContext<TReadModel, TEvent>
where TReadModel : class
{
// Access occurred time, correlation ID, etc.
TReadModel Process(TEvent @event, TReadModel? current, EventContext context);
}

View C# snippet source on GitHub

Both patterns support async methods:

using Cratis.Chronicle.Events;
public interface IEventProcessingAsyncPatterns<TReadModel, TEvent>
where TReadModel : class
{
// Async without context
Task<TReadModel> ProcessAsync(TEvent @event, TReadModel? current);
// Async with context
Task<TReadModel> ProcessWithContextAsync(TEvent @event, TReadModel? current, EventContext context);
}

View C# snippet source on GitHub

EventContext identifies the event’s source and sequence position and carries its recorded metadata:

using Cratis.Chronicle.Auditing;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Identities;
// Illustrative subset of Cratis.Chronicle.Events.EventContext's real shape
public record EventProcessingEventContextShape(
EventSequenceNumber SequenceNumber,
EventSourceId EventSourceId,
EventType EventType,
DateTimeOffset Occurred,
CorrelationId CorrelationId,
IEnumerable<Causation> Causation,
Identity CausedBy);
// ... and more — see EventContext for the full member list

View C# snippet source on GitHub

Use the event’s recorded occurrence time for a last-updated value. Reading the clock during a fold would produce a different timestamp when the same history is replayed:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingContextOrderPlaced(Guid OrderId, decimal Amount);
public record EventProcessingOrderSummaryWithContext(
Guid OrderId,
decimal Total,
DateTimeOffset PlacedAt,
string PlacedBy,
CorrelationId CorrelationId);
public class EventProcessingOrderSummaryWithContextReducer : IReducerFor<EventProcessingOrderSummaryWithContext>
{
public EventProcessingOrderSummaryWithContext Placed(EventProcessingContextOrderPlaced @event, EventProcessingOrderSummaryWithContext? current, EventContext context) =>
new(
OrderId: @event.OrderId,
Total: @event.Amount,
PlacedAt: context.Occurred,
PlacedBy: context.CausedBy.ToString()!,
CorrelationId: context.CorrelationId);
}

View C# snippet source on GitHub

The current parameter represents the previously computed state for this event source.

When an event source has no state yet, current is null. Initialize the model from an event that can create it. For other events, declare a nullable return type such as TReadModel? and return null if the model should remain absent.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingDataRecorded(decimal Value);
public record EventProcessingAnalytics(int EventCount, DateTimeOffset FirstEventTime, DateTimeOffset LastEventTime, decimal TotalValue);
public class EventProcessingAnalyticsReducer : IReducerFor<EventProcessingAnalytics>
{
public EventProcessingAnalytics Recorded(EventProcessingDataRecorded @event, EventProcessingAnalytics? current, EventContext context)
{
if (current is null)
{
// First event - initialize state
return new EventProcessingAnalytics(
EventCount: 1,
FirstEventTime: context.Occurred,
LastEventTime: context.Occurred,
TotalValue: @event.Value);
}
// Update existing state
return current with
{
EventCount = current.EventCount + 1,
LastEventTime = context.Occurred,
TotalValue = current.TotalValue + @event.Value
};
}
}

View C# snippet source on GitHub

After creation, current contains the previous event’s result. A C# record’s with expression lets you return a changed copy. If a later transition removes the model, the following event receives null again, so null handling is not just a first-event concern.

Keep a running sum and count to calculate an average without retaining every value:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingMetricRecorded(decimal Value);
public record EventProcessingStatistics(decimal Sum, int Count, decimal Average);
public class EventProcessingStatisticsReducer : IReducerFor<EventProcessingStatistics>
{
public EventProcessingStatistics Recorded(EventProcessingMetricRecorded @event, EventProcessingStatistics? current)
{
var sum = (current?.Sum ?? 0) + @event.Value;
var count = (current?.Count ?? 0) + 1;
return new EventProcessingStatistics(sum, count, sum / count);
}
}

View C# snippet source on GitHub

Represent order progress as state changes, recording the time of each transition from event context:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingOrderCreatedForStatus(Guid OrderId);
[EventType]
public record EventProcessingOrderPaid(Guid OrderId);
[EventType]
public record EventProcessingOrderShipped(Guid OrderId);
[EventType]
public record EventProcessingOrderDelivered(Guid OrderId);
[EventType]
public record EventProcessingOrderCancelled(Guid OrderId);
public record EventProcessingOrderStatus(string State, DateTimeOffset LastUpdated);
public class EventProcessingOrderStatusReducer : IReducerFor<EventProcessingOrderStatus>
{
public EventProcessingOrderStatus Created(EventProcessingOrderCreatedForStatus @event, EventProcessingOrderStatus? current, EventContext context)
=> new EventProcessingOrderStatus("Created", context.Occurred);
public EventProcessingOrderStatus Paid(EventProcessingOrderPaid @event, EventProcessingOrderStatus? current, EventContext context)
=> new EventProcessingOrderStatus("Paid", context.Occurred);
public EventProcessingOrderStatus Shipped(EventProcessingOrderShipped @event, EventProcessingOrderStatus? current, EventContext context)
=> new EventProcessingOrderStatus("Shipped", context.Occurred);
public EventProcessingOrderStatus Delivered(EventProcessingOrderDelivered @event, EventProcessingOrderStatus? current, EventContext context)
=> new EventProcessingOrderStatus("Delivered", context.Occurred);
public EventProcessingOrderStatus Cancelled(EventProcessingOrderCancelled @event, EventProcessingOrderStatus? current, EventContext context)
=> new EventProcessingOrderStatus("Cancelled", context.Occurred);
}

View C# snippet source on GitHub

Build an activity log by copying the previous list before adding the new entry. Returning a new record alone would not copy a mutable list inside it:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingCustomerAction(string Type, string Description);
public record EventProcessingActivity(string Type, DateTimeOffset Timestamp, string Description);
public record EventProcessingCustomerActivityLog(List<EventProcessingActivity> Activities);
public class EventProcessingCustomerActivityLogReducer : IReducerFor<EventProcessingCustomerActivityLog>
{
public EventProcessingCustomerActivityLog Recorded(EventProcessingCustomerAction @event, EventProcessingCustomerActivityLog? current, EventContext context)
{
// Copy rather than mutate — current.Activities may still be referenced by a held snapshot
var activities = new List<EventProcessingActivity>(current?.Activities ?? []);
activities.Add(new EventProcessingActivity(
@event.Type,
context.Occurred,
@event.Description));
return new EventProcessingCustomerActivityLog(activities);
}
}

View C# snippet source on GitHub

Group metrics by the hour in the recorded event time. This example combines the same hour across all dates; include a date in the key if each day’s hours must stay separate:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingHourlyMetricRecorded(decimal Value);
public record EventProcessingHourlyMetrics(Dictionary<int, decimal> MetricsByHour);
public class EventProcessingHourlyMetricsReducer : IReducerFor<EventProcessingHourlyMetrics>
{
public EventProcessingHourlyMetrics Recorded(EventProcessingHourlyMetricRecorded @event, EventProcessingHourlyMetrics? current, EventContext context)
{
var metricsByHour = new Dictionary<int, decimal>(current?.MetricsByHour ?? []);
var hour = context.Occurred.Hour;
if (!metricsByHour.ContainsKey(hour))
metricsByHour[hour] = 0;
metricsByHour[hour] += @event.Value;
return new EventProcessingHourlyMetrics(metricsByHour);
}
}

View C# snippet source on GitHub

Return the existing state when a condition means the event should have no effect:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingAccountOpened(Guid AccountId);
[EventType]
public record EventProcessingDepositMade(decimal Amount);
[EventType]
public record EventProcessingAccountClosed;
public record EventProcessingAccount(Guid AccountId, decimal Balance, bool IsActive);
public class EventProcessingAccountReducer : IReducerFor<EventProcessingAccount>
{
public EventProcessingAccount Opened(EventProcessingAccountOpened @event, EventProcessingAccount? current, EventContext context)
{
return new EventProcessingAccount(@event.AccountId, 0m, true);
}
public EventProcessingAccount? DepositMade(EventProcessingDepositMade @event, EventProcessingAccount? current, EventContext context)
{
// Skip if account doesn't exist or is not active
if (current is null || !current.IsActive) return current;
return current with { Balance = current.Balance + @event.Amount };
}
public EventProcessingAccount? Closed(EventProcessingAccountClosed @event, EventProcessingAccount? current, EventContext context)
{
if (current is null) return null;
return current with { IsActive = false };
}
}

View C# snippet source on GitHub

If a handler fails, Chronicle does not persist the successfully reduced prefix of that batch. In .NET, failed folds do not notify watchers. A successful fold does notify them before the Kernel persists its result, so Watch is still not a persistence-success signal (#4817). Classic and self reducers share this behavior.

When there’s no state to build on yet, return null from a nullable-returning handler (TReadModel? Handle(...)) to leave the read model unset:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingSkipItemAdded(decimal Price);
public record EventProcessingSkipOrderSummary(decimal Total);
public class EventProcessingSkipOrderSummaryReducer : IReducerFor<EventProcessingSkipOrderSummary>
{
public EventProcessingSkipOrderSummary? ItemAdded(EventProcessingSkipItemAdded @event, EventProcessingSkipOrderSummary? current, EventContext context)
{
// Can't add items if order doesn't exist
if (current is null) return null;
return current with
{
Total = current.Total + @event.Price
};
}
}

View C# snippet source on GitHub

Note the difference between skipping an event and removing a read model: returning null when current was already null is a no-op, but returning null when current holds real state deletes that read model. To ignore an event without discarding existing state, return current unchanged instead.

If invalid input is a result the view should expose rather than an exception that should stop the fold, represent that error in the model:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingInvalidDataDetected(string Reason);
public record EventProcessingValidationResult(bool IsValid, List<string> Errors);
public class EventProcessingValidationResultReducer : IReducerFor<EventProcessingValidationResult>
{
public EventProcessingValidationResult Detected(EventProcessingInvalidDataDetected @event, EventProcessingValidationResult? current)
{
var errors = new List<string>(current?.Errors ?? []) { @event.Reason };
return new EventProcessingValidationResult(false, errors);
}
}

View C# snippet source on GitHub

Measure a fold with representative histories before optimizing it. Reducing allocations must not come at the cost of mutating state that has already been returned.

A record’s with expression makes a shallow copy with selected changes. It keeps the transition readable, but it still creates a record and does not copy nested collections:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingMinimalMetricRecorded(decimal Value);
public record EventProcessingMinimalStats(int Count, decimal Sum);
public class EventProcessingMinimalStatsReducer : IReducerFor<EventProcessingMinimalStats>
{
// Efficient - only creates a new object when needed
public EventProcessingMinimalStats Recorded(EventProcessingMinimalMetricRecorded @event, EventProcessingMinimalStats? current)
{
if (current is null)
return new EventProcessingMinimalStats(Count: 1, Sum: @event.Value);
return current with
{
Count = current.Count + 1,
Sum = current.Sum + @event.Value
};
}
}

View C# snippet source on GitHub

Copy a collection before changing it. A snapshot or another reader may still hold the previous state, including the same collection reference:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record EventProcessingReuseItemAdded(Guid ItemId, string Name);
public record EventProcessingItem(Guid ItemId, string Name);
public record EventProcessingItemList(List<EventProcessingItem> Items);
public class EventProcessingItemListReducer : IReducerFor<EventProcessingItemList>
{
public EventProcessingItemList ItemAdded(EventProcessingReuseItemAdded @event, EventProcessingItemList? current)
{
// Copy rather than mutate current.Items directly — a held snapshot may still reference it
var items = new List<EventProcessingItem>(current?.Items ?? [])
{
new(@event.ItemId, @event.Name)
};
return new EventProcessingItemList(items);
}
}

View C# snippet source on GitHub

Keep the fold deterministic: compute from the event, its context, and the current state rather than live external values. Do not send messages or write elsewhere from a transition; retries and replay can repeat those side effects.

Test creation, updates, removal, and recreation, including events that arrive without prior state. ReadModelScenario lets you check the resulting model through the registered reducer.

Concurrency Across Partitions (.NET client)

Section titled “Concurrency Across Partitions (.NET client)”

A partition is the unit of state and ordering, normally one event source. Within a partition, the .NET client runs batches in arrival order. Different partitions of the same reducer can run at the same time, so reducer code and its services must be safe for concurrent use. There is no ordering across partitions. Replay begin and end notifications wait for work in flight; results are reported to the Kernel one at a time.

Reducers.MaxConcurrentPartitions in ChronicleOptions defaults to the processor count, capped at 8. Set it to 1 when you need batches handled one at a time.