/protean:add-read-modelfrom protean
Builds a complete CQRS read model in Protean: defines a projection (denormalized query view), a projector that listens to domain events, and the events themselves. Covers single-aggregate and cross-aggregate projections with database or cache storage.
Ships in protean. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
A read model is the query side of CQRS. It consists of three parts working together:
| 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 |
Before building a read model, understand:
ValueObject. No Reference, HasOne or HasManyCreate a flat data structure that holds what the query returns.
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):
ValueObject only. No Reference, HasOne or HasManyValueObject field is stored as flattened columns (address_city, ...)identifier=True@domain.projection decoratorEvents carry the data needed to populate the projection. Define them with part_of pointing to their source aggregate.
@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)
Use factory methods or domain methods to raise events when state changes.
@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,
))
The projector listens to events and updates the projection. Use @on decorator from protean.core.projector.
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)
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.
Answer reads with a query and a query handler (see query and query-handler). The handler reads through view_for, which is read-only.
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.
| 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 |
When combining data from multiple aggregates, the projector listens to events from all contributing aggregates:
@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)
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).
| Storage | Option | Best for |
|---|---|---|
| Database | @domain.projection (default) | Durable data, complex queries, reporting |
| Database (specific) | @domain.projection(provider="postgres") | Explicit provider selection |
| Cache | @domain.projection(cache="redis") | Fast reads, session data, ephemeral views |
# 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()).
# 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.
# 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).
# 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.
@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.
# 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.
check and resolve what it reportsassets/read_model_cross_aggregate.py (opens in a new tab)assets/read_model_multiple_events.py (opens in a new tab)assets/read_model_single_aggregate.py (opens in a new tab)references/choosing-storage.md (opens in a new tab)references/cross-aggregate-read-model.md (opens in a new tab)references/single-aggregate-read-model.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
39 skills in this plugin
/add-commandAdd a complete command flow to an existing aggregate. It creates a command class, a FastAPI API endpoint, and a command handler with repository logic. This is the primary workflow for adding write operations to a Protean domain. Use when the user wants to "add a command", "add an action", "add an operation", "expose a write endpoint", "create a command flow", "wire up a POST endpoint", "add a new operation to an aggregate", or describes an action like "I want users to be able to [verb] a [thing]" (e.g., "place an order", "register a user", "cancel a reservation"). This workflow composes the command, command-handler, and api-endpoint element skills./add-domain-service-flowBuild a domain service flow in Protean for business logic that spans two or more aggregates. Domain services are stateless, encapsulate cross-aggregate business rules, and run pre/post invariants for validation. They are used when business logic doesn't naturally belong to a single aggregate. Wire them into command handlers or application services for persistence. Use when the user asks to "add a domain service", "implement cross-aggregate logic", "coordinate multiple aggregates", "add a business operation spanning aggregates", "validate across aggregates", or when they describe scenarios like "placing an order checks inventory and reserves stock", "transferring funds between accounts", "scheduling involves both resource and calendar".npx claudepluginhub proteanhq/protean --plugin proteanOther plugins' skills for the same job