Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Build read models and projections from event streams. Use when implementing CQRS read sides, building materialized views, or optimizing query performance in event-sourced systems.
.claude/skills/dicklesworthstone-projection-patterns/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-10 | ✗→✓ | ▲ Improved | 184% | 0% |
| case-12 | ✗→✓ | ▲ Improved | 117% | 0% |
| case-15 | ✗→✓ | ▲ Improved | 94% | 0% |
| case-17 | ✗→✓ | ▲ Improved | 141% | 0% |
| case-05 | ✓→✓ | = Same ✓ | 135% | 0% |
Comprehensive guide to building projections and read models for event-sourced systems.
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Event Store │────►│ Projector │────►│ Read Model │
│ │ │ │ │ (Database) │
│ ┌─────────┐ │ │ ┌─────────┐ │ │ ┌─────────┐ │
│ │ Events │ │ │ │ Handler │ │ │ │ Tables │ │
│ └─────────┘ │ │ │ Logic │ │ │ │ Views │ │
│ │ │ └─────────┘ │ │ │ Cache │ │
└─────────────┘ └─────────────┘ └─────────────┘| Type | Description | Use Case | | -------------- | --------------------------- | ---------------------- | | Live | Real-time from subscription | Current state queries | | Catchup | Process historical events | Rebuilding read models | | Persistent | Stores checkpoint | Resume after restart | | Inline | Same transaction as write | Strong consistency |
pythonfrom abc import ABC, abstractmethod from dataclasses import dataclass from typing import Dict, Any, Callable, List import asyncpg @dataclass class Event: stream_id: str event_type: str data: dict version: int global_position: int class Projection(ABC): """Base class for projections.""" @property @abstractmethod def name(self) -> str: """Unique projection name for checkpointing.""" pass @abstractmethod def handles(self) -> List[str]: """List of event types this projection handles.""" pass @abstractmethod async def apply(self, event: Event) -> None: """Apply event to the read model.""" pass class Projector: """Runs projections from event store.""" def __init__(self, event_store, checkpoint_store): self.event_store = event_store self.checkpoint_store = checkpoint_store self.projections: List[Projection] = [] def register(self, projection: Projection): self.projections.append(projection) async def run(self, batch_size: int = 100): """Run all projections continuously.""" while True: for projection in self.projections: await self._run_projection(projection, batch_size) await asyncio.sleep(0.1) async def _run_projection(self, projection: Projection, batch_size: int): checkpoint = await self.checkpoint_store.get(projection.name) position = checkpoint or 0 events = await self.event_store.read_all(position, batch_size) for event in events: if event.event_type in projection.handles(): await projection.apply(event) await self.checkpoint_store.save( projection.name, event.global_position ) async def rebuild(self, projection: Projection): """Rebuild a projection from scratch.""" await self.checkpoint_store.delete(projection.name) # Optionally clear read model tables await self._run_projection(projection, batch_size=1000)
pythonclass OrderSummaryProjection(Projection): """Projects order events to a summary read model.""" def __init__(self, db_pool: asyncpg.Pool): self.pool = db_pool @property def name(self) -> str: return "order_summary" def handles(self) -> List[str]: return [ "OrderCreated", "OrderItemAdded", "OrderItemRemoved", "OrderShipped", "OrderCompleted", "OrderCancelled" ] async def apply(self, event: Event) -> None: handlers = { "OrderCreated": self._handle_created, "OrderItemAdded": self._handle_item_added, "OrderItemRemoved": self._handle_item_removed, "OrderShipped": self._handle_shipped, "OrderCompleted": self._handle_completed, "OrderCancelled": self._handle_cancelled, } handler = handlers.get(event.event_type) if handler: await handler(event) async def _handle_created(self, event: Event): async with self.pool.acquire() as conn: await conn.execute( """ INSERT INTO order_summaries (order_id, customer_id, status, total_amount, item_count, created_at) VALUES ($1, $2, $3, $4, $5, $6) """, event.data['order_id'], event.data['customer_id'], 'pending', 0, 0, event.data['created_at'] ) async def _handle_item_added(self, event: Event): async with self.pool.acquire() as conn: await conn.execute( """ UPDATE order_summaries SET total_amount = total_amount + $2, item_count = item_count + 1, updated_at = NOW() WHERE order_id = $1 """, event.data['order_id'], event.data['price'] * event.data['quantity'] ) async def _handle_item_removed(self, event: Event): async with self.pool.acquire() as conn: await conn.execute( """ UPDATE order_summaries SET total_amount = total_amount - $2, item_count = item_count - 1, updated_at = NOW() WHERE order_id = $1 """, event.data['order_id'], event.data['price'] * event.data['quantity'] ) async def _handle_shipped(self, event: Event): async with self.pool.acquire() as conn: await conn.execute( """ UPDATE order_summaries SET status = 'shipped', shipped_at = $2, updated_at = NOW() WHERE order_id = $1 """, event.data['order_id'], event.data['shipped_at'] ) async def _handle_completed(self, event: Event): async with self.pool.acquire() as conn: await conn.execute( """ UPDATE order_summaries SET status = 'completed', completed_at = $2, updated_at = NOW() WHERE order_id = $1 """, event.data['order_id'], event.data['completed_at'] ) async def _handle_cancelled(self, event: Event): async with self.pool.acquire() as conn: await conn.execute( """ UPDATE order_summaries SET status = 'cancelled', cancelled_at = $2, cancellation_reason = $3, updated_at = NOW() WHERE order_id = $1 """, event.data['order_id'], event.data['cancelled_at'], event.data.get('reason') )
pythonfrom elasticsearch import AsyncElasticsearch class ProductSearchProjection(Projection): """Projects product events to Elasticsearch for full-text search.""" def __init__(self, es_client: AsyncElasticsearch): self.es = es_client self.index = "products" @property def name(self) -> str: return "product_search" def handles(self) -> List[str]: return [ "ProductCreated", "ProductUpdated", "ProductPriceChanged", "ProductDeleted" ] async def apply(self, event: Event) -> None: if event.event_type == "ProductCreated": await self.es.index( index=self.index, id=event.data['product_id'], document={ 'name': event.data['name'], 'description': event.data['description'], 'category': event.data['category'], 'price': event.data['price'], 'tags': event.data.get('tags', []), 'created_at': event.data['created_at'] } ) elif event.event_type == "ProductUpdated": await self.es.update( index=self.index, id=event.data['product_id'], doc={ 'name': event.data['name'], 'description': event.data['description'], 'category': event.data['category'], 'tags': event.data.get('tags', []), 'updated_at': event.data['updated_at'] } ) elif event.event_type == "ProductPriceChanged": await self.es.update( index=self.index, id=event.data['product_id'], doc={ 'price': event.data['new_price'], 'price_updated_at': event.data['changed_at'] } ) elif event.event_type == "ProductDeleted": await self.es.delete( index=self.index, id=event.data['product_id'] )
pythonclass DailySalesProjection(Projection): """Aggregates sales data by day for reporting.""" def __init__(self, db_pool: asyncpg.Pool): self.pool = db_pool @property def name(self) -> str: return "daily_sales" def handles(self) -> List[str]: return ["OrderCompleted", "OrderRefunded"] async def apply(self, event: Event) -> None: if event.event_type == "OrderCompleted": await self._increment_sales(event) elif event.event_type == "OrderRefunded": await self._decrement_sales(event) async def _increment_sales(self, event: Event): date = event.data['completed_at'][:10] # YYYY-MM-DD async with self.pool.acquire() as conn: await conn.execute( """ INSERT INTO daily_sales (date, total_orders, total_revenue, total_items) VALUES ($1, 1, $2, $3) ON CONFLICT (date) DO UPDATE SET total_orders = daily_sales.total_orders + 1, total_revenue = daily_sales.total_revenue + $2, total_items = daily_sales.total_items + $3, updated_at = NOW() """, date, event.data['total_amount'], event.data['item_count'] ) async def _decrement_sales(self, event: Event): date = event.data['original_completed_at'][:10] async with self.pool.acquire() as conn: await conn.execute( """ UPDATE daily_sales SET total_orders = total_orders - 1, total_revenue = total_revenue - $2, total_refunds = total_refunds + $2, updated_at = NOW() WHERE date = $1 """, date, event.data['refund_amount'] )
pythonclass CustomerActivityProjection(Projection): """Projects customer activity across multiple tables.""" def __init__(self, db_pool: asyncpg.Pool): self.pool = db_pool @property def name(self) -> str: return "customer_activity" def handles(self) -> List[str]: return [ "CustomerCreated", "OrderCompleted", "ReviewSubmitted", "CustomerTierChanged" ] async def apply(self, event: Event) -> None: async with self.pool.acquire() as conn: async with conn.transaction(): if event.event_type == "CustomerCreated": # Insert into customers table await conn.execute( """ INSERT INTO customers (customer_id, email, name, tier, created_at) VALUES ($1, $2, $3, 'bronze', $4) """, event.data['customer_id'], event.data['email'], event.data['name'], event.data['created_at'] ) # Initialize activity summary await conn.execute( """ INSERT INTO customer_activity_summary (customer_id, total_orders, total_spent, total_reviews) VALUES ($1, 0, 0, 0) """, event.data['customer_id'] ) elif event.event_type == "OrderCompleted": # Update activity summary await conn.execute( """ UPDATE customer_activity_summary SET total_orders = total_orders + 1, total_spent = total_spent + $2, last_order_at = $3 WHERE customer_id = $1 """, event.data['customer_id'], event.data['total_amount'], event.data['completed_at'] ) # Insert into order history await conn.execute( """ INSERT INTO customer_order_history (customer_id, order_id, amount, completed_at) VALUES ($1, $2, $3, $4) """, event.data['customer_id'], event.data['order_id'], event.data['total_amount'], event.data['completed_at'] ) elif event.event_type == "ReviewSubmitted": await conn.execute( """ UPDATE customer_activity_summary SET total_reviews = total_reviews + 1, last_review_at = $2 WHERE customer_id = $1 """, event.data['customer_id'], event.data['submitted_at'] ) elif event.event_type == "CustomerTierChanged": await conn.execute( """ UPDATE customers SET tier = $2, updated_at = NOW() WHERE customer_id = $1 """, event.data['customer_id'], event.data['new_tier'] )
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-04 | fail→fail | 21,940 | 20,185 | -8% | 1 | 1 | 0% | 4,237 | 7,620 | +80% | 0 | 0 | — |
case-11 | fail→fail | 16,341 | 13,588 | -17% | 1 | 1 | 0% | 3,121 | 6,376 | +104% | 0 | 0 | — |
case-01 | fail→fail | 30,553 | 37,668 | +23% | 1 | 1 | 0% | 6,323 | 8,989 | +42% | 0 | 0 | — |
case-02 | fail→fail | 21,007 | 28,260 | +35% | 1 | 1 | 0% | 4,475 | 8,278 | +85% | 0 | 0 | — |
case-03 | fail→fail | 22,443 | 18,390 | -18% | 1 | 1 | 0% | 4,482 | 7,557 | +69% | 0 | 0 | — |
case-05 | pass→pass | 22,270 | 22,473 | +1% | 1 | 1 | 0% | 3,419 | 8,038 | +135% | 0 | 0 | — |
case-06 | pass→pass | 19,073 | 22,299 | +17% | 1 | 1 | 0% | 2,884 | 7,271 | +152% | 0 | 0 | — |
case-07 | fail→fail | 20,357 | 21,336 | +5% | 1 | 1 | 0% | 3,789 | 7,784 | +105% | 0 | 0 | — |
case-08 | pass→pass | 19,751 | 18,202 | -8% | 1 | 1 | 0% | 2,967 | 6,575 | +122% | 0 | 0 | — |
case-09 | fail→fail | 15,752 | 17,948 | +14% | 1 | 1 | 0% | 2,538 | 6,944 | +174% | 0 | 0 | — |
case-10 | fail→pass | 14,118 | 12,327 | -13% | 1 | 1 | 0% | 2,112 | 5,999 | +184% | 0 | 0 | — |
case-12 | fail→pass | 19,459 | 18,990 | -2% | 1 | 1 | 0% | 3,265 | 7,085 | +117% | 0 | 0 | — |
case-13 | fail→fail | 13,589 | 8,342 | -39% | 1 | 1 | 0% | 2,672 | 5,337 | +100% | 0 | 0 | — |
case-14 | pass→pass | 13,280 | 5,238 | -61% | 1 | 1 | 0% | 2,346 | 4,742 | +102% | 0 | 0 | — |
case-15 | fail→pass | 23,634 | 14,170 | -40% | 1 | 1 | 0% | 3,351 | 6,499 | +94% | 0 | 0 | — |
case-16 | fail→fail | 10,106 | 9,514 | -6% | 1 | 1 | 0% | 1,594 | 5,349 | +236% | 0 | 0 | — |
case-17 | fail→pass | 20,626 | 21,049 | +2% | 1 | 1 | 0% | 2,967 | 7,147 | +141% | 0 | 0 | — |
case-18 | pass→pass | 14,755 | 13,468 | -9% | 1 | 1 | 0% | 2,253 | 6,134 | +172% | 0 | 0 | — |
case-19 | fail→fail | 13,501 | 12,085 | -10% | 1 | 1 | 0% | 2,456 | 6,026 | +145% | 0 | 0 | — |
case-20 | pass→pass | 17,559 | 8,610 | -51% | 1 | 1 | 0% | 3,278 | 5,311 | +62% | 0 | 0 | — |
case-21 | fail→fail | 16,052 | 17,633 | +10% | 1 | 1 | 0% | 3,252 | 7,272 | +124% | 0 | 0 | — |
case-22 | pass→pass | 16,009 | 19,359 | +21% | 1 | 1 | 0% | 2,994 | 6,673 | +123% | 0 | 0 | — |
case-23 | pass→pass | 17,004 | 15,085 | -11% | 1 | 1 | 0% | 3,141 | 6,661 | +112% | 0 | 0 | — |
case-24 | pass→pass | 15,987 | 14,268 | -11% | 1 | 1 | 0% | 2,724 | 6,494 | +138% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 24 cases were attempted. The headline lift of +17 percentage points is the difference between those two pass rates over the 24 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.