Skip to content

Chronicle read models — choose a projection or reducer

Use a Chronicle projection when events map directly to a read model’s fields; use a reducer when the next state is clearer as code that reads the previous state. Choose whether to store the result or compute it on demand separately from that authoring decision.

Suppose your library screen needs a book’s title and current borrower. Registration, borrowing, and return events contain the history, but the screen needs one current answer. Copying the title fits a mapping. A calculation that branches on the previous loan state may be clearer in a reducer.

Chronicle offers two families. Projections describe mappings that the kernel executes: attributes on the model, a fluent IProjectionFor<T> definition, or Projection Declaration Language (PDL). Reducers run your code as a fold: each event and the previous state produce the next state through static Reduce methods on the model, a separate IReducerFor<T>, or an explicitly nominated plain class. Authoring placement changes within each family; moving between families also changes execution and capabilities.

For application code, follow this order:

  1. Start with model-bound attributes when the mapping reads clearly on the model.
  2. Use fluent IProjectionFor<T> when the mapping needs structure or the model should stay attribute-free.
  3. Choose a reducer when the answer reads better as state-transition code. For new code, start with a self-reducing read model. Use a separate IReducerFor<T> when you need fold-time dependency injection, instance state used during replay, or separation from the model.
  4. Nominate a plain reducer class only when the reducer or contract assembly cannot reference Chronicle.

Use PDL when the definition belongs outside application code, such as the Workbench, Screenplay, or an ad-hoc query. It is another projection input, not the code-first default.

You need… Pick Why
A screen showing a book’s title and current borrower Model-bound attributes The events directly set or clear properties. Keep those mappings next to the shape the screen reads.
A dashboard counting loans or summing amounts A projection; attributes first Counting, incrementing, adding, and subtracting are built-in operations. For one total across event sources, use a constant key; arithmetic alone does not require a reducer.
A library with a collection of books Fluent projection when the attributes become hard to scan Children describe child identity, parent routing, updates, and removal. Attributes support children too.
A book view with a member’s details from another event source A projection, often fluent A join correlates events across sources and updates the view. Reducers fold one event source at a time and have no native join operation.
Composite keys, context fields, or an attribute-free model Fluent projection The builder makes key structure and context mappings explicit without decorating the model.
A status that depends on the previous status and a rule Self-reducing model Branch on current and return the next state. The rule and state live together.
A running balance that ignores a debit under a guard Self-reducing model Read the previous balance, apply the guard, and calculate the result in code. This derives a view; it does not reject the already-appended debit.
A fold that needs a currency-rate service or clock Separate IReducerFor<T> Constructor injection is available during the fold. Static Reduce accepts only event, current, and optional context. Prefer recording the rate or time in the event: consulting today’s service during replay can change yesterday’s result.
A model distributed as a shared contract Separate IReducerFor<T> for stateful logic; fluent projection for mapping Keep behavior in the consuming application without adding transitions or mapping attributes to the contract.
An observer assembly that cannot reference Chronicle Nominated plain class Register it at the composition root and let Chronicle infer its one model from supported instance methods. Nomination does not relax signature validation.
An Arc application with queries and state transitions on one record Self-reducing model with [ReadModel] and static query methods Keep the state, static Reduce methods, and query surface together. Apply the version guidance below so reduction does not become an endpoint.
State a command must read on demand A passive model [Passive] on the model, or .Passive() on a fluent projection, avoids materialization lag. For a decision that must remain valid until append, use decision reads only with an admitted projection or reducer shape. A fresh passive reducer read does not protect the decision from a concurrent append.
A definition edited in the Workbench or authored in Screenplay PDL The definition is text owned by the tooling workflow. Check Chronicle’s supported expression subset and save settings.

Compare the forms using the same events. The snippets are alternatives in a Chronicle-enabled application with default artifact discovery, not four builders to attach to one model.

using Cratis.Chronicle.Compliance.GDPR;
using Cratis.Chronicle.Events;
[EventType]
public record ChoosingStyleBookRegistered(string Title, string Isbn);
[EventType]
public record ChoosingStyleBookBorrowed([PII] string MemberName);
[EventType]
public record ChoosingStyleBookReturned;

View C# snippet source on GitHub

The view has the following fields. Title and Isbn are nullable because a loan event may arrive without a registration in this history.

using Cratis.Chronicle.Compliance.GDPR;
public record ChoosingStyleBookStatus(
string Id,
string? Title,
string? Isbn,
bool IsBorrowed,
[PII] string? BorrowedBy);

View C# snippet source on GitHub

These examples deliberately define registration as a reset of loan state. Borrowing sets the borrower; returning clears it. Borrowing or returning without prior state creates a partial view with the book’s ID and no title or ISBN. This is a view policy, not an assertion that such a loan is allowed.

Model-bound: describe the mapping on the model

Section titled “Model-bound: describe the mapping on the model”
using Cratis.Chronicle.Compliance.GDPR;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
public record ChoosingStyleBookStatusModelBound(
[Key] string Id,
[SetFrom<ChoosingStyleBookRegistered>] string? Title,
[SetFrom<ChoosingStyleBookRegistered>] string? Isbn,
[SetValue<ChoosingStyleBookRegistered>(false)]
[SetValue<ChoosingStyleBookBorrowed>(true)]
[SetValue<ChoosingStyleBookReturned>(false)]
bool IsBorrowed,
[PII]
[SetFrom<ChoosingStyleBookBorrowed>(nameof(ChoosingStyleBookBorrowed.MemberName))]
[ClearWith<ChoosingStyleBookRegistered>]
[ClearWith<ChoosingStyleBookReturned>]
string? BorrowedBy);

View C# snippet source on GitHub

Chronicle discovers the mapping attributes and builds a projection definition. Registration sets the bibliographic fields and resets both loan fields. The explicit clear matters when a book is registered again after a loan; an omitted mapping would leave the old borrower in place.

using Cratis.Chronicle.Compliance.GDPR;
using Cratis.Chronicle.Projections;
public record ChoosingStyleBookStatusFluent(
string Id,
string? Title,
string? Isbn,
bool IsBorrowed,
[PII] string? BorrowedBy);
public class ChoosingStyleBookStatusProjection : IProjectionFor<ChoosingStyleBookStatusFluent>
{
public void Define(IProjectionBuilderFor<ChoosingStyleBookStatusFluent> builder) => builder
.From<ChoosingStyleBookRegistered>(_ => _
.Set(m => m.Id).ToEventSourceId()
.Set(m => m.IsBorrowed).ToValue(false)
.Clear(m => m.BorrowedBy))
.From<ChoosingStyleBookBorrowed>(_ => _
.Set(m => m.Id).ToEventSourceId()
.Set(m => m.IsBorrowed).ToValue(true)
.Set(m => m.BorrowedBy).To(e => e.MemberName))
.From<ChoosingStyleBookReturned>(_ => _
.Set(m => m.Id).ToEventSourceId()
.Set(m => m.IsBorrowed).ToValue(false)
.Clear(m => m.BorrowedBy));
}

View C# snippet source on GitHub

AutoMap supplies Title and Isbn from registration without an .AutoMap() call. The other mappings set the ID and loan fields explicitly. Define constructs a definition once for registration; these lambdas are not service-injected handlers called for each arriving event.

This is still a kernel projection. Move to fluent for a clearer definition or richer mapping structure, not to run arbitrary business code inside event processing.

Self-reducing: keep transitions with the state

Section titled “Self-reducing: keep transitions with the state”
using Cratis.Chronicle.Compliance.GDPR;
using Cratis.Chronicle.Events;
public record ChoosingStyleBookStatusSelfReducing(
string Id,
string? Title,
string? Isbn,
bool IsBorrowed,
[PII] string? BorrowedBy)
{
public static ChoosingStyleBookStatusSelfReducing Reduce(
ChoosingStyleBookRegistered @event,
ChoosingStyleBookStatusSelfReducing? current,
EventContext context) =>
new(context.EventSourceId.Value, @event.Title, @event.Isbn, false, null);
public static ChoosingStyleBookStatusSelfReducing Reduce(
ChoosingStyleBookBorrowed @event,
ChoosingStyleBookStatusSelfReducing? current,
EventContext context) =>
(current ?? new(context.EventSourceId.Value, null, null, false, null)) with
{
IsBorrowed = true,
BorrowedBy = @event.MemberName
};
public static ChoosingStyleBookStatusSelfReducing Reduce(
ChoosingStyleBookReturned @event,
ChoosingStyleBookStatusSelfReducing? current,
EventContext context) =>
(current ?? new(context.EventSourceId.Value, null, null, false, null)) with
{
IsBorrowed = false,
BorrowedBy = null
};
}

View C# snippet source on GitHub

The complete public static Reduce shape is the discovery signal. Chronicle needs no model instance or reducer marker to invoke it. Each handler accepts nullable current state, including the loan and return handlers: either event can be the first event seen, or follow removal.

Separate reducer: put the fold on an instance

Section titled “Separate reducer: put the fold on an instance”
using Cratis.Chronicle.Compliance.GDPR;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
public record ChoosingStyleBookStatusReducerModel(
string Id,
string? Title,
string? Isbn,
bool IsBorrowed,
[PII] string? BorrowedBy);
public class ChoosingStyleBookStatusReducer : IReducerFor<ChoosingStyleBookStatusReducerModel>
{
public ChoosingStyleBookStatusReducerModel OnBookRegistered(
ChoosingStyleBookRegistered @event,
ChoosingStyleBookStatusReducerModel? current,
EventContext context) =>
new(
Id: context.EventSourceId.Value,
Title: @event.Title,
Isbn: @event.Isbn,
IsBorrowed: false,
BorrowedBy: null);
public ChoosingStyleBookStatusReducerModel OnBookBorrowed(
ChoosingStyleBookBorrowed @event,
ChoosingStyleBookStatusReducerModel? current,
EventContext context) =>
(current ?? new(context.EventSourceId.Value, null, null, false, null)) with
{
IsBorrowed = true,
BorrowedBy = @event.MemberName
};
public ChoosingStyleBookStatusReducerModel OnBookReturned(
ChoosingStyleBookReturned @event,
ChoosingStyleBookStatusReducerModel? current,
EventContext context) =>
(current ?? new(context.EventSourceId.Value, null, null, false, null)) with
{
IsBorrowed = false,
BorrowedBy = null
};
}

View C# snippet source on GitHub

The same transitions now live in an IReducerFor<T> class. Chronicle activates that class through its service provider. This extra type is useful when the fold needs constructor dependencies or the model must remain a data contract. A plain nominated reducer uses the same instance fold, with its model inferred at explicit registration.

For event source book-42, all four implementations produce these field values:

Event history Title / ISBN Borrowed? Borrower
No events No instance — —
Registered(“Dune”, “9780441172719”) Dune / 9780441172719 false not set
Registered → Borrowed(“Avery”) Dune / 9780441172719 true Avery
Registered → Borrowed → Returned Dune / 9780441172719 false not set
Registered → Borrowed → Registered(“Dune”, “9780441172719”) Dune / 9780441172719 false not set
Borrowed(“Avery”) without registration not set true Avery
Returned without registration not set false not set

“Not set” means the field holds no value; each client shows that in its own way. Id is book-42 in every existing instance. The snippets use distinct model type names so they can compile together; those names give them different registered identifiers and default containers. Equivalent field values do not make them interchangeable persisted documents.

The borrower’s name is personal data. The snippets mark both the event member and the destination member as personal data; a mapping does not transfer compliance annotations. In a real library, select the member as the append’s subject rather than accepting the book ID fallback. Review read-model compliance before deploying: projections retain per-property subject lineage, while reducer protection uses the batch’s default subject resolved from its first event. Output equality alone does not prove equal subject ownership.

The API names here follow the .NET examples. Consult each page’s client tabs for its authoring shape. The separate column covers both IReducerFor<T> and a nominated plain instance reducer.

Capability Attributes Fluent PDL Self reducer Separate reducer
Logic location Model metadata Separate Define class Declaration text Static model methods Instance methods on another class
Dependency injection during fold No No; DI can build the definition No No Yes
Joins across event sources Yes Yes Yes No native joins No native joins
Children / nested objects Mappings Mappings Blocks Your code Your code
Counters and sums Operations; no dynamic dictionary-counter form Operations, including dynamic dictionary counters Operations Your code, per source Your code, per source
Dictionary entries keyed per event No dynamic dictionary form Set, set once, sums, counters and key removal keyed by event content or context No clause yet Your code Your code
Set a value only once SetOnce = true on SetFrom / SetFromContext SetOnce(...) No clause yet Your code, guarded on current state Your code, guarded on current state
Ordering new children Prepend / OrderBy / OrderByDescending on ChildrenFrom Prepend() / OrderBy() / OrderByDescending() No clause yet Your code Your code
Remove an instance Removal attributes Removal builders Removal blocks Return null Return null
Variant groups VariantOf / EntersOn / GlobalFor VariantOf / EntersOn; no GlobalFor equivalent No native group block No native group wiring No native group wiring
Passive reads [Passive] on model .Passive() No native passive clause [Passive] on model [Passive] on model
Append-metadata filters No No No Tags, source type, stream type Tags, source type, stream type
Replay lifecycle hooks No handler hooks No handler hooks No hook clauses Static Task hooks; hook services allowed Replay notification interfaces
Decision reads Admitted shapes only Admitted shapes only No direct .NET client-catalog registration path Admitted shapes without filters Admitted shapes without filters; constructor dependencies limited to ILogger<T>
ReadModelScenario Yes Yes No direct PDL overload Yes Yes, including nominated plain classes

Metadata subscription filters have no stream-ID option. Observer tags are descriptive labels, not append-tag filters. For decision reads, check admission before building the workflow: the projection must be a finite, flat event-log shape without joins or hierarchy, with a supported source key (or an admitted stream-scoped key). PDL’s save path also chooses effective sequence and generation settings; do not assume a declaration has every configuration option of a code-authored projection.

If a mapping hides several branches over previous state or guarded calculations, use a reducer. Adding a fluent class does not turn the mapping engine into arbitrary per-event code. PDL likewise accepts Chronicle’s supported projection expressions, not every expression accepted by Screenplay.

Keep a projection when a reducer would make you rebuild mapping features yourself. Counts and sums already have operations. Cross-source joins, custom aggregation keys, and mutually exclusive variant groups belong to projections; reducers are event-source keyed. Keeping the first value an event supplies, adding and removing dictionary entries keyed by an event value, and keeping children newest first or sorted are projection operations too, so none of them alone is a reason to write a reducer.

A reducer’s dependencies also affect where you can read it. A classic reducer with filters or constructor dependencies other than ILogger<T> cannot serve a protected decision read. A self-reducing model has no constructor-dependency restriction. Check reducer decision-read admission before choosing the form for a command’s state check.

Choose an instance reducer when its separation, dependency injection, or instance behavior is useful. Keep durable state in the read model, not the service instance. Replay invokes your code again, and none of the reducer forms promises exactly-once execution or external effects.

Choose materialized or passive reads separately from authoring style. Passive by-ID projection reads select one event source, so cross-source joins and custom-key aggregations cannot generally reconstruct the materialized answer that way. Passive reads are not a synchronous append mode, and an on-demand result does not enforce uniqueness.

You can keep event contracts, the read-model schema, the query surface, and the expected field values when the new form expresses the same behavior. Storage continuity takes more care:

What to check Why it matters
Read-model identifier In .NET it is the full model type name. Renaming or moving the model changes that identity.
Observer identifier and scope Attributes default to the model’s full name; fluent and separate reducer classes default to their own full names; self reducers default to the model’s full name; PDL uses its declaration name. Explicit IDs can preserve observer identity, but store, namespace, and sequence also scope progress.
Container name The default .NET naming policy pluralizes the short model name. A new identity may get a different default container; a namespace move can keep the container while changing identity. Fluent projections can override the container; reducers have no equivalent override. Ordinary registration refuses a different container for the same identity, including case-only changes. Keep naming policies consistent across clients; use an explicit definition update for an intentional change. Updating the definition does not move data.
Replay or rebuild Definition and reducer-implementation changes are evaluated under the configured evolution policy. Expect replay work or a recommendation; not every source edit triggers a full rebuild. Reusing an ID across projection and reducer kinds is not a state or schema migration.
Compliance lineage A projection’s per-property subject tracking and a reducer’s batch/default subject protection differ. Keep model PII annotations and verify subject ownership, release, and erasure after a family change.

Before switching, record the existing IDs, scope, container, and configuration. Preserve the identifiers you intend to keep and remove the previous builder; a self-reducing model cannot share ownership with another reducer or projection in the same catalog. When moving a fold to static methods, decide how to replace constructor dependencies and replay interfaces as part of the change.

Run the same event histories against the replacement, then exercise registration and replay against a real kernel and the intended sink. Verify stored-state compatibility, catch-up, query results, indexes, and compliance. Inspect registration outcomes and projection evolution and retirement; a running client alone does not prove every definition registered. Coordinate stopping the old writer before starting the replacement. Projection retirement retains its container, and its successor recommendations concern projections, not reducers. Plan the rebuild explicitly when changing families.

The same ReadModelScenario can exercise all four application-code forms above, as well as a nominated plain reducer configured through per-run defaults. Give each form the same events and assert the same fields, including re-registration and missing current state.

using Cratis.Chronicle;
using Cratis.Chronicle.Testing;
using Cratis.Chronicle.Testing.ReadModels;
using Cratis.Specifications;
// Uses the events and four implementations above. Call VerifyAll() from a test.
public static class ChoosingStyleVerification
{
public static async Task VerifyAll()
{
await Verify<ChoosingStyleBookStatusModelBound>(m => new(m.Id, m.Title, m.Isbn, m.IsBorrowed, m.BorrowedBy));
await Verify<ChoosingStyleBookStatusFluent>(m => new(m.Id, m.Title, m.Isbn, m.IsBorrowed, m.BorrowedBy));
await Verify<ChoosingStyleBookStatusSelfReducing>(m => new(m.Id, m.Title, m.Isbn, m.IsBorrowed, m.BorrowedBy));
await Verify<ChoosingStyleBookStatusReducerModel>(m => new(m.Id, m.Title, m.Isbn, m.IsBorrowed, m.BorrowedBy));
}
static async Task Verify<T>(Func<T, ChoosingStyleBookStatus> fields) where T : class
{
var artifacts = new InMemoryClientArtifactsProvider
{
EventTypes = [typeof(ChoosingStyleBookRegistered), typeof(ChoosingStyleBookBorrowed), typeof(ChoosingStyleBookReturned)],
ModelBoundProjections = [typeof(ChoosingStyleBookStatusModelBound)],
Projections = [typeof(ChoosingStyleBookStatusProjection)],
Reducers = [typeof(ChoosingStyleBookStatusSelfReducing), typeof(ChoosingStyleBookStatusReducer)]
};
var defaults = new Defaults(artifacts);
var registered = new ChoosingStyleBookRegistered("Dune", "9780441172719");
var borrowed = new ChoosingStyleBookBorrowed("Avery");
var returned = new ChoosingStyleBookReturned();
var available = new ChoosingStyleBookStatus("book-42", "Dune", "9780441172719", false, null);
var empty = new ReadModelScenario<T>(null, defaults);
empty.Instance!.ShouldBeNull();
await Check([registered], available);
await Check([registered, borrowed], available with { IsBorrowed = true, BorrowedBy = "Avery" });
await Check([registered, borrowed, returned], available);
await Check([registered, borrowed, registered], available);
await Check([borrowed], new("book-42", null, null, true, "Avery"));
await Check([returned], new("book-42", null, null, false, null));
async Task Check(object[] events, ChoosingStyleBookStatus expected)
{
var scenario = new ReadModelScenario<T>(null, defaults);
await scenario.Given.ForEventSource("book-42").Events(events);
fields(scenario.Instance!).ShouldEqual(expected);
}
}
}

View C# snippet source on GitHub

The check compares values rather than model type identity. In-process scenarios substitute storage, observer lifecycle, and read-model compliance: they do not prove transport, replay policy, encryption, erasure, sink subject ownership, or migration of existing documents. Keep the scenario as a behavioral regression check and add a real-kernel check before treating a style change as an operationally safe replacement.