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.
Read models are derived and disposable
Section titled “Read models are derived and disposable”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.
Shape it for the query, not the domain
Section titled “Shape it for the query, not the domain”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.
Specialize over reuse
Section titled “Specialize over reuse”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 eventsReach for the declarative path first
Section titled “Reach for the declarative path first”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.
The constructor may not run
Section titled “The constructor may not run”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 ?? [];}data class DesigningReadModelsLineItem(val productName: String, val quantity: Int, val price: Double)
// A non-nullable property with a default in the constructor - not a body that "fixes up" a// value after the fact, which a document deserializer may skip entirely.data class DesigningReadModelsOrderSummary( val id: String, val lines: List<DesigningReadModelsLineItem> = emptyList())import java.util.Collections;import java.util.List;
record DesigningReadModelsLineItem(String productName, int quantity, double price) {}
// A collection defaulted at the call site, not "fixed up" by logic in a constructor body -// a document deserializer may build the instance without ever running one.record DesigningReadModelsOrderSummary(String id, List<DesigningReadModelsLineItem> lines) { static DesigningReadModelsOrderSummary empty(String id) { return new DesigningReadModelsOrderSummary(id, Collections.emptyList()); }}Elixir does not support this workflow yet.TypeScript does not support this workflow yet.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. |
Design for eventual consistency
Section titled “Design for eventual consistency”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);}// Requires io.cratis:chronicle 6.5.0 or later.import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.readModels.Passiveimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class DesigningReadModelsCustomerNamed(val name: String)
// Nothing materializes this read model: every read computes it from the event log.@Passive@ReadModel@FromEvent(DesigningReadModelsCustomerNamed::class)data class DesigningReadModelsCustomerDetail(val name: String = "")
class DesigningReadModelsCustomerDetailService(private val eventStore: IEventStore) { suspend fun getDetail(customerId: String): DesigningReadModelsCustomerDetail? = eventStore.readModels.getInstanceByKey(DesigningReadModelsCustomerDetail::class, customerId)}// Requires io.cratis:chronicle 6.5.0 or later.import io.cratis.chronicle.EventStore;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.java.ReadModelsJavaBridge;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.readModels.Passive;import io.cratis.chronicle.readModels.ReadModel;
@EventTyperecord DesigningReadModelsCustomerNamed(String name) {}
// Nothing materializes this read model: every read computes it from the event log.@Passive@ReadModel@FromEvent(eventType = DesigningReadModelsCustomerNamed.class)class DesigningReadModelsCustomerDetail { public String name = "";}
class DesigningReadModelsCustomerDetailService { private final EventStore eventStore;
DesigningReadModelsCustomerDetailService(EventStore eventStore) { this.eventStore = eventStore; }
DesigningReadModelsCustomerDetail getDetail(String customerId) { return ReadModelsJavaBridge.getInstanceByKey( eventStore.getReadModels(), DesigningReadModelsCustomerDetail.class, customerId); }}defmodule MyApp.ReadModels.DesigningReadModelsCustomerDetail do use Cratis.Chronicle.ReadModels.ReadModel
defstruct id: "", name: ""end
defmodule MyApp.DesigningReadModelsCustomerDetailService do alias MyApp.ReadModels.DesigningReadModelsCustomerDetail
def get_detail(customer_id) do Cratis.Chronicle.read_model(DesigningReadModelsCustomerDetail, customer_id) endendimport { IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
class DesigningReadModelsCustomerDetail { @field(String) readonly id: string; @field(String) readonly name: string;
constructor(id: string, name: string) { this.id = id; this.name = name; }}
class DesigningReadModelsCustomerDetailService { constructor(private readonly store: IEventStore) {}
getDetail(customerId: string): Promise<DesigningReadModelsCustomerDetail | null> { return this.store.readModels.findInstanceById(DesigningReadModelsCustomerDetail, customerId); }}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.
Query it
Section titled “Query it”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); }}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.readModels.ReadModel
@ReadModeldata class DesigningReadModelsCustomerListItem(val id: String = "", val name: String = "")
// Every instance in one call — read from the materialized storesuspend fun getEveryInstance(store: IEventStore) = store.readModels.getInstances(DesigningReadModelsCustomerListItem::class)
// One page of materialized instances, with paging done by the storesuspend fun getPage(store: IEventStore) = store.readModels.materialized.getInstances(DesigningReadModelsCustomerListItem::class, skip = 0, take = 20)import io.cratis.chronicle.EventStore;import io.cratis.chronicle.readModels.ReadModel;import io.cratis.chronicle.java.ReadModelsJavaBridge;
import java.util.List;
@ReadModelclass DesigningReadModelsCustomerListItem { private String id = ""; private String name = "";
public DesigningReadModelsCustomerListItem() {}
public String getId() { return id; } public void setId(String id) { this.id = id; }
public String getName() { return name; } public void setName(String name) { this.name = name; }}
class DesigningReadModelsCustomerListService { // Every instance in one call — read from the materialized store List<DesigningReadModelsCustomerListItem> getEveryInstance(EventStore store) { return ReadModelsJavaBridge.getInstances(store.getReadModels(), DesigningReadModelsCustomerListItem.class); }
// One page of materialized instances, with paging done by the store List<DesigningReadModelsCustomerListItem> getPage(EventStore store) { return ReadModelsJavaBridge.getMaterializedInstances(store.getReadModels(), DesigningReadModelsCustomerListItem.class, 0, 20); }}defmodule MyApp.ReadModels.DesigningReadModelsCustomerListItem do use Cratis.Chronicle.ReadModels.ReadModel
defstruct id: "", name: ""end
defmodule MyApp.DesigningReadModelsCustomerListService do alias MyApp.ReadModels.DesigningReadModelsCustomerListItem
def get_all_strongly_consistent do # Strongly consistent — Chronicle replays the read model's events on demand Cratis.Chronicle.all(DesigningReadModelsCustomerListItem) end
def get_page_eventually_consistent do # Eventually consistent — a page of materialized instances straight from storage Cratis.Chronicle.ReadModels.query(DesigningReadModelsCustomerListItem, page: 0, page_size: 20) endendimport { IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
class DesigningReadModelsCustomerListItem { @field(String) readonly id: string; @field(String) readonly name: string;
constructor(id: string, name: string) { this.id = id; this.name = name; }}
class DesigningReadModelsCustomerListService { constructor(private readonly store: IEventStore) {}
// Strongly consistent — Chronicle replays the read model's events on demand getAllStronglyConsistent(): Promise<DesigningReadModelsCustomerListItem[]> { return this.store.readModels.getInstances(DesigningReadModelsCustomerListItem); }
// Eventually consistent — a page of materialized instances straight from storage getPageEventuallyConsistent(): Promise<DesigningReadModelsCustomerListItem[]> { return this.store.readModels.materialized.getInstances(DesigningReadModelsCustomerListItem, 0, 20); }}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 aDbContext, 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.
Where this leads
Section titled “Where this leads”- Read Models — retrieval, snapshots, and consistency in depth.
- Projections, reducers, and reactors — how the read side is built.
- Modeling events well — the source of truth your read models derive from.