Projections and read models explained
A read model is data shaped to answer a query, such as the books currently on loan. A projection defines how events build that view. Keeping the result in storage lets a screen read the answer without replaying the full history on every request.
For a balance, the projection applies deposits and withdrawals to a running total. Several projections can use the same events to answer different questions: the balance, a transaction list or a monthly summary. This is the read side of an event-sourced CQRS design. Start with what is event sourcing? if you need the storage model first.
How projections and read models work
Section titled “How projections and read models work”A projection selects the event types it needs and maps their facts into a read model. An event’s key identifies which instance to update; for a book-status view, that can be the book id. A materialized projection stores the result for queries to read.
Treat the view as derived data. Business writes go to events, not directly to the projected fields: a direct edit can be overwritten by the next event or replay. If the mapping is wrong, correct it and rebuild the view from the retained facts.
A new view can use old events only if those events contain what it needs. Replay cannot recover a fact that was never recorded. Stored views also update after the append, so they can lag behind it; a failed observer may leave them stale until processing recovers.
Chronicle projections join events, not other read models. Keeping the inputs in the event history avoids making a rebuild depend on another view’s current state.
Projections, reducers and read models
Section titled “Projections, reducers and read models”The terms overlap, so here is how Chronicle uses them.
| Term | What it is |
|---|---|
| Read model | The shaped, queryable result |
| Projection | A declarative rule that maps events onto a read model |
| Reducer | Code that folds each event into the current state, one event at a time |
The examples below use three authoring styles in C#, Kotlin, and Java. The choice is about where the transformation lives, not which application language you use. Other clients expose different APIs; First projection shows a book view in TypeScript, Elixir, and C#.
| Style | What it looks like | Use it when |
|---|---|---|
| Model-bound projection | Attributes on the read model type | Direct field mappings describe the view |
| Declarative projection | A separate fluent mapping definition | The mapping needs more explicit structure |
| Reducer | Code that folds the previous state and an event | State transitions are easier to write as code |
Chronicle’s choose a read-model style page compares these forms with other supported choices, including self-reducing models in .NET.
A concrete example: a library book
Section titled “A concrete example: a library book”A library tracks whether each book is on the shelf or on loan. Three events carry the story:
using Cratis.Chronicle.Events;
[EventType]public record BookRegistered(string Title, string Isbn);
[EventType]public record BookBorrowed(string MemberName);
[EventType]public record BookReturned;import io.cratis.chronicle.events.EventType
@EventTypedata class BookRegistered(val title: String, val isbn: String)
@EventTypedata class BookBorrowed(val memberName: String)
@EventTypeclass BookReturnedimport io.cratis.chronicle.events.EventType;
@EventTypepublic record BookRegistered(String title, String isbn) {}
@EventTypepublic record BookBorrowed(String memberName) {}
@EventTypepublic record BookReturned() {}The screen needs a small read model: the title, whether the book is on loan and who has it. In a model-bound projection, the read model describes how events fill it:
using Cratis.Chronicle.Keys;using Cratis.Chronicle.Projections.ModelBound;
public record BookStatus( [Key] string Id,
[SetFrom<BookRegistered>] string Title, [SetFrom<BookRegistered>] string Isbn,
[SetValue<BookBorrowed>(true)] [SetValue<BookReturned>(false)] bool IsBorrowed,
[SetFrom<BookBorrowed>(nameof(BookBorrowed.MemberName))] [ClearWith<BookReturned>] string? BorrowedBy);import io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.projections.SetValueimport io.cratis.chronicle.readModels.ReadModel
@ReadModel@FromEvent(BookRegistered::class)@FromEvent(BookBorrowed::class)@FromEvent(BookReturned::class)data class BookStatus( val id: String = "",
@SetFrom(eventType = BookRegistered::class) val title: String = "", @SetFrom(eventType = BookRegistered::class) val isbn: String = "",
@SetValue(BookBorrowed::class, value = "true") @SetValue(BookReturned::class, value = "false") val isBorrowed: Boolean = false,
@SetFrom("memberName", BookBorrowed::class) @SetValue(BookReturned::class, clear = true) val borrowedBy: String? = null)import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.projections.SetValue;import io.cratis.chronicle.readModels.ReadModel;
@ReadModel@FromEvent(eventType = BookRegistered.class)@FromEvent(eventType = BookBorrowed.class)@FromEvent(eventType = BookReturned.class)public class BookStatus { public String id = "";
@SetFrom(eventType = BookRegistered.class) public String title = ""; @SetFrom(eventType = BookRegistered.class) public String isbn = "";
@SetValue(eventType = BookBorrowed.class, value = "true") @SetValue(eventType = BookReturned.class, value = "false") public boolean isBorrowed = false;
@SetFrom(propertyPath = "memberName", eventType = BookBorrowed.class) @SetValue(eventType = BookReturned.class, clear = true) public String borrowedBy;}The registered Chronicle client discovers the model-bound definition, so this form needs no separate projection class. The registration event fills the title and ISBN. Borrowing sets the borrowed flag and member name; returning clears both. In C#, [ClearWith<BookReturned>] expresses clearing the member name; the JVM examples use their mapping annotations.
A separate projection class can express the same mapping. AutoMap fills matching title and ISBN properties, while the fluent definition explicitly maps the borrowed flag and member name:
using Cratis.Chronicle.Projections;
public class BookStatusProjection : IProjectionFor<BookStatus>{ public void Define(IProjectionBuilderFor<BookStatus> builder) => builder .From<BookRegistered>(_ => _ .Set(m => m.Id).ToEventSourceId() .Set(m => m.IsBorrowed).ToValue(false) .Clear(m => m.BorrowedBy)) .From<BookBorrowed>(_ => _ .Set(m => m.IsBorrowed).ToValue(true) .Set(m => m.BorrowedBy).To(e => e.MemberName)) .From<BookReturned>(_ => _ .Set(m => m.IsBorrowed).ToValue(false) .Clear(m => m.BorrowedBy));}import io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionFor
class BookStatusProjection : IProjectionFor<BookStatus> { override fun define(builder: IProjectionBuilderFor<BookStatus>) { builder .from(BookRegistered::class) { it.set(BookStatus::id).toEventSourceId() it.set(BookStatus::isBorrowed).toValue(false) it.set(BookStatus::borrowedBy).toValue(null) } .from(BookBorrowed::class) { it.set(BookStatus::isBorrowed).toValue(true) it.set(BookStatus::borrowedBy).toProperty("memberName") } .from(BookReturned::class) { it.set(BookStatus::isBorrowed).toValue(false) it.set(BookStatus::borrowedBy).toValue(null) } }}import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
public class BookStatusProjection implements IProjectionFor<BookStatus> { @Override public void define(IProjectionBuilderFor<BookStatus> builder) { builder .from(BookRegistered.class, fb -> { fb.<String>set("id").toEventSourceId(); fb.<Boolean>set("isBorrowed").toValue(false); fb.<String>set("borrowedBy").toValue(null); }) .from(BookBorrowed.class, fb -> { fb.<Boolean>set("isBorrowed").toValue(true); fb.<String>set("borrowedBy").toProperty("memberName"); }) .from(BookReturned.class, fb -> { fb.<Boolean>set("isBorrowed").toValue(false); fb.<String>set("borrowedBy").toValue(null); }); }}Use one style per read model, not both definitions together. These excerpts assume a registered Chronicle client; Get started with Chronicle covers the host setup.
When you want to fold state with ordinary code, a reducer receives the event, the current state and the event context, and returns the new state. A running balance is a good fit:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Reducers;
[EventType]public record DepositMade(decimal Amount);
[EventType]public record WithdrawalMade(decimal Amount);
public record AccountBalance(decimal Balance, DateTimeOffset LastUpdated);
public class AccountBalanceReducer : IReducerFor<AccountBalance>{ public AccountBalance Deposited(DepositMade @event, AccountBalance? current, EventContext context) => new((current?.Balance ?? 0m) + @event.Amount, context.Occurred);
public AccountBalance WithdrawalMade(WithdrawalMade @event, AccountBalance? current, EventContext context) => new((current?.Balance ?? 0m) - @event.Amount, context.Occurred);}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.observation.Reducerimport io.cratis.chronicle.readModels.ReadModelimport java.math.BigDecimalimport java.time.Instant
@EventTypedata class DepositMade(val amount: BigDecimal)
@EventTypedata class WithdrawalMade(val amount: BigDecimal)
@ReadModeldata class AccountBalance(val balance: BigDecimal = BigDecimal.ZERO, val lastUpdated: Instant = Instant.EPOCH)
@Reducerclass AccountBalanceReducer { fun deposited(event: DepositMade, current: AccountBalance?, context: EventContext) = AccountBalance((current?.balance ?: BigDecimal.ZERO) + event.amount, context.occurred)
fun withdrawalMade(event: WithdrawalMade, current: AccountBalance?, context: EventContext) = AccountBalance((current?.balance ?: BigDecimal.ZERO) - event.amount, context.occurred)}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.observation.Reducer;import io.cratis.chronicle.readModels.ReadModel;
import java.math.BigDecimal;import java.time.Instant;
@EventTypepublic record DepositMade(BigDecimal amount) {}
@EventTypepublic record WithdrawalMade(BigDecimal amount) {}
@ReadModelpublic record AccountBalance(BigDecimal balance, Instant lastUpdated) { public AccountBalance() { this(BigDecimal.ZERO, Instant.EPOCH); }}
@Reducerpublic class AccountBalanceReducer { public AccountBalance deposited(DepositMade event, AccountBalance current, EventContext context) { BigDecimal balance = current == null ? BigDecimal.ZERO : current.balance(); return new AccountBalance(balance.add(event.amount()), context.getOccurred()); }
public AccountBalance withdrawalMade(WithdrawalMade event, AccountBalance current, EventContext context) { BigDecimal balance = current == null ? BigDecimal.ZERO : current.balance(); return new AccountBalance(balance.subtract(event.amount()), context.getOccurred()); }}To read the book-status result, ask for its instance by key. With materialization enabled, this retrieves the stored view, which may not yet include the latest append:
BookStatus? status = await eventStore.ReadModels.GetInstanceById<BookStatus>(bookId);
if (status is not null){ Console.WriteLine($"{status.Title}: {(status.IsBorrowed ? status.BorrowedBy : "on the shelf")}");}val status = eventStore.readModels.getInstanceByKey(BookStatus::class, bookId)
if (status != null) { println("${status.title}: ${if (status.isBorrowed) status.borrowedBy else "on the shelf"}")}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.java.BlockingEventStore;
public class BookStatusLookup { public void printStatus(IEventStore eventStore, String bookId) { var status = new BlockingEventStore(eventStore) .getReadModels() .getInstanceByKey(BookStatus.class, bookId);
if (status != null) { System.out.println(status.title + ": " + (status.isBorrowed ? status.borrowedBy : "on the shelf")); } }}In an Arc .NET application, the same read model carries a [ReadModel] attribute and a static query method, and the frontend gets a typed proxy. See read models in Arc with Chronicle.
Consistency: materialized or on demand
Section titled “Consistency: materialized or on demand”A materialized read model is stored and updated after the append. This is the default: repeated queries read the saved result rather than calculating it again. When one caller needs its own write back, it can wait for the append’s observers to finish before querying, and must handle failures or timeouts from that wait.
A passive read model is computed on demand from events instead of stored in a sink. Its cost grows with the history it replays. Ordinary passive by-id reads select one event source: they do not generally reconstruct a view that joins sources or uses a custom aggregation key. Keep those views materialized.
Choose freshness separately from write correctness. Even a fresh on-demand result does not protect a later append from another writer. Use an append-time constraint or a protected decision read for rules that must hold under concurrency. Read model consistency explains the read options and their limits.
Benefits
Section titled “Benefits”A materialized view moves calculation out of the query path. The loan screen can read the title, borrower and status together without folding every loan event. A report can use a different shape over the same history.
That separation lets you evolve a view without rewriting business facts. Rebuilds still cost time and need a rollout plan, but the events remain the input.
Trade-offs and when not to use them
Section titled “Trade-offs and when not to use them”Every view adds a definition to maintain and data to rebuild. Large histories make replay an operational task, and an asynchronously updated screen needs a way to represent pending or stale data.
Do not use an unprotected read-then-append check to enforce a business rule. Two commands can both pass the check, even with on-demand reads. Protect the decision on the write side. For a simple application that only needs current-state records, ordinary database queries may be enough without event projections.
Common pitfalls
Section titled “Common pitfalls”- One giant read model for every screen. It brings back the coupling you set out to avoid. Build specialised models.
- Treating a read model as the source of truth. It can be dropped and rebuilt. The events are the record.
- Putting business rules in a projection. A projection mirrors facts. Decisions belong where commands are handled.
- Mixing view rebuilds with external actions. Keep projection logic focused on derived state so a rebuild does not send email. Reactors need a separate replay policy; see event-driven architecture vs. event sourcing.
- Unbounded child collections. A read model that collects every event of a busy entity grows without limit. Keep child lists bounded or split the view.
- Querying the event log directly for screens. Use a read model.
Frequently asked questions
Section titled “Frequently asked questions”What is the difference between a projection and a read model?
Section titled “What is the difference between a projection and a read model?”The read model is the result, and the projection is the rule that produces it. People often say “projection” for both.
Is a read model the same as a materialized view?
Section titled “Is a read model the same as a materialized view?”A materialized event-sourced read model is similar: it stores a precomputed result, built from events rather than a SQL view definition. The broader term read model describes the data’s purpose, and can also include on-demand results or views over current-state tables.
How do I rebuild a read model?
Section titled “How do I rebuild a read model?”Replay the retained events through the projection. Chronicle can rebuild a projection from the start of its history. Keep external actions out of projection logic so rebuilding a view does not send emails or charge payments.
Can a projection use data from another read model?
Section titled “Can a projection use data from another read model?”Not in a Chronicle projection. Join the relevant events instead, so rebuilding the view does not depend on another read model’s freshness or replay order.
Where is a read model stored?
Section titled “Where is a read model stored?”A materialized read model is written to a storage destination called a sink. MongoDB is the default; a passive read model has no stored instance. See Chronicle’s projections documentation for configuration.
Next steps
Section titled “Next steps”For your first view, choose a read-model style and use Chronicle projections to define the mapping. Chronicle read models covers retrieval; an Arc query can expose the result to React.
If you have not yet chosen the view’s fields, use event modeling to work backwards from the screen to the facts it needs. CQRS explained places that read model alongside the commands that record those facts.