Skip to content

Designing read models in Cratis Chronicle

A read model in Cratis Chronicle is a view derived from events and shaped for a query. Design it around what a screen or report needs to read, then choose how it is built and how fresh the answer must be.

Modeling events preserves business facts. Read-model design gives those same facts different useful shapes, without making the stored events depend on a particular screen.

A read model is computed from events by a projection or reducer. When its shape no longer fits, change the mapping and rebuild it from the relevant history rather than treating the old document as the source of truth.

Rebuilding still has an operational cost: it takes work to replay events, write the new state, and coordinate the change with readers. Keep the model derived entirely from events so that a rebuild does not lose manually added data.

Start with the query rather than copying the write-side domain model:

  • A list screen wants a flat, denormalized row per item.
  • A detail screen wants one rich document with its children embedded.
  • A dashboard wants pre-aggregated counts.

These can be separate read models built from the same events. Denormalizing avoids joins or calculations on the read path, at the cost of more stored data and projection work. Keep updates in the projection or reducer, not in ad hoc writes to the resulting documents.

Split a shared Customer read model when its consumers need conflicting shapes or change independently. A dedicated model lets you change the billing view without also reshaping the customer list. If several queries genuinely need the same fields and consistency, sharing a model can be simpler; duplicating it adds storage and maintenance without changing the answer.

❌ One CustomerReadModel feeding the list, the detail page, and the billing report
✅ CustomerListItem · CustomerDetail · CustomerBillingSummary — each from the same events

Start with model-bound projections, where attributes describe how event properties map onto the read model. Use the fluent declarative projection builder (IProjectionFor<T>) when the mapping needs more explicit configuration. Choose a reducer when code that combines an event with previous state expresses the calculation more clearly. Both approaches derive state; neither should perform external side effects.

Do not rely on a read model’s constructor or property initializer to normalize stored data. This C# record tries to turn a null collection into an empty one:

public record LineItem(string ProductName, int Quantity, decimal Price);
// Don't rely on this. It may never execute.
public record OrderSummary(OrderId Id, IEnumerable<LineItem> Lines)
{
public IEnumerable<LineItem> Lines { get; init; } = Lines ?? [];
}

View C# snippet source on GitHub

Chronicle’s .NET reader deserializes read models with System.Text.Json. Reading the same document through IMongoCollection<T> uses the MongoDB driver’s serializer and its configured class maps instead. Those paths need not construct or populate a record in the same way. Even when an initializer runs, assigning the stored property value can replace its result.

Put defaults in the projected state so readers see stored values, rather than relying on construction-time logic. Validate business rules before appending events, not while reading the facts back:

You want Where it belongs
An empty collection rather than null A supported non-nullable collection declaration when using Chronicle’s reader. See Empty child collections for supported types and other readers.
A meaningful default before any event assigns the property The projection — SetValue or initial values — so the default is part of the projected state every reader sees.
A rule that rejects bad data The write side, before the event is appended. A read model is derived from facts that already happened; refusing them here is too late to help.

A materialized read model is stored by an observer after events are appended, so it is eventually consistent: a successful append does not mean the view has caught up. Use observable queries when the UI should receive updated results as that happens.

If a read must include the appended history without waiting for materialization, mark the model [Passive]. IReadModels then computes it from events on demand rather than reading an asynchronously updated view. That trades replay work on the read path for freshness:

using Cratis.Chronicle;
using Cratis.Chronicle.ReadModels;
// Passive: no observer materializes this, so Chronicle computes it from the events on every read.
[Passive]
public record DesigningReadModelsCustomerDetail(Guid Id, string Name);
public class DesigningReadModelsCustomerDetailService(IEventStore eventStore)
{
public Task<DesigningReadModelsCustomerDetail> GetDetail(Guid customerId) =>
eventStore.ReadModels.GetInstanceById<DesigningReadModelsCustomerDetail>(customerId);
}

View C# snippet source on GitHub

The call site is the same; the model’s declaration changes where the answer comes from. A fresh read alone does not prevent another writer from changing state before your append. Use a constraint for uniqueness or a decision read to guard a supported state-based decision against concurrent changes. Deep dive: consistency explains the choices.

Choose retrieval by result size and query needs. The following snippet shows the .NET collection APIs:

using Cratis.Chronicle;
public record DesigningReadModelsCustomerListItem(Guid Id, string Name);
public class DesigningReadModelsCustomerListService(IEventStore eventStore)
{
public async Task<IEnumerable<DesigningReadModelsCustomerListItem>> GetEveryInstance()
{
// Every instance in one call — read from the materialized store
return await eventStore.ReadModels.GetInstances<DesigningReadModelsCustomerListItem>();
}
public async Task<IEnumerable<DesigningReadModelsCustomerListItem>> GetPage()
{
// One page of materialized instances, with paging done by the store
return await eventStore.ReadModels.Materialized.GetInstances<DesigningReadModelsCustomerListItem>(skip: 0, take: 20);
}
}

View C# snippet source on GitHub

  • GetInstances<T>() returns all instances from the materialized store, or computes them from events for a passive model. An event count (GetInstances<T>(eventCount)) requests a bounded replay and can produce incomplete state. Use it for reporting and small populations, not an unbounded list screen.
  • Materialized.GetInstances<T>(skip, take) pages the stored view. It does not wait for projection catch-up. See Materialized read models.
  • A sink’s native query tools, such as IMongoCollection<T> or a DbContext, provide filtering, sorting, and aggregation over the materialized data in that database.

The choice between all instances and a page is not a consistency setting. Decide freshness first, then choose an API that bounds the data and work your query needs.

Keep the read side ignorant of the write side

Section titled “Keep the read side ignorant of the write side”

A projection only knows about events. It must not trigger commands, call external systems, or produce side effects — that’s a reactor’s job. Keeping projections pure is what makes them safe to replay at any time.