Add Read Model
ASecurityBuild a complete read model in Protean, a projection populated by a projector that reacts to domain events. Covers single-aggregate projections (flattened view of one aggregate), cross-aggregate projections (combining data from multiple aggregates), and choosing between database-backed and cache-backed storage. Use when the user asks to "add a read model", "create a projection with projector", "build a query view", "add a CQRS read side", "create a denormalized view", "build a reporting view"...
- 46 stars
- 0 votes
- 0 copies
- 2 views
- Added September 20, 2026
Works with
Security analysis
100/100Pro scans all 7 files and shows the line behind each finding
npx -y skills add proteanhq/protean --skill add-read-model --agent claude-codeAre you the author of Add Read Model?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/proteanhq-add-read-model)---
name: add-read-model
description: Build a complete read model in Protean, a projection populated by a projector that reacts to domain events. Covers single-aggregate projections (flattened view of one aggregate), cross-aggregate projections (combining data from multiple aggregates), and choosing between database-backed and cache-backed storage. Use when the user asks to "add a read model", "create a projection with projector", "build a query view", "add a CQRS read side", "create a denormalized view", "build a reporting view", "add a dashboard query model", or when they need to combine data from multiple aggregates into one queryable structure.
license: Apache-2.0
compatibility: Requires Python 3.11+, protean framework
metadata:
author: proteanhq
version: "0.1"
category: workflow
composes: [projection, projector, event, aggregate]
diagnostic_codes: [PROJECTION_WITHOUT_PROJECTOR, UNSOURCED_PROJECTION_FIELD]
---
# Add Read Model
A read model is the query side of CQRS. It consists of three parts working together:
1. **Projection**: A denormalized, query-optimized data structure built from basic fields and value objects
2. **Projector**: An event listener that populates and updates the projection
3. **Domain events**: The bridge between write-side aggregates and read-side projections
## What this creates
| Component | Purpose | Decorator |
|-----------|---------|-----------|
| Projection | Flat, queryable data structure | `@domain.projection` |
| Projector | Event-to-projection mapper | `@domain.projector(projector_for=..., aggregates=[...])` |
| Events | Carry state changes from aggregates | `@domain.event(part_of=...)` |
| Aggregate factory methods | Raise events on state changes | `raise_()` in aggregate methods |
## Information to gather
Before building a read model, understand:
- [ ] **What query does this serve?** What data does the UI/API need? (e.g., "product listing with stock levels")
- [ ] **Which aggregates contribute data?** Single aggregate or multiple? (determines projector configuration)
- [ ] **What events trigger updates?** Which state changes should update the read model?
- [ ] **What fields are needed?** Basic types (String, Integer, Float, Identifier, DateTime, Boolean, Text, Date) and `ValueObject`. No `Reference`, `HasOne` or `HasMany`
- [ ] **What storage is appropriate?** Database (durable, queryable) or cache (fast, ephemeral)?
## Process
### Step 1: Define the projection
Create a flat data structure that holds what the query returns.
```python
from protean.fields import Decimal, Identifier, Integer, String
@domain.projection
class ProductListing:
product_id: Identifier(identifier=True, required=True)
name: String(max_length=200, required=True)
price: Decimal(precision=19, scale=4)
stock_quantity: Integer(default=0)
```
Every field here is written by the Step 4 projector. Declare a field only once a projector handler fills it; a field no handler writes renders as a dead column, which `check` reports as `UNSOURCED_PROJECTION_FIELD`. To flatten a field from another aggregate (say a category name), source it from that aggregate's event in the projector, as the cross-aggregate example below shows.
**Key rules for projections** (see [projection](../projection/SKILL.md)):
- Basic field types and `ValueObject` only. No `Reference`, `HasOne` or `HasMany`
- A `ValueObject` field is stored as flattened columns (`address_city`, ...)
- At least one field with `identifier=True`
- Flatten nested data into basic fields
- Use `@domain.projection` decorator
### Step 2: Define the events
Events carry the data needed to populate the projection. Define them with `part_of` pointing to their source aggregate.
```python
@domain.event(part_of="Product")
class ProductAdded:
product_id: Identifier(required=True)
name: String(required=True)
price: Decimal(precision=19, scale=4, required=True)
stock_quantity: Integer(required=True)
@domain.event(part_of="Product")
class ProductPriceChanged:
product_id: Identifier(required=True)
new_price: Decimal(precision=19, scale=4, required=True)
```
### Step 3: Raise events from aggregates
Use factory methods or domain methods to raise events when state changes.
```python
@domain.aggregate
class Product:
name: String(required=True)
price: Decimal(precision=19, scale=4, required=True)
stock_quantity: Integer(default=0)
@classmethod
def create(cls, name, price, stock_quantity=0):
product = cls(name=name, price=price, stock_quantity=stock_quantity)
product.raise_(ProductAdded(
product_id=product.id,
name=name,
price=price,
stock_quantity=stock_quantity,
))
return product
def update_price(self, new_price):
self.price = new_price
self.raise_(ProductPriceChanged(
product_id=self.id,
new_price=new_price,
))
```
### Step 4: Build the projector
The projector listens to events and updates the projection. Use `@on` decorator from `protean.core.projector`.
```python
from protean.core.projector import on
@domain.projector(projector_for=ProductListing, aggregates=[Product])
class ProductListingProjector:
@on(ProductAdded)
def on_product_added(self, event: ProductAdded):
repo = domain.repository_for(ProductListing)
listing = ProductListing(
product_id=event.product_id,
name=event.name,
price=event.price,
stock_quantity=event.stock_quantity,
)
repo.add(listing)
@on(ProductPriceChanged)
def on_price_changed(self, event: ProductPriceChanged):
repo = domain.repository_for(ProductListing)
listing = repo.get(event.product_id)
listing.price = event.new_price
repo.add(listing)
```
### Step 5: Enable synchronous processing (for testing)
```python
domain.config["event_processing"] = "sync"
```
In production, events are processed asynchronously. For testing and development, set `event_processing` to `"sync"` so projectors run immediately when events are raised.
### Step 6: Read the model back
Answer reads with a query and a query handler (see [query](../query/SKILL.md) and [query-handler](../query-handler/SKILL.md)). The handler reads through `view_for`, which is read-only.
```python
from protean import current_domain, read
@domain.query(part_of=ProductListing)
class GetProductListing:
product_id: Identifier(required=True)
@domain.query_handler(part_of=ProductListing)
class ProductListingQueryHandler:
@read(GetProductListing)
def get_listing(self, query: GetProductListing):
return current_domain.view_for(ProductListing).get(query.product_id)
domain.init(traverse=False)
with domain.domain_context():
product = Product.create(name="Desk Lamp", price=39.0, stock_quantity=5)
domain.repository_for(Product).add(product) # the projector runs here
listing = domain.dispatch(GetProductListing(product_id=product.id))
assert (listing.name, listing.price) == ("Desk Lamp", 39.0)
```
`view_for(...).get()` raises `ObjectNotFoundError` when no record has that id. With asynchronous event processing, that includes a read made right after the write, before the projector has run.
Calling `domain.view_for(ProductListing)` directly works too, for example in a test.
## Single-aggregate vs cross-aggregate
| Aspect | Single-aggregate | Cross-aggregate |
|--------|-----------------|-----------------|
| **Projector config** | `aggregates=[Product]` | `aggregates=[User, Transaction]` |
| **Data source** | One aggregate's events | Multiple aggregates' events |
| **Complexity** | Straightforward mapping | Must handle ordering, missing records |
| **Example** | Product → ProductListing | User + Transaction → UserBalance |
### Cross-aggregate projector
When combining data from multiple aggregates, the projector listens to events from all contributing aggregates:
```python
@domain.aggregate
class User:
name: String(required=True)
@domain.aggregate
class Transaction:
user_id: Identifier(required=True)
amount: Decimal(precision=19, scale=4, required=True)
@domain.event(part_of=User)
class UserRegistered:
user_id: Identifier(required=True)
name: String(required=True)
@domain.event(part_of=Transaction)
class TransactionCompleted:
user_id: Identifier(required=True)
amount: Decimal(precision=19, scale=4, required=True)
@domain.projection
class UserBalance:
user_id: Identifier(identifier=True)
name: String()
balance: Decimal(precision=19, scale=4, default=0)
@domain.projector(
projector_for=UserBalance,
aggregates=[User, Transaction],
)
class UserBalanceProjector:
@on(UserRegistered)
def on_user_registered(self, event):
balance = UserBalance(user_id=event.user_id, name=event.name, balance=0.0)
domain.repository_for(UserBalance).add(balance)
@on(TransactionCompleted)
def on_transaction_completed(self, event):
balance = domain.repository_for(UserBalance).get(event.user_id)
balance.balance += event.amount
domain.repository_for(UserBalance).add(balance)
```
### Redelivered events
An event can be delivered more than once. As written, this projector adds the amount again when `TransactionCompleted` is redelivered, and a redelivered `UserRegistered` fails because the record already exists. Writing `on_user_registered` as an upsert (get the record, create it only if missing) fixes the second case. An upsert does not fix the first: adding to a running total is not safe to repeat, so set `idempotent=True` on the projector to have the framework skip an event it has already handled. That option is exactly-once only on a transactional database provider and does nothing for a cache-backed projection (see the `idempotent` option in [projector](../projector/SKILL.md)).
## Choosing storage
| Storage | Option | Best for |
|---------|--------|----------|
| **Database** | `@domain.projection` (default) | Durable data, complex queries, reporting |
| **Database (specific)** | `@domain.projection(database="postgres")` | Explicit provider selection |
| **Cache** | `@domain.projection(cache="redis")` | Fast reads, session data, ephemeral views |
## Common mistakes
### Complex field types in a projection
```python
# fragment
# Wrong! Projections are flat: no references or associations
@domain.projection
class ProductListing:
product_id: Identifier(identifier=True)
category = Reference(Category) # No
reviews = HasMany("Review") # No
```
Instead: flatten into basic fields (`category_name: String()`, `review_count: Integer()`).
### Business logic in the projector
```python
# fragment
# Wrong! Projector decides business rules
@on(OrderPlaced)
def on_order_placed(self, event):
if event.total > 1000: # rule leaks into the read side
apply_vip_discount(event)
```
Instead: projectors only map event data into projection rows; keep rules on the write side.
### Handling create but not update
```python
# fragment
# Wrong! Only the create event is handled: the projection goes stale
@on(ProductAdded)
def on_added(self, event): ...
# (no handler for ProductPriceChanged)
```
Instead: handle every event that changes the projected data, including updates (and deletes).
### Reading the aggregate instead of the projection
```python
# fragment
# Wrong! The read path queries the write model
orders = domain.repository_for(Order).query.filter(status="placed")
```
Instead: query the projection (`domain.repository_for(ProductListing)` or `view_for`), which is shaped for the query.
### A projection field no projector writes
```python
@domain.projection
class ProductListing:
product_id: Identifier(identifier=True)
name: String()
last_updated: DateTime()
# Wrong! The projector writes product_id and name but never last_updated
@domain.projector(projector_for=ProductListing, aggregates=[Product])
class ProductListingProjector:
@on(ProductAdded)
def on_added(self, event):
repo = domain.repository_for(ProductListing)
repo.add(ProductListing(product_id=event.product_id, name=event.name))
# last_updated stays empty, so it renders as a dead column
```
Instead: write every projection field from the projector handler for the event that carries
it, or drop the field. `check` reports a field the projector leaves unwritten as
`UNSOURCED_PROJECTION_FIELD`. A projection with no projector at all is a different report,
`PROJECTION_WITHOUT_PROJECTOR`; add a projector, or set `externally_populated=True` when a
subscriber fills it.
### Forgetting sync processing in tests
```python
# fragment
# Wrong! The projector never runs, so the projection stays empty
domain.process(command) # async by default
assert domain.repository_for(ProductListing).get("P-1") # fails
```
Instead: set `domain.config["event_processing"] = "sync"` in tests so projectors run immediately.
## Complete examples
- [Single-aggregate read model](assets/read_model_single_aggregate.py): Product → ProductListing with create and update events
- [Cross-aggregate read model](assets/read_model_cross_aggregate.py): User + Order → CustomerOrderSummary combining data from two aggregates
- [Read model with multiple events](assets/read_model_multiple_events.py): Inventory tracking with stock adjustments, reservations, and releases
## Detailed references
- [Single-Aggregate Read Model](references/single-aggregate-read-model.md): Step-by-step walkthrough
- [Cross-Aggregate Read Model](references/cross-aggregate-read-model.md): Combining data from multiple aggregates
- [Choosing Storage](references/choosing-storage.md): Database vs cache trade-offs
## Related skills
- [projection](../projection/SKILL.md): Projection definition and field types
- [projector](../projector/SKILL.md): Projector patterns and configuration
- [event](../event/SKILL.md): Defining domain events
- [aggregate](../aggregate/SKILL.md): Aggregates that raise events
## Verify your work
- [Verify with check](../../references/verify-with-check.md): run `check` and resolve what it reports
Files in this skill
- SKILL.md
- assets/read_model_cross_aggregate.py
- assets/read_model_multiple_events.py
- assets/read_model_single_aggregate.py
- references/choosing-storage.md
- references/cross-aggregate-read-model.md
- references/single-aggregate-read-model.md
Attribution
Related skills
View all in development →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.