Skip to content

Read Models from Events: Projections Instead of Accidental Caches

A read model built from events is a deliberately maintained projection for concrete queries. Origin and rebuild set it apart from an accidentally grown cache, even if the technical view can look cache-like.

≈ 12 min readSoftwareArchitecture

Read Models from Events: Projections Instead of Accidental Caches

This post looks at the event sourcing case: behind the read view there is an event stream from which it can be derived again. That makes the read model the view intended for queries, not an accidental acceleration layer. Technically it may still look cache-like, for example as a denormalized table with fast replacement. What matters is origin and rebuild, not the storage product.

The comparison with a cache is still tempting: a denormalized, fast view that sits next to the actual database simply looks like one. It gets expensive the moment the first schema on the read side has to change. A read side that was built as a cache can then no longer be restored cleanly. One that was built as a projection has the rebuild in its design from the start – and this difference runs through operations, migration and troubleshooting.

Where the cache reflex comes from#

The reflex has a grain of truth. On the surface, a read model and a cache solve the same problem: queries should be fast without asking the expensive write model every time something is displayed. Both are denormalized, both sit closer to the user than the source of truth, both are potentially stale.

The break lies one level deeper, in the question: who is the source of truth, and how does the fast view emerge from it? A cache has an authoritative database behind it. If the cache entry drops out, you pull the record from that source again and store it again. Invalidation is a side effect of TTL or eviction, and a cold start is an operational detail. A read model, on the other hand, has no “actual” read database behind it from which you reload it when needed. It is the authoritative read view. What lies behind it is the event store or the write model – and the read model is not “reloaded” from it but computed.

That computation is the projection. And it is the reason I insist on the distinction.

What makes a projection#

Three terms come before the code. Martin Fowler describes CQRS as a deliberate separation: you use a different model to update information than the model you use to read information. The read model is not a view through the domain model, but a separate model that serves queries exclusively. Greg Young and Vaughn Vernon provide the link: the projection – the process that derives and updates the read model from the changes on the write side, specifically from the domain events.

The decisive property of the projection discussed here is its origin in an immutable event stream. If events, order, projection code and other inputs are fixed, replaying produces the same read model. The second property follows from that: you can throw the view away and recompute it entirely from the events. The rebuild is not an emergency plan but a regular tool.

This is exactly where the projection parts ways with the cache. You can refill a cache too, but that rebuild is a cold-start side effect whose result depends on the source at the current moment. Rebuilding a projection is deterministic and independent of time, because it rests on history, not on a momentary state.

A caveat belongs here: this free rebuild assumes that the events are available permanently and completely – that is, a write path with event sourcing in which the event store is the source of truth. CQRS and event sourcing are two separate decisions that are often made together but do not have to be; Fowler explicitly describes CQRS independently of the form of persistence. If you run CQRS without a persistent event history and only update the read side from transient notifications, you have a projection in operation, but not the deterministic rebuild from history. The examples here assume the event store – and with it the property that separates the read model from the cache.

The projection as a fold#

It becomes clearest in code. At its core, a projection is a fold – a reduce over the events that starts with an empty state and applies each event to the state so far. As an illustration, in TypeScript:

type OrderPlaced = { type: "OrderPlaced"; orderId: string; total: number }
type OrderShipped = { type: "OrderShipped"; orderId: string }
type OrderCancelled = { type: "OrderCancelled"; orderId: string }

type OrderEvent = OrderPlaced | OrderShipped | OrderCancelled

type OrderSummary = {
  orderId: string
  total: number
  status: "placed" | "shipped" | "cancelled"
}

// pure reducer: (state, event) => state
function apply(state: OrderSummary, event: OrderEvent): OrderSummary {
  switch (event.type) {
    case "OrderPlaced":
      return { orderId: event.orderId, total: event.total, status: "placed" }
    case "OrderShipped":
      return { ...state, status: "shipped" }
    case "OrderCancelled":
      return { ...state, status: "cancelled" }
  }
}

// the projection is a fold over the event stream
function project(events: OrderEvent[]): OrderSummary {
  return events.reduce(apply, {} as OrderSummary)
}

apply is a pure function (state, event) => state. No access to the clock, no network, no randomness. That is not a stylistic preference. Without this purity, the rebuild does not stay deterministic. As soon as a Date.now() or an external lookup sneaks into apply, the nice property “same events, same read model” is lost – and you have unknowingly built yourself a cache whose rebuild depends on the point in time.

One read model per view#

The second key point: there is no single read model. There is one per query, each denormalized and tailored exactly to the view it serves. Vernon points out that read models are especially useful where the displayed data cuts across several aggregates. The read model pulls this data together in advance, so the query stays flat and cheap.

A view for an order list pulls different fields than a detail view. Instead of joining and computing at runtime, the projection stores the finished values:

type CustomerOrderListItem = {
  orderId: string
  customerName: string   // denormalized from the customer aggregate
  itemCount: number      // precomputed, no join at read time
  totalAmount: number
  statusLabel: string    // display-ready, e.g. "Versandt"
}

// this projection cuts across order and customer to build one flat view
function toListItem(
  order: OrderSummary,
  customerName: string,
  itemCount: number,
): CustomerOrderListItem {
  return {
    orderId: order.orderId,
    customerName,
    itemCount,
    totalAmount: order.total,
    statusLabel: order.status === "shipped" ? "Versandt" : "Offen",
  }
}

The direction of thinking is what matters: the read model is built for the query, not the query for the read model. That is exactly what I mean in CQRS is a domain boundary when I say that separating reads and writes is a statement about responsibility, not about two databases. The read side may have its own shape because it has its own job.

The rebuild is part of the design#

Because the projection emerges deterministically from the events, the rebuild is trivial to express – you clear the read side and replay the events:

interface ReadStore {
  clear(): void
  save(view: OrderSummary): void
}

interface EventStore {
  allEvents(): Iterable<OrderEvent>
}

function rebuild(events: EventStore, read: ReadStore): void {
  read.clear()
  const views = new Map<string, OrderSummary>()
  for (const event of events.allEvents()) {
    const current = views.get(event.orderId) ?? ({} as OrderSummary)
    views.set(event.orderId, apply(current, event))
  }
  for (const view of views.values()) read.save(view)
}

This rebuild is the practical litmus test. If you can write it cleanly, you have a projection. If you cannot write it cleanly – because state flows in from outside, because events were discarded, because apply is not pure – then you have a cache and should stop calling it a read model.

The rebuild is also the answer to a question that comes up in projects sooner or later: what happens with a schema change on the read side? With a cache, that is a migration problem with data transfer. With a projection, it is a new projector that you run over the existing events. The new view emerges from the same source as the old one. This is the moment when the initial discipline pays off.

The data flow in a picture#

One source, several view-specific projections – this is what the flow looks like:

flowchart LR
  C[Command] --> W[Write Model /<br/>Event Store]
  W -->|Events| P[Projector]
  P -->|async · eventual| A[Read Model A<br/>List]
  P -->|async · eventual| B[Read Model B<br/>Detail]
  P -->|async · eventual| R[Read Model C<br/>Report]

The command runs against the write model and produces events. The projector subscribes to these events and uses them to update as many read models as there are views. The edges to the read models are deliberately labeled “async · eventual,” because this is where the third key point lies: consistency.

Eventual consistency is a deliberate trade#

The projection runs asynchronously after the write has succeeded. Fowler states the consequence soberly: you cannot guarantee exactly when the read model is consistent. Shortly after the write, it is potentially stale. That is not a bug, not data loss and not corruption – it is a bounded, known delay that you accept in order to decouple the read side from the write side.

The delay itself rarely causes trouble. How you deal with it does. If you expect synchronous read-after-write consistency, you build the UI so that it reads from the read model immediately after the command and are surprised that the new record is “missing.” It is not gone; the projection just has not caught up yet. That belongs in the design of the UI, not in a bug report.

The second variant is more dangerous: checking command-side invariants from the read model. Greg Young is clear here – the read model must not carry a business decision that has to rely on current, consistent state. Because it can be stale, you would be deciding on stale data. Checking whether an account has sufficient funds or whether an order may still be canceled belongs on the write side, against the aggregate, not against the read view. I wrote up this division of labor in more detail in Cleanly Separating Commands, Events and Queries: a query asks a question and changes nothing; that is why it must not force a decision either.

Projection or cache – the distinction in five points#

Whether a concrete read side is a projection or a cache becomes clear from five questions:

  • Who is the source of truth? With a projection, the event store is the source, and the read model is the authoritative read view. With a cache, the authoritative source is the database behind it.
  • How is it invalidated? The projection is updated event-driven, the cache through TTL or eviction.
  • How does the rebuild work? The projection can, by design, be recomputed deterministically from history; the cache rebuild is a cold-start side effect that depends on the current state of the source.
  • What shape does the view have? The projection is denormalized per view and pulled together across aggregates, the cache is usually a copy of the source record.
  • What about consistency? The projection is deliberately eventually consistent with a bounded delay, the cache best effort.

You can argue about one or two of these points. But if the answers mostly land in the cache column, you should call the thing what it is and not hang the expectations of a read model on it.

The three pitfalls, concretely#

Finally, the patterns that cause the trouble, each named in one sentence along with the countermeasure.

The first is cache thinking itself: treating the read model as an optional accelerator that you pull again from the “actual” database on a miss. That actual database does not exist. Updates are event-driven, and the rebuild comes from the events. If you take this seriously, you stop looking for the source behind the read model.

The second is the read model as the source of truth: deciding on command invariants from a potentially stale read view. The consequence is decisions based on old state. The countermeasure is discipline across the boundary between the sides – decisions go on the write side, against the aggregate.

The third is the forgotten rebuild: building a projection that cannot be replayed because apply is not pure or events were discarded. Then the first schema migration becomes a dead end. The countermeasure is in the code above – keep the projector a pure fold over the events, and write the rebuild early, not only when things are on fire.

Conclusion#

A read model deserves a better name than “cache,” because the name sets the expectations. If you call it a cache, you build an optional accelerator with a supposed source behind it, TTL invalidation and a rebuild that remains a side effect. If you call it a projection, you build a pure fold over an immutable event stream, tailored per view, updated event-driven and deterministically recomputable at any time. The three properties I use to pin this down are always the same: deterministically derived, rebuildable at any time, deliberately eventually consistent. If you build these three into the design, you have a read side that you can operate and migrate without breaking a sweat at every change.

Further reading#

  • Slide deck on this topic: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.en.html
  • Martin Fowler, CQRS – the conceptual model split and the warning to use it only locally within a context.
  • Martin Fowler, Reporting Database – the related but narrower idea of a separate read database.
  • Martin Fowler, Event Sourcing – the form of persistence that makes projections so natural.
  • Greg Young, CQRS Documents (2010, PDF) – the foundations of read models, eventual consistency and rebuild.
  • Vaughn Vernon, Implementing Domain-Driven Design (2013), chapters on architecture and CQRS; sample code in the IDDD Samples.
  • My own talk material “CQRS + Event Sourcing” on SlideShare – the slides from which I derive the core in trainings: reading and writing are different responsibilities.

Revised and translated from German with the help of AI.