Skip to content

Choose passive or inactive Cratis Chronicle reducers

A passive Cratis Chronicle reducer reconstructs a read model by folding its events on demand: applying them in order to compute state rather than keeping a stored result up to date. Use it for occasional reads when repeating the fold is an acceptable cost. An inactive reducer is different: it stops observing events but still reads from its configured storage, which may be stale or empty.

A sink is the storage destination for materialized state. Choose whether you want to maintain that state before choosing whether the observer should run:

Configuration Active observation Sink By-id read
Default Enabled Configured sink Current materialized state, eventually consistent
[Reducer(isActive: false)] only Disabled Still configured Materialized state; it may be absent or stale
[Passive] on the read model Disabled None Reconstruct from the matching events

For a self reducer, the read model is also the reducer declaration, so place [Passive] on that same type. For a classic reducer, place it on the target model, not the reducer service.

In .NET, put [Passive] on the read model so normal by-ID reads fold its events on demand:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.ReadModels;
using Cratis.Chronicle.Reducers;
[EventType]
public record PassiveReducersTransactionCompleted(decimal Amount);
[Passive]
public record PassiveReducersAdHocReport(
decimal TotalRevenue,
int TransactionCount,
DateTimeOffset GeneratedAt);
public class PassiveReducersAdHocReportReducer : IReducerFor<PassiveReducersAdHocReport>
{
public PassiveReducersAdHocReport Completed(PassiveReducersTransactionCompleted @event, PassiveReducersAdHocReport? current, EventContext context)
{
var revenue = current?.TotalRevenue ?? 0m;
var count = current?.TransactionCount ?? 0;
return new PassiveReducersAdHocReport(
revenue + @event.Amount,
count + 1,
context.Occurred);
}
}

View C# snippet source on GitHub

This disables active observation regardless of the reducer’s isActive setting and selects on-demand reads through IReadModels. Read through that API rather than querying a storage collection; the passive model has no materialized sink.

using Cratis.Chronicle;
using Cratis.Chronicle.ReadModels;
public class PassiveReducersReportingService(IEventStore eventStore)
{
public async Task<PassiveReducersMonthlyRevenueReport> GenerateReport(Guid reportId) =>
// This triggers the passive reducer to compute state from events
await eventStore.ReadModels.GetInstanceById<PassiveReducersMonthlyRevenueReport>(reportId);
}

View C# snippet source on GitHub

No matching history means no instance. The same is true if filters reject every event. During the fold, returning null clears the computed state; a later accepted event can recreate it. Return current unchanged if you only mean to ignore an event.

Both classic and self passive reads apply the same filters as active delivery. An event needs to match any configured tag, plus each configured event source type and event stream type. See event metadata filtering when selecting the history to fold.

Use isActive: false when you want the observer registered but not running:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
[EventType]
public record PassiveReducersDataRecorded(decimal Value);
public record PassiveReducersAnalytics(int RecordCount, decimal TotalValue, DateTimeOffset LastUpdated);
[Reducer(isActive: false)]
public class PassiveReducersTemporaryAnalyticsReducer : IReducerFor<PassiveReducersAnalytics>
{
public PassiveReducersAnalytics Recorded(PassiveReducersDataRecorded @event, PassiveReducersAnalytics? current, EventContext context)
{
var count = current?.RecordCount ?? 0;
var sum = current?.TotalValue ?? 0m;
return new PassiveReducersAnalytics(count + 1, sum + @event.Value, context.Occurred);
}
}

View C# snippet source on GitHub

This does not make the model passive. Previously persisted state remains in its configured sink and is no longer maintained. By-id reads do not switch to event reconstruction unless the read model carries [Passive].

Bounded analysis, not arbitrary-date history

Section titled “Bounded analysis, not arbitrary-date history”

Use GetInstances(eventCount) to examine the state produced by a limited prefix of history. Chronicle first selects events of the handled types and takes the prefix, then applies metadata filters. Rejected events count toward the bound; they do not cause Chronicle to read farther for more accepted events.

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.ReadModels;
[EventType]
public record PassivePrefixAmountRecorded(decimal Amount);
[Passive]
public record PassiveReducersAccountBalance(decimal Balance)
{
public static PassiveReducersAccountBalance Reduce(PassivePrefixAmountRecorded @event, PassiveReducersAccountBalance? current) =>
new((current?.Balance ?? 0m) + @event.Amount);
}
public class PassiveReducersPrefixAnalysis(IEventStore eventStore)
{
public Task<IEnumerable<PassiveReducersAccountBalance>> GetBalancesFromPrefix(EventCount eventCount) =>
eventStore.ReadModels.GetInstances<PassiveReducersAccountBalance>(eventCount);
}

View C# snippet source on GitHub

The argument is an event count, not a date or a count of accepted events. GetSnapshotsById returns no reducer history. Use projection snapshots when you need that historical read surface rather than a reducer fold.

For an infrequent revenue report, you can compute totals from the matching payment history without maintaining another stored view:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.ReadModels;
using Cratis.Chronicle.Reducers;
[EventType]
public record PassiveReducersPaymentReceived(string Category, decimal Amount);
[Passive]
public record PassiveReducersMonthlyRevenueReport(
decimal TotalRevenue,
Dictionary<string, decimal> RevenueByCategory,
int Month,
int Year);
public class PassiveReducersMonthlyRevenueReportReducer : IReducerFor<PassiveReducersMonthlyRevenueReport>
{
public PassiveReducersMonthlyRevenueReport Received(PassiveReducersPaymentReceived @event, PassiveReducersMonthlyRevenueReport? current, EventContext context)
{
var revenue = current?.TotalRevenue ?? 0m;
var byCategory = current?.RevenueByCategory ?? new Dictionary<string, decimal>();
if (!byCategory.ContainsKey(@event.Category))
byCategory[@event.Category] = 0;
byCategory[@event.Category] += @event.Amount;
return new PassiveReducersMonthlyRevenueReport(
revenue + @event.Amount,
byCategory,
context.Occurred.Month,
context.Occurred.Year);
}
}

View C# snippet source on GitHub

The example accumulates payments; [Passive] does not itself restrict them to a calendar month. Define any reporting-window rule in the fold or the selected history.

For a new analysis, declare the state you want to examine, then supply its reducer before reading it:

using Cratis.Chronicle.ReadModels;
[Passive]
public record PassiveReducersCustomerBehaviorAnalysis(
int UniqueCustomers,
decimal AverageOrderValue,
Dictionary<int, int> OrdersByHour);

View C# snippet source on GitHub

Each on-demand read repeats the fold over the selected history. If the same report is read often, compare that work with maintaining a materialized reducer. Measure with the history size you expect; passive reads trade ongoing maintenance for work at read time, not a guaranteed reduction in cost.

To stop observation only in debug builds, conditionally apply the inactive configuration:

using Cratis.Chronicle.Reducers;
public record PassiveReducersExperimentalMetrics(int SampleCount);
#if DEBUG
[Reducer(isActive: false)]
#endif
public class PassiveReducersExperimentalMetricsReducer : IReducerFor<PassiveReducersExperimentalMetrics>;

View C# snippet source on GitHub

For an unconditional change, put the inactive setting directly on the reducer. This declaration shows the setting only; add the event handlers your model needs:

using Cratis.Chronicle.Reducers;
public record PassiveReducersSwitchableReadModel(int Value);
// Was active, now passive
[Reducer(isActive: false)]
public class PassiveReducersSwitchableReducer : IReducerFor<PassiveReducersSwitchableReadModel>;

View C# snippet source on GitHub

Changing isActive updates observer activity, not the model’s read strategy. Adding or removing [Passive] changes sink selection and by-id reconstruction semantics. Treat that as a read-model configuration change; do not assume toggling isActive has the same effect.

An on-demand fold does not protect a later write. Another writer can append between your read and your append, so a balance reconstructed for display is not enough to enforce a spending rule. Use a constraint or a decision read when the rule must hold at append time. Choosing how a rule holds helps you choose that boundary.

Passive and inactive reducers can both participate in decision reads, but activity settings do not bypass admission checks. Reducer decision reads require the event log, no metadata filters, one generation per event type, and no constructor dependencies other than ILogger<T> for an instance reducer. Decision reads for reducers covers the remaining checks.

Neither passive nor inactive reducers add stream-ID subscription filtering or exactly-once delivery. Keep the shared reducer limits in mind when changing a model from active maintenance to on-demand reads.