[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HR0R5FE7DN1WJVXXP4DB11":3,"skill-same:01M6HR0R5FE7DN1WJVXXP4DB11":70},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":27,"publishedAt":44,"linkOnly":45,"markdownContent":46,"markdownBody":47,"frontMatter":48,"refName":49,"commitSha":50,"skillDirectory":51,"forksCount":52,"repositoryHtmlUrl":53,"repositoryHomepageUrl":6,"ownerHtmlUrl":54,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":55,"install":56,"resources":69},"01M6HR0R5FE7DN1WJVXXP4DB11","event-store-design",null,"Design and implement event stores for event-sourced systems. Use when building event sourcing infrastructure, choosing event store technologies, or implementing event persistence patterns.","welflau\u002Fai-dev-system","welflau","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F7010385?v=4","01M6HPTDGF18RFY07M229P8CTM","01M6HPTDMRMZCJPYBFEA9XVVYT",3,"MIT","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Fbackend-development\u002Fskills\u002Fevent-store-design\u002FSKILL.md",[17,22],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000015","视觉设计","SCENARIO","使用场景",{"categoryNo":23,"categoryName":24,"taxonomyType":25,"taxonomyTypeDesc":26},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43],"design","event store design","event store","store","event","implement","infrastructure","event sourcing","persistence","use","patterns","systems","implementing","for","sourcing","when","2026-11-10 10:12:30",false,"---\nname: event-store-design\ndescription: Design and implement event stores for event-sourced systems. Use when building event sourcing infrastructure, choosing event store technologies, or implementing event persistence patterns.\n---\n\n# Event Store Design\n\nComprehensive guide to designing event stores for event-sourced applications.\n\n## When to Use This Skill\n\n- Designing event sourcing infrastructure\n- Choosing between event store technologies\n- Implementing custom event stores\n- Optimizing event storage and retrieval\n- Setting up event store schemas\n- Planning for event store scaling\n\n## Core Concepts\n\n### 1. Event Store Architecture\n\n```\n┌─────────────────────────────────────────────────────┐\n│                    Event Store                       │\n├─────────────────────────────────────────────────────┤\n│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐ │\n│  │   Stream 1   │  │   Stream 2   │  │   Stream 3   │ │\n│  │ (Aggregate)  │  │ (Aggregate)  │  │ (Aggregate)  │ │\n│  ├─────────────┤  ├─────────────┤  ├─────────────┤ │\n│  │ Event 1     │  │ Event 1     │  │ Event 1     │ │\n│  │ Event 2     │  │ Event 2     │  │ Event 2     │ │\n│  │ Event 3     │  │ ...         │  │ Event 3     │ │\n│  │ ...         │  │             │  │ Event 4     │ │\n│  └─────────────┘  └─────────────┘  └─────────────┘ │\n├─────────────────────────────────────────────────────┤\n│  Global Position: 1 → 2 → 3 → 4 → 5 → 6 → ...     │\n└─────────────────────────────────────────────────────┘\n```\n\n### 2. Event Store Requirements\n\n| Requirement       | Description                        |\n| ----------------- | ---------------------------------- |\n| **Append-only**   | Events are immutable, only appends |\n| **Ordered**       | Per-stream and global ordering     |\n| **Versioned**     | Optimistic concurrency control     |\n| **Subscriptions** | Real-time event notifications      |\n| **Idempotent**    | Handle duplicate writes safely     |\n\n## Technology Comparison\n\n| Technology       | Best For                  | Limitations                      |\n| ---------------- | ------------------------- | -------------------------------- |\n| **EventStoreDB** | Pure event sourcing       | Single-purpose                   |\n| **PostgreSQL**   | Existing Postgres stack   | Manual implementation            |\n| **Kafka**        | High-throughput streaming | Not ideal for per-stream queries |\n| **DynamoDB**     | Serverless, AWS-native    | Query limitations                |\n| **Marten**       | .NET ecosystems           | .NET specific                    |\n\n## Templates\n\n### Template 1: PostgreSQL Event Store Schema\n\n```sql\n-- Events table\nCREATE TABLE events (\n    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n    stream_id VARCHAR(255) NOT NULL,\n    stream_type VARCHAR(255) NOT NULL,\n    event_type VARCHAR(255) NOT NULL,\n    event_data JSONB NOT NULL,\n    metadata JSONB DEFAULT '{}',\n    version BIGINT NOT NULL,\n    global_position BIGSERIAL,\n    created_at TIMESTAMPTZ DEFAULT NOW(),\n\n    CONSTRAINT unique_stream_version UNIQUE (stream_id, version)\n);\n\n-- Index for stream queries\nCREATE INDEX idx_events_stream_id ON events(stream_id, version);\n\n-- Index for global subscription\nCREATE INDEX idx_events_global_position ON events(global_position);\n\n-- Index for event type queries\nCREATE INDEX idx_events_event_type ON events(event_type);\n\n-- Index for time-based queries\nCREATE INDEX idx_events_created_at ON events(created_at);\n\n-- Snapshots table\nCREATE TABLE snapshots (\n    stream_id VARCHAR(255) PRIMARY KEY,\n    stream_type VARCHAR(255) NOT NULL,\n    snapshot_data JSONB NOT NULL,\n    version BIGINT NOT NULL,\n    created_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- Subscriptions checkpoint table\nCREATE TABLE subscription_checkpoints (\n    subscription_id VARCHAR(255) PRIMARY KEY,\n    last_position BIGINT NOT NULL DEFAULT 0,\n    updated_at TIMESTAMPTZ DEFAULT NOW()\n);\n```\n\n### Template 2: Python Event Store Implementation\n\n```python\nfrom dataclasses import dataclass, field\nfrom datetime import datetime\nfrom typing import Any, Optional, List\nfrom uuid import UUID, uuid4\nimport json\nimport asyncpg\n\n@dataclass\nclass Event:\n    stream_id: str\n    event_type: str\n    data: dict\n    metadata: dict = field(default_factory=dict)\n    event_id: UUID = field(default_factory=uuid4)\n    version: Optional[int] = None\n    global_position: Optional[int] = None\n    created_at: datetime = field(default_factory=datetime.utcnow)\n\n\nclass EventStore:\n    def __init__(self, pool: asyncpg.Pool):\n        self.pool = pool\n\n    async def append_events(\n        self,\n        stream_id: str,\n        stream_type: str,\n        events: List[Event],\n        expected_version: Optional[int] = None\n    ) -> List[Event]:\n        \"\"\"Append events to a stream with optimistic concurrency.\"\"\"\n        async with self.pool.acquire() as conn:\n            async with conn.transaction():\n                # Check expected version\n                if expected_version is not None:\n                    current = await conn.fetchval(\n                        \"SELECT MAX(version) FROM events WHERE stream_id = $1\",\n                        stream_id\n                    )\n                    current = current or 0\n                    if current != expected_version:\n                        raise ConcurrencyError(\n                            f\"Expected version {expected_version}, got {current}\"\n                        )\n\n                # Get starting version\n                start_version = await conn.fetchval(\n                    \"SELECT COALESCE(MAX(version), 0) + 1 FROM events WHERE stream_id = $1\",\n                    stream_id\n                )\n\n                # Insert events\n                saved_events = []\n                for i, event in enumerate(events):\n                    event.version = start_version + i\n                    row = await conn.fetchrow(\n                        \"\"\"\n                        INSERT INTO events (id, stream_id, stream_type, event_type,\n                                          event_data, metadata, version, created_at)\n                        VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n                        RETURNING global_position\n                        \"\"\",\n                        event.event_id,\n                        stream_id,\n                        stream_type,\n                        event.event_type,\n                        json.dumps(event.data),\n                        json.dumps(event.metadata),\n                        event.version,\n                        event.created_at\n                    )\n                    event.global_position = row['global_position']\n                    saved_events.append(event)\n\n                return saved_events\n\n    async def read_stream(\n        self,\n        stream_id: str,\n        from_version: int = 0,\n        limit: int = 1000\n    ) -> List[Event]:\n        \"\"\"Read events from a stream.\"\"\"\n        async with self.pool.acquire() as conn:\n            rows = await conn.fetch(\n                \"\"\"\n                SELECT id, stream_id, event_type, event_data, metadata,\n                       version, global_position, created_at\n                FROM events\n                WHERE stream_id = $1 AND version >= $2\n                ORDER BY version\n                LIMIT $3\n                \"\"\",\n                stream_id, from_version, limit\n            )\n            return [self._row_to_event(row) for row in rows]\n\n    async def read_all(\n        self,\n        from_position: int = 0,\n        limit: int = 1000\n    ) -> List[Event]:\n        \"\"\"Read all events globally.\"\"\"\n        async with self.pool.acquire() as conn:\n            rows = await conn.fetch(\n                \"\"\"\n                SELECT id, stream_id, event_type, event_data, metadata,\n                       version, global_position, created_at\n                FROM events\n                WHERE global_position > $1\n                ORDER BY global_position\n                LIMIT $2\n                \"\"\",\n                from_position, limit\n            )\n            return [self._row_to_event(row) for row in rows]\n\n    async def subscribe(\n        self,\n        subscription_id: str,\n        handler,\n        from_position: int = 0,\n        batch_size: int = 100\n    ):\n        \"\"\"Subscribe to all events from a position.\"\"\"\n        # Get checkpoint\n        async with self.pool.acquire() as conn:\n            checkpoint = await conn.fetchval(\n                \"\"\"\n                SELECT last_position FROM subscription_checkpoints\n                WHERE subscription_id = $1\n                \"\"\",\n                subscription_id\n            )\n            position = checkpoint or from_position\n\n        while True:\n            events = await self.read_all(position, batch_size)\n            if not events:\n                await asyncio.sleep(1)  # Poll interval\n                continue\n\n            for event in events:\n                await handler(event)\n                position = event.global_position\n\n            # Save checkpoint\n            async with self.pool.acquire() as conn:\n                await conn.execute(\n                    \"\"\"\n                    INSERT INTO subscription_checkpoints (subscription_id, last_position)\n                    VALUES ($1, $2)\n                    ON CONFLICT (subscription_id)\n                    DO UPDATE SET last_position = $2, updated_at = NOW()\n                    \"\"\",\n                    subscription_id, position\n                )\n\n    def _row_to_event(self, row) -> Event:\n        return Event(\n            event_id=row['id'],\n            stream_id=row['stream_id'],\n            event_type=row['event_type'],\n            data=json.loads(row['event_data']),\n            metadata=json.loads(row['metadata']),\n            version=row['version'],\n            global_position=row['global_position'],\n            created_at=row['created_at']\n        )\n\n\nclass ConcurrencyError(Exception):\n    \"\"\"Raised when optimistic concurrency check fails.\"\"\"\n    pass\n```\n\n### Template 3: EventStoreDB Usage\n\n```python\nfrom esdbclient import EventStoreDBClient, NewEvent, StreamState\nimport json\n\n# Connect\nclient = EventStoreDBClient(uri=\"esdb:\u002F\u002Flocalhost:2113?tls=false\")\n\n# Append events\ndef append_events(stream_name: str, events: list, expected_revision=None):\n    new_events = [\n        NewEvent(\n            type=event['type'],\n            data=json.dumps(event['data']).encode(),\n            metadata=json.dumps(event.get('metadata', {})).encode()\n        )\n        for event in events\n    ]\n\n    if expected_revision is None:\n        state = StreamState.ANY\n    elif expected_revision == -1:\n        state = StreamState.NO_STREAM\n    else:\n        state = expected_revision\n\n    return client.append_to_stream(\n        stream_name=stream_name,\n        events=new_events,\n        current_version=state\n    )\n\n# Read stream\ndef read_stream(stream_name: str, from_revision: int = 0):\n    events = client.get_stream(\n        stream_name=stream_name,\n        stream_position=from_revision\n    )\n    return [\n        {\n            'type': event.type,\n            'data': json.loads(event.data),\n            'metadata': json.loads(event.metadata) if event.metadata else {},\n            'stream_position': event.stream_position,\n            'commit_position': event.commit_position\n        }\n        for event in events\n    ]\n\n# Subscribe to all\nasync def subscribe_to_all(handler, from_position: int = 0):\n    subscription = client.subscribe_to_all(commit_position=from_position)\n    async for event in subscription:\n        await handler({\n            'type': event.type,\n            'data': json.loads(event.data),\n            'stream_id': event.stream_name,\n            'position': event.commit_position\n        })\n\n# Category projection ($ce-Category)\ndef read_category(category: str):\n    \"\"\"Read all events for a category using system projection.\"\"\"\n    return read_stream(f\"$ce-{category}\")\n```\n\n### Template 4: DynamoDB Event Store\n\n```python\nimport boto3\nfrom boto3.dynamodb.conditions import Key\nfrom datetime import datetime\nimport json\nimport uuid\n\nclass DynamoEventStore:\n    def __init__(self, table_name: str):\n        self.dynamodb = boto3.resource('dynamodb')\n        self.table = self.dynamodb.Table(table_name)\n\n    def append_events(self, stream_id: str, events: list, expected_version: int = None):\n        \"\"\"Append events with conditional write for concurrency.\"\"\"\n        with self.table.batch_writer() as batch:\n            for i, event in enumerate(events):\n                version = (expected_version or 0) + i + 1\n                item = {\n                    'PK': f\"STREAM#{stream_id}\",\n                    'SK': f\"VERSION#{version:020d}\",\n                    'GSI1PK': 'EVENTS',\n                    'GSI1SK': datetime.utcnow().isoformat(),\n                    'event_id': str(uuid.uuid4()),\n                    'stream_id': stream_id,\n                    'event_type': event['type'],\n                    'event_data': json.dumps(event['data']),\n                    'version': version,\n                    'created_at': datetime.utcnow().isoformat()\n                }\n                batch.put_item(Item=item)\n        return events\n\n    def read_stream(self, stream_id: str, from_version: int = 0):\n        \"\"\"Read events from a stream.\"\"\"\n        response = self.table.query(\n            KeyConditionExpression=Key('PK').eq(f\"STREAM#{stream_id}\") &\n                                  Key('SK').gte(f\"VERSION#{from_version:020d}\")\n        )\n        return [\n            {\n                'event_type': item['event_type'],\n                'data': json.loads(item['event_data']),\n                'version': item['version']\n            }\n            for item in response['Items']\n        ]\n\n# Table definition (CloudFormation\u002FTerraform)\n\"\"\"\nDynamoDB Table:\n  - PK (Partition Key): String\n  - SK (Sort Key): String\n  - GSI1PK, GSI1SK for global ordering\n\nCapacity: On-demand or provisioned based on throughput needs\n\"\"\"\n```\n\n## Best Practices\n\n### Do's\n\n- **Use stream IDs that include aggregate type** - `Order-{uuid}`\n- **Include correlation\u002Fcausation IDs** - For tracing\n- **Version events from day one** - Plan for schema evolution\n- **Implement idempotency** - Use event IDs for deduplication\n- **Index appropriately** - For your query patterns\n\n### Don'ts\n\n- **Don't update or delete events** - They're immutable facts\n- **Don't store large payloads** - Keep events small\n- **Don't skip optimistic concurrency** - Prevents data corruption\n- **Don't ignore backpressure** - Handle slow consumers\n\n## Resources\n\n- [EventStoreDB](https:\u002F\u002Fwww.eventstore.com\u002F)\n- [Marten Events](https:\u002F\u002Fmartendb.io\u002Fevents\u002F)\n- [Event Sourcing Pattern](https:\u002F\u002Fdocs.microsoft.com\u002Fen-us\u002Fazure\u002Farchitecture\u002Fpatterns\u002Fevent-sourcing)\n","# Event Store Design\n\nComprehensive guide to designing event stores for event-sourced applications.\n\n## When to Use This Skill\n\n- Designing event sourcing infrastructure\n- Choosing between event store technologies\n- Implementing custom event stores\n- Optimizing event storage and retrieval\n- Setting up event store schemas\n- Planning for event store scaling\n\n## Core Concepts\n\n### 1. Event Store Architecture\n\n```\n┌─────────────────────────────────────────────────────┐\n│                    Event Store                       │\n├─────────────────────────────────────────────────────┤\n│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐ │\n│  │   Stream 1   │  │   Stream 2   │  │   Stream 3   │ │\n│  │ (Aggregate)  │  │ (Aggregate)  │  │ (Aggregate)  │ │\n│  ├─────────────┤  ├─────────────┤  ├─────────────┤ │\n│  │ Event 1     │  │ Event 1     │  │ Event 1     │ │\n│  │ Event 2     │  │ Event 2     │  │ Event 2     │ │\n│  │ Event 3     │  │ ...         │  │ Event 3     │ │\n│  │ ...         │  │             │  │ Event 4     │ │\n│  └─────────────┘  └─────────────┘  └─────────────┘ │\n├─────────────────────────────────────────────────────┤\n│  Global Position: 1 → 2 → 3 → 4 → 5 → 6 → ...     │\n└─────────────────────────────────────────────────────┘\n```\n\n### 2. Event Store Requirements\n\n| Requirement       | Description                        |\n| ----------------- | ---------------------------------- |\n| **Append-only**   | Events are immutable, only appends |\n| **Ordered**       | Per-stream and global ordering     |\n| **Versioned**     | Optimistic concurrency control     |\n| **Subscriptions** | Real-time event notifications      |\n| **Idempotent**    | Handle duplicate writes safely     |\n\n## Technology Comparison\n\n| Technology       | Best For                  | Limitations                      |\n| ---------------- | ------------------------- | -------------------------------- |\n| **EventStoreDB** | Pure event sourcing       | Single-purpose                   |\n| **PostgreSQL**   | Existing Postgres stack   | Manual implementation            |\n| **Kafka**        | High-throughput streaming | Not ideal for per-stream queries |\n| **DynamoDB**     | Serverless, AWS-native    | Query limitations                |\n| **Marten**       | .NET ecosystems           | .NET specific                    |\n\n## Templates\n\n### Template 1: PostgreSQL Event Store Schema\n\n```sql\n-- Events table\nCREATE TABLE events (\n    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n    stream_id VARCHAR(255) NOT NULL,\n    stream_type VARCHAR(255) NOT NULL,\n    event_type VARCHAR(255) NOT NULL,\n    event_data JSONB NOT NULL,\n    metadata JSONB DEFAULT '{}',\n    version BIGINT NOT NULL,\n    global_position BIGSERIAL,\n    created_at TIMESTAMPTZ DEFAULT NOW(),\n\n    CONSTRAINT unique_stream_version UNIQUE (stream_id, version)\n);\n\n-- Index for stream queries\nCREATE INDEX idx_events_stream_id ON events(stream_id, version);\n\n-- Index for global subscription\nCREATE INDEX idx_events_global_position ON events(global_position);\n\n-- Index for event type queries\nCREATE INDEX idx_events_event_type ON events(event_type);\n\n-- Index for time-based queries\nCREATE INDEX idx_events_created_at ON events(created_at);\n\n-- Snapshots table\nCREATE TABLE snapshots (\n    stream_id VARCHAR(255) PRIMARY KEY,\n    stream_type VARCHAR(255) NOT NULL,\n    snapshot_data JSONB NOT NULL,\n    version BIGINT NOT NULL,\n    created_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- Subscriptions checkpoint table\nCREATE TABLE subscription_checkpoints (\n    subscription_id VARCHAR(255) PRIMARY KEY,\n    last_position BIGINT NOT NULL DEFAULT 0,\n    updated_at TIMESTAMPTZ DEFAULT NOW()\n);\n```\n\n### Template 2: Python Event Store Implementation\n\n```python\nfrom dataclasses import dataclass, field\nfrom datetime import datetime\nfrom typing import Any, Optional, List\nfrom uuid import UUID, uuid4\nimport json\nimport asyncpg\n\n@dataclass\nclass Event:\n    stream_id: str\n    event_type: str\n    data: dict\n    metadata: dict = field(default_factory=dict)\n    event_id: UUID = field(default_factory=uuid4)\n    version: Optional[int] = None\n    global_position: Optional[int] = None\n    created_at: datetime = field(default_factory=datetime.utcnow)\n\n\nclass EventStore:\n    def __init__(self, pool: asyncpg.Pool):\n        self.pool = pool\n\n    async def append_events(\n        self,\n        stream_id: str,\n        stream_type: str,\n        events: List[Event],\n        expected_version: Optional[int] = None\n    ) -> List[Event]:\n        \"\"\"Append events to a stream with optimistic concurrency.\"\"\"\n        async with self.pool.acquire() as conn:\n            async with conn.transaction():\n                # Check expected version\n                if expected_version is not None:\n                    current = await conn.fetchval(\n                        \"SELECT MAX(version) FROM events WHERE stream_id = $1\",\n                        stream_id\n                    )\n                    current = current or 0\n                    if current != expected_version:\n                        raise ConcurrencyError(\n                            f\"Expected version {expected_version}, got {current}\"\n                        )\n\n                # Get starting version\n                start_version = await conn.fetchval(\n                    \"SELECT COALESCE(MAX(version), 0) + 1 FROM events WHERE stream_id = $1\",\n                    stream_id\n                )\n\n                # Insert events\n                saved_events = []\n                for i, event in enumerate(events):\n                    event.version = start_version + i\n                    row = await conn.fetchrow(\n                        \"\"\"\n                        INSERT INTO events (id, stream_id, stream_type, event_type,\n                                          event_data, metadata, version, created_at)\n                        VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n                        RETURNING global_position\n                        \"\"\",\n                        event.event_id,\n                        stream_id,\n                        stream_type,\n                        event.event_type,\n                        json.dumps(event.data),\n                        json.dumps(event.metadata),\n                        event.version,\n                        event.created_at\n                    )\n                    event.global_position = row['global_position']\n                    saved_events.append(event)\n\n                return saved_events\n\n    async def read_stream(\n        self,\n        stream_id: str,\n        from_version: int = 0,\n        limit: int = 1000\n    ) -> List[Event]:\n        \"\"\"Read events from a stream.\"\"\"\n        async with self.pool.acquire() as conn:\n            rows = await conn.fetch(\n                \"\"\"\n                SELECT id, stream_id, event_type, event_data, metadata,\n                       version, global_position, created_at\n                FROM events\n                WHERE stream_id = $1 AND version >= $2\n                ORDER BY version\n                LIMIT $3\n                \"\"\",\n                stream_id, from_version, limit\n            )\n            return [self._row_to_event(row) for row in rows]\n\n    async def read_all(\n        self,\n        from_position: int = 0,\n        limit: int = 1000\n    ) -> List[Event]:\n        \"\"\"Read all events globally.\"\"\"\n        async with self.pool.acquire() as conn:\n            rows = await conn.fetch(\n                \"\"\"\n                SELECT id, stream_id, event_type, event_data, metadata,\n                       version, global_position, created_at\n                FROM events\n                WHERE global_position > $1\n                ORDER BY global_position\n                LIMIT $2\n                \"\"\",\n                from_position, limit\n            )\n            return [self._row_to_event(row) for row in rows]\n\n    async def subscribe(\n        self,\n        subscription_id: str,\n        handler,\n        from_position: int = 0,\n        batch_size: int = 100\n    ):\n        \"\"\"Subscribe to all events from a position.\"\"\"\n        # Get checkpoint\n        async with self.pool.acquire() as conn:\n            checkpoint = await conn.fetchval(\n                \"\"\"\n                SELECT last_position FROM subscription_checkpoints\n                WHERE subscription_id = $1\n                \"\"\",\n                subscription_id\n            )\n            position = checkpoint or from_position\n\n        while True:\n            events = await self.read_all(position, batch_size)\n            if not events:\n                await asyncio.sleep(1)  # Poll interval\n                continue\n\n            for event in events:\n                await handler(event)\n                position = event.global_position\n\n            # Save checkpoint\n            async with self.pool.acquire() as conn:\n                await conn.execute(\n                    \"\"\"\n                    INSERT INTO subscription_checkpoints (subscription_id, last_position)\n                    VALUES ($1, $2)\n                    ON CONFLICT (subscription_id)\n                    DO UPDATE SET last_position = $2, updated_at = NOW()\n                    \"\"\",\n                    subscription_id, position\n                )\n\n    def _row_to_event(self, row) -> Event:\n        return Event(\n            event_id=row['id'],\n            stream_id=row['stream_id'],\n            event_type=row['event_type'],\n            data=json.loads(row['event_data']),\n            metadata=json.loads(row['metadata']),\n            version=row['version'],\n            global_position=row['global_position'],\n            created_at=row['created_at']\n        )\n\n\nclass ConcurrencyError(Exception):\n    \"\"\"Raised when optimistic concurrency check fails.\"\"\"\n    pass\n```\n\n### Template 3: EventStoreDB Usage\n\n```python\nfrom esdbclient import EventStoreDBClient, NewEvent, StreamState\nimport json\n\n# Connect\nclient = EventStoreDBClient(uri=\"esdb:\u002F\u002Flocalhost:2113?tls=false\")\n\n# Append events\ndef append_events(stream_name: str, events: list, expected_revision=None):\n    new_events = [\n        NewEvent(\n            type=event['type'],\n            data=json.dumps(event['data']).encode(),\n            metadata=json.dumps(event.get('metadata', {})).encode()\n        )\n        for event in events\n    ]\n\n    if expected_revision is None:\n        state = StreamState.ANY\n    elif expected_revision == -1:\n        state = StreamState.NO_STREAM\n    else:\n        state = expected_revision\n\n    return client.append_to_stream(\n        stream_name=stream_name,\n        events=new_events,\n        current_version=state\n    )\n\n# Read stream\ndef read_stream(stream_name: str, from_revision: int = 0):\n    events = client.get_stream(\n        stream_name=stream_name,\n        stream_position=from_revision\n    )\n    return [\n        {\n            'type': event.type,\n            'data': json.loads(event.data),\n            'metadata': json.loads(event.metadata) if event.metadata else {},\n            'stream_position': event.stream_position,\n            'commit_position': event.commit_position\n        }\n        for event in events\n    ]\n\n# Subscribe to all\nasync def subscribe_to_all(handler, from_position: int = 0):\n    subscription = client.subscribe_to_all(commit_position=from_position)\n    async for event in subscription:\n        await handler({\n            'type': event.type,\n            'data': json.loads(event.data),\n            'stream_id': event.stream_name,\n            'position': event.commit_position\n        })\n\n# Category projection ($ce-Category)\ndef read_category(category: str):\n    \"\"\"Read all events for a category using system projection.\"\"\"\n    return read_stream(f\"$ce-{category}\")\n```\n\n### Template 4: DynamoDB Event Store\n\n```python\nimport boto3\nfrom boto3.dynamodb.conditions import Key\nfrom datetime import datetime\nimport json\nimport uuid\n\nclass DynamoEventStore:\n    def __init__(self, table_name: str):\n        self.dynamodb = boto3.resource('dynamodb')\n        self.table = self.dynamodb.Table(table_name)\n\n    def append_events(self, stream_id: str, events: list, expected_version: int = None):\n        \"\"\"Append events with conditional write for concurrency.\"\"\"\n        with self.table.batch_writer() as batch:\n            for i, event in enumerate(events):\n                version = (expected_version or 0) + i + 1\n                item = {\n                    'PK': f\"STREAM#{stream_id}\",\n                    'SK': f\"VERSION#{version:020d}\",\n                    'GSI1PK': 'EVENTS',\n                    'GSI1SK': datetime.utcnow().isoformat(),\n                    'event_id': str(uuid.uuid4()),\n                    'stream_id': stream_id,\n                    'event_type': event['type'],\n                    'event_data': json.dumps(event['data']),\n                    'version': version,\n                    'created_at': datetime.utcnow().isoformat()\n                }\n                batch.put_item(Item=item)\n        return events\n\n    def read_stream(self, stream_id: str, from_version: int = 0):\n        \"\"\"Read events from a stream.\"\"\"\n        response = self.table.query(\n            KeyConditionExpression=Key('PK').eq(f\"STREAM#{stream_id}\") &\n                                  Key('SK').gte(f\"VERSION#{from_version:020d}\")\n        )\n        return [\n            {\n                'event_type': item['event_type'],\n                'data': json.loads(item['event_data']),\n                'version': item['version']\n            }\n            for item in response['Items']\n        ]\n\n# Table definition (CloudFormation\u002FTerraform)\n\"\"\"\nDynamoDB Table:\n  - PK (Partition Key): String\n  - SK (Sort Key): String\n  - GSI1PK, GSI1SK for global ordering\n\nCapacity: On-demand or provisioned based on throughput needs\n\"\"\"\n```\n\n## Best Practices\n\n### Do's\n\n- **Use stream IDs that include aggregate type** - `Order-{uuid}`\n- **Include correlation\u002Fcausation IDs** - For tracing\n- **Version events from day one** - Plan for schema evolution\n- **Implement idempotency** - Use event IDs for deduplication\n- **Index appropriately** - For your query patterns\n\n### Don'ts\n\n- **Don't update or delete events** - They're immutable facts\n- **Don't store large payloads** - Keep events small\n- **Don't skip optimistic concurrency** - Prevents data corruption\n- **Don't ignore backpressure** - Handle slow consumers\n\n## Resources\n\n- [EventStoreDB](https:\u002F\u002Fwww.eventstore.com\u002F)\n- [Marten Events](https:\u002F\u002Fmartendb.io\u002Fevents\u002F)\n- [Event Sourcing Pattern](https:\u002F\u002Fdocs.microsoft.com\u002Fen-us\u002Fazure\u002Farchitecture\u002Fpatterns\u002Fevent-sourcing)\n",{"name":5,"description":7},"main","18d0e63d1313ca87098f614aa7c1e2dcf6de79c7","backend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Fbackend-development\u002Fskills\u002Fevent-store-design",1,"https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system","https:\u002F\u002Fgithub.com\u002Fwelflau","2026-11-12 14:55:20",{"source":8,"skillName":5,"commands":57,"prompt":67,"zipAvailable":68},[58,61,64],{"tool":59,"command":60},"npx","npx skills add welflau\u002Fai-dev-system --skill event-store-design",{"tool":62,"command":63},"bunx","bunx skills add welflau\u002Fai-dev-system --skill event-store-design",{"tool":65,"command":66},"pnpm","pnpm dlx skills add welflau\u002Fai-dev-system --skill event-store-design","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Fbackend-development\u002Fskills\u002Fevent-store-design\u002FSKILL.md",true,[],[71,103,132,158,180,204],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":75,"licenseFileUrl":76,"sourceHtmlUrl":77,"categories":78,"keywords":85,"publishedAt":102},"01M6HS9Z4B0YA8CJCS2Y2F04Y3","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Fwebapp-testing\u002FSKILL.md",[79,82],{"categoryNo":80,"categoryName":81,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":83,"categoryName":84,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000009","前端开发",[86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,41],"testing","webapp testing","webapp","frontend","screenshots","playwright","web","debugging","toolkit","browser","ui","logs","applications","behavior","local","with","2026-11-11 15:11:14",{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":75,"licenseFileUrl":107,"sourceHtmlUrl":108,"categories":109,"keywords":113,"publishedAt":102},"01M6HRAGMG7JF0HXYHMA5QHS8A","internal-comms","A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill whenever asked to write some sort of internal communications (status reports, leadership updates, 3P updates, company newsletters, FAQs, incident reports, project updates, etc.).","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Finternal-comms\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Finternal-comms\u002FSKILL.md",[110],{"categoryNo":111,"categoryName":112,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000005","邮件与沟通",[114,115,116,117,118,119,37,120,121,122,123,124,125,126,127,128,129,130,131],"internal comms","comms","status","help","SET","write","reports","me","incident","leadership","project","resources","communications","internal communications","formats","sort","my","updates",{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":75,"licenseFileUrl":136,"sourceHtmlUrl":137,"categories":138,"keywords":140,"publishedAt":44},"01M6HSTDP4M3JFXEBK91VFB4PA","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Fweb-artifacts-builder\u002FSKILL.md",[139],{"categoryNo":83,"categoryName":84,"taxonomyType":20,"taxonomyTypeDesc":21},[141,92,142,143,144,89,145,146,147,148,149,150,151,152,37,153,154,155,156,41,157],"web artifacts builder","artifacts","artifacts builder","builder","css","components","react","routing","state management","state","file","Tailwind","single-file","simple","ui components","multi","single",{"skillNo":159,"name":160,"nameZh":6,"description":161,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":75,"licenseFileUrl":162,"sourceHtmlUrl":163,"categories":164,"keywords":168,"publishedAt":44},"01M6HSDXH0JSP8R3QTNY9XZ8HN","frontend-design","Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML\u002FCSS layouts, or when styling\u002Fbeautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics.","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Ffrontend-design\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Ffrontend-design\u002FSKILL.md",[165,166,167],{"categoryNo":83,"categoryName":84,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":23,"categoryName":24,"taxonomyType":25,"taxonomyTypeDesc":26},[89,28,169,145,92,146,147,170,171,172,142,173,98,174,37,175,176,177,178,101,179,43],"frontend design","react components","create","code","examples","landing","ui design","pages","aesthetics","web ui","generic",{"skillNo":181,"name":182,"nameZh":6,"description":183,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":75,"licenseFileUrl":184,"sourceHtmlUrl":185,"categories":186,"keywords":188,"publishedAt":44},"01M6HSA77QYVP7A72HREGTDN2C","algorithmic-art","Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code, generative art, algorithmic art, flow fields, or particle systems. Create original algorithmic art rather than copying existing artists' work to avoid copyright violations.","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Falgorithmic-art\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fplugins\u002Falgorithmic-art\u002FSKILL.md",[187],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},[189,190,191,171,172,192,193,194,195,37,196,197,39,198,101,199,200,201,202,203,43],"algorithmic art","Art","algorithmic","flow","js","work","interactive","generative art","exploration","users","Existing","request","generative","copyright","fields",{"skillNo":205,"name":206,"nameZh":6,"description":207,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":75,"licenseFileUrl":208,"sourceHtmlUrl":209,"categories":210,"keywords":212,"publishedAt":44},"01M6HS9HE0X390Y6RQKTY1YNGJ","theme-factory","Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors\u002Ffonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Ftheme-factory\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Ftheme-factory\u002FSKILL.md",[211],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},[213,214,215,216,94,217,142,118,218,219,174,220,221,176,222,101,223,224,225,41,226,227],"theme factory","factory","theme","docs","generate","fly","slides","styling","artifact","themes","you","fonts","can","apply","new"]