A CQRS view is a query-oriented representation of data maintained separately from the transactional model. A dedicated view database is updated from events published by the services that own the data. Queries read the view rather than calling those providers at runtime. section 13.4
A view is useful when API composition cannot efficiently filter, sort, or paginate across services, or when a service’s own database cannot support its queries. It adds infrastructure and operational work, however. For small, infrequently queried datasets, a normalized relational schema with joins may be sufficient. section 13.4 section 13.3
Design the view around its queries and the events that update it:
- Choose whether to reuse an existing view or create one. Reuse saves infrastructure and operations, but unrelated queries can make a view less cohesive. section 13.3
- Select a database for the required query and update operations, data model, transactions, and operational characteristics. Query support is the primary consideration. section 13.4
- Decide how to group records, what to precompute, and which indexes to define. Store result fields as well as fields needed for filtering, sorting, and locating records to update. section 13.3.2
- Define repository operations and provider event contracts together. Events must carry each provider’s required data and the identifiers needed to create, find, or update records. section 13.3 section 13.3.4
Order history
An order history view can store order summaries together with status and timestamp fields used for filtering and sorting. An OrderCreated event carries the order ID and consumer ID, allowing the view to create the record and later find that consumer’s orders. Depending on query and update needs, orders can be grouped in a customer document or stored in separate order documents. section 13.3.4 section 13.3.2
Provider services must publish changes reliably, and view update logic must handle duplicate, out-of-order, and concurrent events. Event contracts also require coordination and careful evolution across teams. A view can live in an existing service or in a standalone service when independent scaling or ownership warrants it. section 13.2.3 section 13.4 section 13.3.5
Figure 13.4 Because it takes time for an event to flow from the provider service to the CQRS view, a client is not guaranteed to be able to read its own writes. A query might not return data that is up to date.
Event propagation takes time, so a query can return stale data and a client might not immediately read its own writes. section 13.2.3
Plan for initialization and rebuilding as well as routine updates. Replaying the entire event history can be impractical; provider snapshot events can help initialize a new view. section 13.3.5 section 13.4
