[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BMQJMMNAHR7MJSC4FJEBVS":3,"skill-same:01M7BMQJMMNAHR7MJSC4FJEBVS":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7BMQJMMNAHR7MJSC4FJEBVS","cqrs-implementation",null,"Implement Command Query Responsibility Segregation for scalable architectures. Use when separating read and write models, optimizing query performance, or building event-sourced systems.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Agent-智能体\u002FYYC3-Agent-智能体-agents\u002Fplugins\u002Fbackend-development\u002Fskills\u002Fcqrs-implementation\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: cqrs-implementation\ndescription: Implement Command Query Responsibility Segregation for scalable architectures. Use when separating read and write models, optimizing query performance, or building event-sourced systems.\n---\n\n# CQRS Implementation\n\nComprehensive guide to implementing CQRS (Command Query Responsibility Segregation) patterns.\n\n## When to Use This Skill\n\n- Separating read and write concerns\n- Scaling reads independently from writes\n- Building event-sourced systems\n- Optimizing complex query scenarios\n- Different read\u002Fwrite data models needed\n- High-performance reporting requirements\n\n## Core Concepts\n\n### 1. CQRS Architecture\n\n```\n                    ┌─────────────┐\n                    │   Client    │\n                    └──────┬──────┘\n                           │\n              ┌────────────┴────────────┐\n              │                         │\n              ▼                         ▼\n       ┌─────────────┐          ┌─────────────┐\n       │  Commands   │          │   Queries   │\n       │    API      │          │    API      │\n       └──────┬──────┘          └──────┬──────┘\n              │                         │\n              ▼                         ▼\n       ┌─────────────┐          ┌─────────────┐\n       │  Command    │          │   Query     │\n       │  Handlers   │          │  Handlers   │\n       └──────┬──────┘          └──────┬──────┘\n              │                         │\n              ▼                         ▼\n       ┌─────────────┐          ┌─────────────┐\n       │   Write     │─────────►│    Read     │\n       │   Model     │  Events  │   Model     │\n       └─────────────┘          └─────────────┘\n```\n\n### 2. Key Components\n\n| Component           | Responsibility                  |\n| ------------------- | ------------------------------- |\n| **Command**         | Intent to change state          |\n| **Command Handler** | Validates and executes commands |\n| **Event**           | Record of state change          |\n| **Query**           | Request for data                |\n| **Query Handler**   | Retrieves data from read model  |\n| **Projector**       | Updates read model from events  |\n\n## Templates\n\n### Template 1: Command Infrastructure\n\n```python\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom typing import TypeVar, Generic, Dict, Any, Type\nfrom datetime import datetime\nimport uuid\n\n# Command base\n@dataclass\nclass Command:\n    command_id: str = None\n    timestamp: datetime = None\n\n    def __post_init__(self):\n        self.command_id = self.command_id or str(uuid.uuid4())\n        self.timestamp = self.timestamp or datetime.utcnow()\n\n\n# Concrete commands\n@dataclass\nclass CreateOrder(Command):\n    customer_id: str\n    items: list\n    shipping_address: dict\n\n\n@dataclass\nclass AddOrderItem(Command):\n    order_id: str\n    product_id: str\n    quantity: int\n    price: float\n\n\n@dataclass\nclass CancelOrder(Command):\n    order_id: str\n    reason: str\n\n\n# Command handler base\nT = TypeVar('T', bound=Command)\n\nclass CommandHandler(ABC, Generic[T]):\n    @abstractmethod\n    async def handle(self, command: T) -> Any:\n        pass\n\n\n# Command bus\nclass CommandBus:\n    def __init__(self):\n        self._handlers: Dict[Type[Command], CommandHandler] = {}\n\n    def register(self, command_type: Type[Command], handler: CommandHandler):\n        self._handlers[command_type] = handler\n\n    async def dispatch(self, command: Command) -> Any:\n        handler = self._handlers.get(type(command))\n        if not handler:\n            raise ValueError(f\"No handler for {type(command).__name__}\")\n        return await handler.handle(command)\n\n\n# Command handler implementation\nclass CreateOrderHandler(CommandHandler[CreateOrder]):\n    def __init__(self, order_repository, event_store):\n        self.order_repository = order_repository\n        self.event_store = event_store\n\n    async def handle(self, command: CreateOrder) -> str:\n        # Validate\n        if not command.items:\n            raise ValueError(\"Order must have at least one item\")\n\n        # Create aggregate\n        order = Order.create(\n            customer_id=command.customer_id,\n            items=command.items,\n            shipping_address=command.shipping_address\n        )\n\n        # Persist events\n        await self.event_store.append_events(\n            stream_id=f\"Order-{order.id}\",\n            stream_type=\"Order\",\n            events=order.uncommitted_events\n        )\n\n        return order.id\n```\n\n### Template 2: Query Infrastructure\n\n```python\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom typing import TypeVar, Generic, List, Optional\n\n# Query base\n@dataclass\nclass Query:\n    pass\n\n\n# Concrete queries\n@dataclass\nclass GetOrderById(Query):\n    order_id: str\n\n\n@dataclass\nclass GetCustomerOrders(Query):\n    customer_id: str\n    status: Optional[str] = None\n    page: int = 1\n    page_size: int = 20\n\n\n@dataclass\nclass SearchOrders(Query):\n    query: str\n    filters: dict = None\n    sort_by: str = \"created_at\"\n    sort_order: str = \"desc\"\n\n\n# Query result types\n@dataclass\nclass OrderView:\n    order_id: str\n    customer_id: str\n    status: str\n    total_amount: float\n    item_count: int\n    created_at: datetime\n    shipped_at: Optional[datetime] = None\n\n\n@dataclass\nclass PaginatedResult(Generic[T]):\n    items: List[T]\n    total: int\n    page: int\n    page_size: int\n\n    @property\n    def total_pages(self) -> int:\n        return (self.total + self.page_size - 1) \u002F\u002F self.page_size\n\n\n# Query handler base\nT = TypeVar('T', bound=Query)\nR = TypeVar('R')\n\nclass QueryHandler(ABC, Generic[T, R]):\n    @abstractmethod\n    async def handle(self, query: T) -> R:\n        pass\n\n\n# Query bus\nclass QueryBus:\n    def __init__(self):\n        self._handlers: Dict[Type[Query], QueryHandler] = {}\n\n    def register(self, query_type: Type[Query], handler: QueryHandler):\n        self._handlers[query_type] = handler\n\n    async def dispatch(self, query: Query) -> Any:\n        handler = self._handlers.get(type(query))\n        if not handler:\n            raise ValueError(f\"No handler for {type(query).__name__}\")\n        return await handler.handle(query)\n\n\n# Query handler implementation\nclass GetOrderByIdHandler(QueryHandler[GetOrderById, Optional[OrderView]]):\n    def __init__(self, read_db):\n        self.read_db = read_db\n\n    async def handle(self, query: GetOrderById) -> Optional[OrderView]:\n        async with self.read_db.acquire() as conn:\n            row = await conn.fetchrow(\n                \"\"\"\n                SELECT order_id, customer_id, status, total_amount,\n                       item_count, created_at, shipped_at\n                FROM order_views\n                WHERE order_id = $1\n                \"\"\",\n                query.order_id\n            )\n            if row:\n                return OrderView(**dict(row))\n            return None\n\n\nclass GetCustomerOrdersHandler(QueryHandler[GetCustomerOrders, PaginatedResult[OrderView]]):\n    def __init__(self, read_db):\n        self.read_db = read_db\n\n    async def handle(self, query: GetCustomerOrders) -> PaginatedResult[OrderView]:\n        async with self.read_db.acquire() as conn:\n            # Build query with optional status filter\n            where_clause = \"customer_id = $1\"\n            params = [query.customer_id]\n\n            if query.status:\n                where_clause += \" AND status = $2\"\n                params.append(query.status)\n\n            # Get total count\n            total = await conn.fetchval(\n                f\"SELECT COUNT(*) FROM order_views WHERE {where_clause}\",\n                *params\n            )\n\n            # Get paginated results\n            offset = (query.page - 1) * query.page_size\n            rows = await conn.fetch(\n                f\"\"\"\n                SELECT order_id, customer_id, status, total_amount,\n                       item_count, created_at, shipped_at\n                FROM order_views\n                WHERE {where_clause}\n                ORDER BY created_at DESC\n                LIMIT ${len(params) + 1} OFFSET ${len(params) + 2}\n                \"\"\",\n                *params, query.page_size, offset\n            )\n\n            return PaginatedResult(\n                items=[OrderView(**dict(row)) for row in rows],\n                total=total,\n                page=query.page,\n                page_size=query.page_size\n            )\n```\n\n### Template 3: FastAPI CQRS Application\n\n```python\nfrom fastapi import FastAPI, HTTPException, Depends\nfrom pydantic import BaseModel\nfrom typing import List, Optional\n\napp = FastAPI()\n\n# Request\u002FResponse models\nclass CreateOrderRequest(BaseModel):\n    customer_id: str\n    items: List[dict]\n    shipping_address: dict\n\n\nclass OrderResponse(BaseModel):\n    order_id: str\n    customer_id: str\n    status: str\n    total_amount: float\n    item_count: int\n    created_at: datetime\n\n\n# Dependency injection\ndef get_command_bus() -> CommandBus:\n    return app.state.command_bus\n\n\ndef get_query_bus() -> QueryBus:\n    return app.state.query_bus\n\n\n# Command endpoints (POST, PUT, DELETE)\n@app.post(\"\u002Forders\", response_model=dict)\nasync def create_order(\n    request: CreateOrderRequest,\n    command_bus: CommandBus = Depends(get_command_bus)\n):\n    command = CreateOrder(\n        customer_id=request.customer_id,\n        items=request.items,\n        shipping_address=request.shipping_address\n    )\n    order_id = await command_bus.dispatch(command)\n    return {\"order_id\": order_id}\n\n\n@app.post(\"\u002Forders\u002F{order_id}\u002Fitems\")\nasync def add_item(\n    order_id: str,\n    product_id: str,\n    quantity: int,\n    price: float,\n    command_bus: CommandBus = Depends(get_command_bus)\n):\n    command = AddOrderItem(\n        order_id=order_id,\n        product_id=product_id,\n        quantity=quantity,\n        price=price\n    )\n    await command_bus.dispatch(command)\n    return {\"status\": \"item_added\"}\n\n\n@app.delete(\"\u002Forders\u002F{order_id}\")\nasync def cancel_order(\n    order_id: str,\n    reason: str,\n    command_bus: CommandBus = Depends(get_command_bus)\n):\n    command = CancelOrder(order_id=order_id, reason=reason)\n    await command_bus.dispatch(command)\n    return {\"status\": \"cancelled\"}\n\n\n# Query endpoints (GET)\n@app.get(\"\u002Forders\u002F{order_id}\", response_model=OrderResponse)\nasync def get_order(\n    order_id: str,\n    query_bus: QueryBus = Depends(get_query_bus)\n):\n    query = GetOrderById(order_id=order_id)\n    result = await query_bus.dispatch(query)\n    if not result:\n        raise HTTPException(status_code=404, detail=\"Order not found\")\n    return result\n\n\n@app.get(\"\u002Fcustomers\u002F{customer_id}\u002Forders\")\nasync def get_customer_orders(\n    customer_id: str,\n    status: Optional[str] = None,\n    page: int = 1,\n    page_size: int = 20,\n    query_bus: QueryBus = Depends(get_query_bus)\n):\n    query = GetCustomerOrders(\n        customer_id=customer_id,\n        status=status,\n        page=page,\n        page_size=page_size\n    )\n    return await query_bus.dispatch(query)\n\n\n@app.get(\"\u002Forders\u002Fsearch\")\nasync def search_orders(\n    q: str,\n    sort_by: str = \"created_at\",\n    query_bus: QueryBus = Depends(get_query_bus)\n):\n    query = SearchOrders(query=q, sort_by=sort_by)\n    return await query_bus.dispatch(query)\n```\n\n### Template 4: Read Model Synchronization\n\n```python\nclass ReadModelSynchronizer:\n    \"\"\"Keeps read models in sync with events.\"\"\"\n\n    def __init__(self, event_store, read_db, projections: List[Projection]):\n        self.event_store = event_store\n        self.read_db = read_db\n        self.projections = {p.name: p for p in projections}\n\n    async def run(self):\n        \"\"\"Continuously sync read models.\"\"\"\n        while True:\n            for name, projection in self.projections.items():\n                await self._sync_projection(projection)\n            await asyncio.sleep(0.1)\n\n    async def _sync_projection(self, projection: Projection):\n        checkpoint = await self._get_checkpoint(projection.name)\n\n        events = await self.event_store.read_all(\n            from_position=checkpoint,\n            limit=100\n        )\n\n        for event in events:\n            if event.event_type in projection.handles():\n                try:\n                    await projection.apply(event)\n                except Exception as e:\n                    # Log error, possibly retry or skip\n                    logger.error(f\"Projection error: {e}\")\n                    continue\n\n            await self._save_checkpoint(projection.name, event.global_position)\n\n    async def rebuild_projection(self, projection_name: str):\n        \"\"\"Rebuild a projection from scratch.\"\"\"\n        projection = self.projections[projection_name]\n\n        # Clear existing data\n        await projection.clear()\n\n        # Reset checkpoint\n        await self._save_checkpoint(projection_name, 0)\n\n        # Rebuild\n        while True:\n            checkpoint = await self._get_checkpoint(projection_name)\n            events = await self.event_store.read_all(checkpoint, 1000)\n\n            if not events:\n                break\n\n            for event in events:\n                if event.event_type in projection.handles():\n                    await projection.apply(event)\n\n            await self._save_checkpoint(\n                projection_name,\n                events[-1].global_position\n            )\n```\n\n### Template 5: Eventual Consistency Handling\n\n```python\nclass ConsistentQueryHandler:\n    \"\"\"Query handler that can wait for consistency.\"\"\"\n\n    def __init__(self, read_db, event_store):\n        self.read_db = read_db\n        self.event_store = event_store\n\n    async def query_after_command(\n        self,\n        query: Query,\n        expected_version: int,\n        stream_id: str,\n        timeout: float = 5.0\n    ):\n        \"\"\"\n        Execute query, ensuring read model is at expected version.\n        Used for read-your-writes consistency.\n        \"\"\"\n        start_time = time.time()\n\n        while time.time() - start_time \u003C timeout:\n            # Check if read model is caught up\n            projection_version = await self._get_projection_version(stream_id)\n\n            if projection_version >= expected_version:\n                return await self.execute_query(query)\n\n            # Wait a bit and retry\n            await asyncio.sleep(0.1)\n\n        # Timeout - return stale data with warning\n        return {\n            \"data\": await self.execute_query(query),\n            \"_warning\": \"Data may be stale\"\n        }\n\n    async def _get_projection_version(self, stream_id: str) -> int:\n        \"\"\"Get the last processed event version for a stream.\"\"\"\n        async with self.read_db.acquire() as conn:\n            return await conn.fetchval(\n                \"SELECT last_event_version FROM projection_state WHERE stream_id = $1\",\n                stream_id\n            ) or 0\n```\n\n## Best Practices\n\n### Do's\n\n- **Separate command and query models** - Different needs\n- **Use eventual consistency** - Accept propagation delay\n- **Validate in command handlers** - Before state change\n- **Denormalize read models** - Optimize for queries\n- **Version your events** - For schema evolution\n\n### Don'ts\n\n- **Don't query in commands** - Use only for writes\n- **Don't couple read\u002Fwrite schemas** - Independent evolution\n- **Don't over-engineer** - Start simple\n- **Don't ignore consistency SLAs** - Define acceptable lag\n","# CQRS Implementation\n\nComprehensive guide to implementing CQRS (Command Query Responsibility Segregation) patterns.\n\n## When to Use This Skill\n\n- Separating read and write concerns\n- Scaling reads independently from writes\n- Building event-sourced systems\n- Optimizing complex query scenarios\n- Different read\u002Fwrite data models needed\n- High-performance reporting requirements\n\n## Core Concepts\n\n### 1. CQRS Architecture\n\n```\n                    ┌─────────────┐\n                    │   Client    │\n                    └──────┬──────┘\n                           │\n              ┌────────────┴────────────┐\n              │                         │\n              ▼                         ▼\n       ┌─────────────┐          ┌─────────────┐\n       │  Commands   │          │   Queries   │\n       │    API      │          │    API      │\n       └──────┬──────┘          └──────┬──────┘\n              │                         │\n              ▼                         ▼\n       ┌─────────────┐          ┌─────────────┐\n       │  Command    │          │   Query     │\n       │  Handlers   │          │  Handlers   │\n       └──────┬──────┘          └──────┬──────┘\n              │                         │\n              ▼                         ▼\n       ┌─────────────┐          ┌─────────────┐\n       │   Write     │─────────►│    Read     │\n       │   Model     │  Events  │   Model     │\n       └─────────────┘          └─────────────┘\n```\n\n### 2. Key Components\n\n| Component           | Responsibility                  |\n| ------------------- | ------------------------------- |\n| **Command**         | Intent to change state          |\n| **Command Handler** | Validates and executes commands |\n| **Event**           | Record of state change          |\n| **Query**           | Request for data                |\n| **Query Handler**   | Retrieves data from read model  |\n| **Projector**       | Updates read model from events  |\n\n## Templates\n\n### Template 1: Command Infrastructure\n\n```python\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom typing import TypeVar, Generic, Dict, Any, Type\nfrom datetime import datetime\nimport uuid\n\n# Command base\n@dataclass\nclass Command:\n    command_id: str = None\n    timestamp: datetime = None\n\n    def __post_init__(self):\n        self.command_id = self.command_id or str(uuid.uuid4())\n        self.timestamp = self.timestamp or datetime.utcnow()\n\n\n# Concrete commands\n@dataclass\nclass CreateOrder(Command):\n    customer_id: str\n    items: list\n    shipping_address: dict\n\n\n@dataclass\nclass AddOrderItem(Command):\n    order_id: str\n    product_id: str\n    quantity: int\n    price: float\n\n\n@dataclass\nclass CancelOrder(Command):\n    order_id: str\n    reason: str\n\n\n# Command handler base\nT = TypeVar('T', bound=Command)\n\nclass CommandHandler(ABC, Generic[T]):\n    @abstractmethod\n    async def handle(self, command: T) -> Any:\n        pass\n\n\n# Command bus\nclass CommandBus:\n    def __init__(self):\n        self._handlers: Dict[Type[Command], CommandHandler] = {}\n\n    def register(self, command_type: Type[Command], handler: CommandHandler):\n        self._handlers[command_type] = handler\n\n    async def dispatch(self, command: Command) -> Any:\n        handler = self._handlers.get(type(command))\n        if not handler:\n            raise ValueError(f\"No handler for {type(command).__name__}\")\n        return await handler.handle(command)\n\n\n# Command handler implementation\nclass CreateOrderHandler(CommandHandler[CreateOrder]):\n    def __init__(self, order_repository, event_store):\n        self.order_repository = order_repository\n        self.event_store = event_store\n\n    async def handle(self, command: CreateOrder) -> str:\n        # Validate\n        if not command.items:\n            raise ValueError(\"Order must have at least one item\")\n\n        # Create aggregate\n        order = Order.create(\n            customer_id=command.customer_id,\n            items=command.items,\n            shipping_address=command.shipping_address\n        )\n\n        # Persist events\n        await self.event_store.append_events(\n            stream_id=f\"Order-{order.id}\",\n            stream_type=\"Order\",\n            events=order.uncommitted_events\n        )\n\n        return order.id\n```\n\n### Template 2: Query Infrastructure\n\n```python\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom typing import TypeVar, Generic, List, Optional\n\n# Query base\n@dataclass\nclass Query:\n    pass\n\n\n# Concrete queries\n@dataclass\nclass GetOrderById(Query):\n    order_id: str\n\n\n@dataclass\nclass GetCustomerOrders(Query):\n    customer_id: str\n    status: Optional[str] = None\n    page: int = 1\n    page_size: int = 20\n\n\n@dataclass\nclass SearchOrders(Query):\n    query: str\n    filters: dict = None\n    sort_by: str = \"created_at\"\n    sort_order: str = \"desc\"\n\n\n# Query result types\n@dataclass\nclass OrderView:\n    order_id: str\n    customer_id: str\n    status: str\n    total_amount: float\n    item_count: int\n    created_at: datetime\n    shipped_at: Optional[datetime] = None\n\n\n@dataclass\nclass PaginatedResult(Generic[T]):\n    items: List[T]\n    total: int\n    page: int\n    page_size: int\n\n    @property\n    def total_pages(self) -> int:\n        return (self.total + self.page_size - 1) \u002F\u002F self.page_size\n\n\n# Query handler base\nT = TypeVar('T', bound=Query)\nR = TypeVar('R')\n\nclass QueryHandler(ABC, Generic[T, R]):\n    @abstractmethod\n    async def handle(self, query: T) -> R:\n        pass\n\n\n# Query bus\nclass QueryBus:\n    def __init__(self):\n        self._handlers: Dict[Type[Query], QueryHandler] = {}\n\n    def register(self, query_type: Type[Query], handler: QueryHandler):\n        self._handlers[query_type] = handler\n\n    async def dispatch(self, query: Query) -> Any:\n        handler = self._handlers.get(type(query))\n        if not handler:\n            raise ValueError(f\"No handler for {type(query).__name__}\")\n        return await handler.handle(query)\n\n\n# Query handler implementation\nclass GetOrderByIdHandler(QueryHandler[GetOrderById, Optional[OrderView]]):\n    def __init__(self, read_db):\n        self.read_db = read_db\n\n    async def handle(self, query: GetOrderById) -> Optional[OrderView]:\n        async with self.read_db.acquire() as conn:\n            row = await conn.fetchrow(\n                \"\"\"\n                SELECT order_id, customer_id, status, total_amount,\n                       item_count, created_at, shipped_at\n                FROM order_views\n                WHERE order_id = $1\n                \"\"\",\n                query.order_id\n            )\n            if row:\n                return OrderView(**dict(row))\n            return None\n\n\nclass GetCustomerOrdersHandler(QueryHandler[GetCustomerOrders, PaginatedResult[OrderView]]):\n    def __init__(self, read_db):\n        self.read_db = read_db\n\n    async def handle(self, query: GetCustomerOrders) -> PaginatedResult[OrderView]:\n        async with self.read_db.acquire() as conn:\n            # Build query with optional status filter\n            where_clause = \"customer_id = $1\"\n            params = [query.customer_id]\n\n            if query.status:\n                where_clause += \" AND status = $2\"\n                params.append(query.status)\n\n            # Get total count\n            total = await conn.fetchval(\n                f\"SELECT COUNT(*) FROM order_views WHERE {where_clause}\",\n                *params\n            )\n\n            # Get paginated results\n            offset = (query.page - 1) * query.page_size\n            rows = await conn.fetch(\n                f\"\"\"\n                SELECT order_id, customer_id, status, total_amount,\n                       item_count, created_at, shipped_at\n                FROM order_views\n                WHERE {where_clause}\n                ORDER BY created_at DESC\n                LIMIT ${len(params) + 1} OFFSET ${len(params) + 2}\n                \"\"\",\n                *params, query.page_size, offset\n            )\n\n            return PaginatedResult(\n                items=[OrderView(**dict(row)) for row in rows],\n                total=total,\n                page=query.page,\n                page_size=query.page_size\n            )\n```\n\n### Template 3: FastAPI CQRS Application\n\n```python\nfrom fastapi import FastAPI, HTTPException, Depends\nfrom pydantic import BaseModel\nfrom typing import List, Optional\n\napp = FastAPI()\n\n# Request\u002FResponse models\nclass CreateOrderRequest(BaseModel):\n    customer_id: str\n    items: List[dict]\n    shipping_address: dict\n\n\nclass OrderResponse(BaseModel):\n    order_id: str\n    customer_id: str\n    status: str\n    total_amount: float\n    item_count: int\n    created_at: datetime\n\n\n# Dependency injection\ndef get_command_bus() -> CommandBus:\n    return app.state.command_bus\n\n\ndef get_query_bus() -> QueryBus:\n    return app.state.query_bus\n\n\n# Command endpoints (POST, PUT, DELETE)\n@app.post(\"\u002Forders\", response_model=dict)\nasync def create_order(\n    request: CreateOrderRequest,\n    command_bus: CommandBus = Depends(get_command_bus)\n):\n    command = CreateOrder(\n        customer_id=request.customer_id,\n        items=request.items,\n        shipping_address=request.shipping_address\n    )\n    order_id = await command_bus.dispatch(command)\n    return {\"order_id\": order_id}\n\n\n@app.post(\"\u002Forders\u002F{order_id}\u002Fitems\")\nasync def add_item(\n    order_id: str,\n    product_id: str,\n    quantity: int,\n    price: float,\n    command_bus: CommandBus = Depends(get_command_bus)\n):\n    command = AddOrderItem(\n        order_id=order_id,\n        product_id=product_id,\n        quantity=quantity,\n        price=price\n    )\n    await command_bus.dispatch(command)\n    return {\"status\": \"item_added\"}\n\n\n@app.delete(\"\u002Forders\u002F{order_id}\")\nasync def cancel_order(\n    order_id: str,\n    reason: str,\n    command_bus: CommandBus = Depends(get_command_bus)\n):\n    command = CancelOrder(order_id=order_id, reason=reason)\n    await command_bus.dispatch(command)\n    return {\"status\": \"cancelled\"}\n\n\n# Query endpoints (GET)\n@app.get(\"\u002Forders\u002F{order_id}\", response_model=OrderResponse)\nasync def get_order(\n    order_id: str,\n    query_bus: QueryBus = Depends(get_query_bus)\n):\n    query = GetOrderById(order_id=order_id)\n    result = await query_bus.dispatch(query)\n    if not result:\n        raise HTTPException(status_code=404, detail=\"Order not found\")\n    return result\n\n\n@app.get(\"\u002Fcustomers\u002F{customer_id}\u002Forders\")\nasync def get_customer_orders(\n    customer_id: str,\n    status: Optional[str] = None,\n    page: int = 1,\n    page_size: int = 20,\n    query_bus: QueryBus = Depends(get_query_bus)\n):\n    query = GetCustomerOrders(\n        customer_id=customer_id,\n        status=status,\n        page=page,\n        page_size=page_size\n    )\n    return await query_bus.dispatch(query)\n\n\n@app.get(\"\u002Forders\u002Fsearch\")\nasync def search_orders(\n    q: str,\n    sort_by: str = \"created_at\",\n    query_bus: QueryBus = Depends(get_query_bus)\n):\n    query = SearchOrders(query=q, sort_by=sort_by)\n    return await query_bus.dispatch(query)\n```\n\n### Template 4: Read Model Synchronization\n\n```python\nclass ReadModelSynchronizer:\n    \"\"\"Keeps read models in sync with events.\"\"\"\n\n    def __init__(self, event_store, read_db, projections: List[Projection]):\n        self.event_store = event_store\n        self.read_db = read_db\n        self.projections = {p.name: p for p in projections}\n\n    async def run(self):\n        \"\"\"Continuously sync read models.\"\"\"\n        while True:\n            for name, projection in self.projections.items():\n                await self._sync_projection(projection)\n            await asyncio.sleep(0.1)\n\n    async def _sync_projection(self, projection: Projection):\n        checkpoint = await self._get_checkpoint(projection.name)\n\n        events = await self.event_store.read_all(\n            from_position=checkpoint,\n            limit=100\n        )\n\n        for event in events:\n            if event.event_type in projection.handles():\n                try:\n                    await projection.apply(event)\n                except Exception as e:\n                    # Log error, possibly retry or skip\n                    logger.error(f\"Projection error: {e}\")\n                    continue\n\n            await self._save_checkpoint(projection.name, event.global_position)\n\n    async def rebuild_projection(self, projection_name: str):\n        \"\"\"Rebuild a projection from scratch.\"\"\"\n        projection = self.projections[projection_name]\n\n        # Clear existing data\n        await projection.clear()\n\n        # Reset checkpoint\n        await self._save_checkpoint(projection_name, 0)\n\n        # Rebuild\n        while True:\n            checkpoint = await self._get_checkpoint(projection_name)\n            events = await self.event_store.read_all(checkpoint, 1000)\n\n            if not events:\n                break\n\n            for event in events:\n                if event.event_type in projection.handles():\n                    await projection.apply(event)\n\n            await self._save_checkpoint(\n                projection_name,\n                events[-1].global_position\n            )\n```\n\n### Template 5: Eventual Consistency Handling\n\n```python\nclass ConsistentQueryHandler:\n    \"\"\"Query handler that can wait for consistency.\"\"\"\n\n    def __init__(self, read_db, event_store):\n        self.read_db = read_db\n        self.event_store = event_store\n\n    async def query_after_command(\n        self,\n        query: Query,\n        expected_version: int,\n        stream_id: str,\n        timeout: float = 5.0\n    ):\n        \"\"\"\n        Execute query, ensuring read model is at expected version.\n        Used for read-your-writes consistency.\n        \"\"\"\n        start_time = time.time()\n\n        while time.time() - start_time \u003C timeout:\n            # Check if read model is caught up\n            projection_version = await self._get_projection_version(stream_id)\n\n            if projection_version >= expected_version:\n                return await self.execute_query(query)\n\n            # Wait a bit and retry\n            await asyncio.sleep(0.1)\n\n        # Timeout - return stale data with warning\n        return {\n            \"data\": await self.execute_query(query),\n            \"_warning\": \"Data may be stale\"\n        }\n\n    async def _get_projection_version(self, stream_id: str) -> int:\n        \"\"\"Get the last processed event version for a stream.\"\"\"\n        async with self.read_db.acquire() as conn:\n            return await conn.fetchval(\n                \"SELECT last_event_version FROM projection_state WHERE stream_id = $1\",\n                stream_id\n            ) or 0\n```\n\n## Best Practices\n\n### Do's\n\n- **Separate command and query models** - Different needs\n- **Use eventual consistency** - Accept propagation delay\n- **Validate in command handlers** - Before state change\n- **Denormalize read models** - Optimize for queries\n- **Version your events** - For schema evolution\n\n### Don'ts\n\n- **Don't query in commands** - Use only for writes\n- **Don't couple read\u002Fwrite schemas** - Independent evolution\n- **Don't over-engineer** - Start simple\n- **Don't ignore consistency SLAs** - Define acceptable lag\n",{"name":5,"description":7},"main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Agent-智能体\u002FYYC3-Agent-智能体-agents\u002Fplugins\u002Fbackend-development\u002Fskills\u002Fcqrs-implementation",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill cqrs-implementation",{"tool":39,"command":40},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill cqrs-implementation",{"tool":42,"command":43},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill cqrs-implementation","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Agent-智能体\u002FYYC3-Agent-智能体-agents\u002Fplugins\u002Fbackend-development\u002Fskills\u002Fcqrs-implementation\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]