[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HR0WZXV7JM1S1GK19BSYJ9":3,"skill-same:01M6HR0WZXV7JM1S1GK19BSYJ9":64},{"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":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":43,"commitSha":44,"skillDirectory":45,"forksCount":46,"repositoryHtmlUrl":47,"repositoryHomepageUrl":6,"ownerHtmlUrl":48,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":49,"install":50,"resources":63},"01M6HR0WZXV7JM1S1GK19BSYJ9","microservices-patterns",null,"Design microservices architectures with service boundaries, event-driven communication, and resilience patterns. Use when building distributed systems, decomposing monoliths, or implementing microservices.","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\u002Fmicroservices-patterns\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"microservices","microservices patterns","patterns","systems","when","design microservices","implementing","resilience patterns","with","event","event-driven","architectures","driven","design","service","distributed systems","use","communication","distributed","resilience","2026-11-10 10:12:30",false,"---\nname: microservices-patterns\ndescription: Design microservices architectures with service boundaries, event-driven communication, and resilience patterns. Use when building distributed systems, decomposing monoliths, or implementing microservices.\n---\n\n# Microservices Patterns\n\nMaster microservices architecture patterns including service boundaries, inter-service communication, data management, and resilience patterns for building distributed systems.\n\n## When to Use This Skill\n\n- Decomposing monoliths into microservices\n- Designing service boundaries and contracts\n- Implementing inter-service communication\n- Managing distributed data and transactions\n- Building resilient distributed systems\n- Implementing service discovery and load balancing\n- Designing event-driven architectures\n\n## Core Concepts\n\n### 1. Service Decomposition Strategies\n\n**By Business Capability**\n\n- Organize services around business functions\n- Each service owns its domain\n- Example: OrderService, PaymentService, InventoryService\n\n**By Subdomain (DDD)**\n\n- Core domain, supporting subdomains\n- Bounded contexts map to services\n- Clear ownership and responsibility\n\n**Strangler Fig Pattern**\n\n- Gradually extract from monolith\n- New functionality as microservices\n- Proxy routes to old\u002Fnew systems\n\n### 2. Communication Patterns\n\n**Synchronous (Request\u002FResponse)**\n\n- REST APIs\n- gRPC\n- GraphQL\n\n**Asynchronous (Events\u002FMessages)**\n\n- Event streaming (Kafka)\n- Message queues (RabbitMQ, SQS)\n- Pub\u002FSub patterns\n\n### 3. Data Management\n\n**Database Per Service**\n\n- Each service owns its data\n- No shared databases\n- Loose coupling\n\n**Saga Pattern**\n\n- Distributed transactions\n- Compensating actions\n- Eventual consistency\n\n### 4. Resilience Patterns\n\n**Circuit Breaker**\n\n- Fail fast on repeated errors\n- Prevent cascade failures\n\n**Retry with Backoff**\n\n- Transient fault handling\n- Exponential backoff\n\n**Bulkhead**\n\n- Isolate resources\n- Limit impact of failures\n\n## Service Decomposition Patterns\n\n### Pattern 1: By Business Capability\n\n```python\n# E-commerce example\n\n# Order Service\nclass OrderService:\n    \"\"\"Handles order lifecycle.\"\"\"\n\n    async def create_order(self, order_data: dict) -> Order:\n        order = Order.create(order_data)\n\n        # Publish event for other services\n        await self.event_bus.publish(\n            OrderCreatedEvent(\n                order_id=order.id,\n                customer_id=order.customer_id,\n                items=order.items,\n                total=order.total\n            )\n        )\n\n        return order\n\n# Payment Service (separate service)\nclass PaymentService:\n    \"\"\"Handles payment processing.\"\"\"\n\n    async def process_payment(self, payment_request: PaymentRequest) -> PaymentResult:\n        # Process payment\n        result = await self.payment_gateway.charge(\n            amount=payment_request.amount,\n            customer=payment_request.customer_id\n        )\n\n        if result.success:\n            await self.event_bus.publish(\n                PaymentCompletedEvent(\n                    order_id=payment_request.order_id,\n                    transaction_id=result.transaction_id\n                )\n            )\n\n        return result\n\n# Inventory Service (separate service)\nclass InventoryService:\n    \"\"\"Handles inventory management.\"\"\"\n\n    async def reserve_items(self, order_id: str, items: List[OrderItem]) -> ReservationResult:\n        # Check availability\n        for item in items:\n            available = await self.inventory_repo.get_available(item.product_id)\n            if available \u003C item.quantity:\n                return ReservationResult(\n                    success=False,\n                    error=f\"Insufficient inventory for {item.product_id}\"\n                )\n\n        # Reserve items\n        reservation = await self.create_reservation(order_id, items)\n\n        await self.event_bus.publish(\n            InventoryReservedEvent(\n                order_id=order_id,\n                reservation_id=reservation.id\n            )\n        )\n\n        return ReservationResult(success=True, reservation=reservation)\n```\n\n### Pattern 2: API Gateway\n\n```python\nfrom fastapi import FastAPI, HTTPException, Depends\nimport httpx\nfrom circuitbreaker import circuit\n\napp = FastAPI()\n\nclass APIGateway:\n    \"\"\"Central entry point for all client requests.\"\"\"\n\n    def __init__(self):\n        self.order_service_url = \"http:\u002F\u002Forder-service:8000\"\n        self.payment_service_url = \"http:\u002F\u002Fpayment-service:8001\"\n        self.inventory_service_url = \"http:\u002F\u002Finventory-service:8002\"\n        self.http_client = httpx.AsyncClient(timeout=5.0)\n\n    @circuit(failure_threshold=5, recovery_timeout=30)\n    async def call_order_service(self, path: str, method: str = \"GET\", **kwargs):\n        \"\"\"Call order service with circuit breaker.\"\"\"\n        response = await self.http_client.request(\n            method,\n            f\"{self.order_service_url}{path}\",\n            **kwargs\n        )\n        response.raise_for_status()\n        return response.json()\n\n    async def create_order_aggregate(self, order_id: str) -> dict:\n        \"\"\"Aggregate data from multiple services.\"\"\"\n        # Parallel requests\n        order, payment, inventory = await asyncio.gather(\n            self.call_order_service(f\"\u002Forders\u002F{order_id}\"),\n            self.call_payment_service(f\"\u002Fpayments\u002Forder\u002F{order_id}\"),\n            self.call_inventory_service(f\"\u002Freservations\u002Forder\u002F{order_id}\"),\n            return_exceptions=True\n        )\n\n        # Handle partial failures\n        result = {\"order\": order}\n        if not isinstance(payment, Exception):\n            result[\"payment\"] = payment\n        if not isinstance(inventory, Exception):\n            result[\"inventory\"] = inventory\n\n        return result\n\n@app.post(\"\u002Fapi\u002Forders\")\nasync def create_order(\n    order_data: dict,\n    gateway: APIGateway = Depends()\n):\n    \"\"\"API Gateway endpoint.\"\"\"\n    try:\n        # Route to order service\n        order = await gateway.call_order_service(\n            \"\u002Forders\",\n            method=\"POST\",\n            json=order_data\n        )\n        return {\"order\": order}\n    except httpx.HTTPError as e:\n        raise HTTPException(status_code=503, detail=\"Order service unavailable\")\n```\n\n## Communication Patterns\n\n### Pattern 1: Synchronous REST Communication\n\n```python\n# Service A calls Service B\nimport httpx\nfrom tenacity import retry, stop_after_attempt, wait_exponential\n\nclass ServiceClient:\n    \"\"\"HTTP client with retries and timeout.\"\"\"\n\n    def __init__(self, base_url: str):\n        self.base_url = base_url\n        self.client = httpx.AsyncClient(\n            timeout=httpx.Timeout(5.0, connect=2.0),\n            limits=httpx.Limits(max_keepalive_connections=20)\n        )\n\n    @retry(\n        stop=stop_after_attempt(3),\n        wait=wait_exponential(multiplier=1, min=2, max=10)\n    )\n    async def get(self, path: str, **kwargs):\n        \"\"\"GET with automatic retries.\"\"\"\n        response = await self.client.get(f\"{self.base_url}{path}\", **kwargs)\n        response.raise_for_status()\n        return response.json()\n\n    async def post(self, path: str, **kwargs):\n        \"\"\"POST request.\"\"\"\n        response = await self.client.post(f\"{self.base_url}{path}\", **kwargs)\n        response.raise_for_status()\n        return response.json()\n\n# Usage\npayment_client = ServiceClient(\"http:\u002F\u002Fpayment-service:8001\")\nresult = await payment_client.post(\"\u002Fpayments\", json=payment_data)\n```\n\n### Pattern 2: Asynchronous Event-Driven\n\n```python\n# Event-driven communication with Kafka\nfrom aiokafka import AIOKafkaProducer, AIOKafkaConsumer\nimport json\nfrom dataclasses import dataclass, asdict\nfrom datetime import datetime\n\n@dataclass\nclass DomainEvent:\n    event_id: str\n    event_type: str\n    aggregate_id: str\n    occurred_at: datetime\n    data: dict\n\nclass EventBus:\n    \"\"\"Event publishing and subscription.\"\"\"\n\n    def __init__(self, bootstrap_servers: List[str]):\n        self.bootstrap_servers = bootstrap_servers\n        self.producer = None\n\n    async def start(self):\n        self.producer = AIOKafkaProducer(\n            bootstrap_servers=self.bootstrap_servers,\n            value_serializer=lambda v: json.dumps(v).encode()\n        )\n        await self.producer.start()\n\n    async def publish(self, event: DomainEvent):\n        \"\"\"Publish event to Kafka topic.\"\"\"\n        topic = event.event_type\n        await self.producer.send_and_wait(\n            topic,\n            value=asdict(event),\n            key=event.aggregate_id.encode()\n        )\n\n    async def subscribe(self, topic: str, handler: callable):\n        \"\"\"Subscribe to events.\"\"\"\n        consumer = AIOKafkaConsumer(\n            topic,\n            bootstrap_servers=self.bootstrap_servers,\n            value_deserializer=lambda v: json.loads(v.decode()),\n            group_id=\"my-service\"\n        )\n        await consumer.start()\n\n        try:\n            async for message in consumer:\n                event_data = message.value\n                await handler(event_data)\n        finally:\n            await consumer.stop()\n\n# Order Service publishes event\nasync def create_order(order_data: dict):\n    order = await save_order(order_data)\n\n    event = DomainEvent(\n        event_id=str(uuid.uuid4()),\n        event_type=\"OrderCreated\",\n        aggregate_id=order.id,\n        occurred_at=datetime.now(),\n        data={\n            \"order_id\": order.id,\n            \"customer_id\": order.customer_id,\n            \"total\": order.total\n        }\n    )\n\n    await event_bus.publish(event)\n\n# Inventory Service listens for OrderCreated\nasync def handle_order_created(event_data: dict):\n    \"\"\"React to order creation.\"\"\"\n    order_id = event_data[\"data\"][\"order_id\"]\n    items = event_data[\"data\"][\"items\"]\n\n    # Reserve inventory\n    await reserve_inventory(order_id, items)\n```\n\n### Pattern 3: Saga Pattern (Distributed Transactions)\n\n```python\n# Saga orchestration for order fulfillment\nfrom enum import Enum\nfrom typing import List, Callable\n\nclass SagaStep:\n    \"\"\"Single step in saga.\"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        action: Callable,\n        compensation: Callable\n    ):\n        self.name = name\n        self.action = action\n        self.compensation = compensation\n\nclass SagaStatus(Enum):\n    PENDING = \"pending\"\n    COMPLETED = \"completed\"\n    COMPENSATING = \"compensating\"\n    FAILED = \"failed\"\n\nclass OrderFulfillmentSaga:\n    \"\"\"Orchestrated saga for order fulfillment.\"\"\"\n\n    def __init__(self):\n        self.steps: List[SagaStep] = [\n            SagaStep(\n                \"create_order\",\n                action=self.create_order,\n                compensation=self.cancel_order\n            ),\n            SagaStep(\n                \"reserve_inventory\",\n                action=self.reserve_inventory,\n                compensation=self.release_inventory\n            ),\n            SagaStep(\n                \"process_payment\",\n                action=self.process_payment,\n                compensation=self.refund_payment\n            ),\n            SagaStep(\n                \"confirm_order\",\n                action=self.confirm_order,\n                compensation=self.cancel_order_confirmation\n            )\n        ]\n\n    async def execute(self, order_data: dict) -> SagaResult:\n        \"\"\"Execute saga steps.\"\"\"\n        completed_steps = []\n        context = {\"order_data\": order_data}\n\n        try:\n            for step in self.steps:\n                # Execute step\n                result = await step.action(context)\n                if not result.success:\n                    # Compensate\n                    await self.compensate(completed_steps, context)\n                    return SagaResult(\n                        status=SagaStatus.FAILED,\n                        error=result.error\n                    )\n\n                completed_steps.append(step)\n                context.update(result.data)\n\n            return SagaResult(status=SagaStatus.COMPLETED, data=context)\n\n        except Exception as e:\n            # Compensate on error\n            await self.compensate(completed_steps, context)\n            return SagaResult(status=SagaStatus.FAILED, error=str(e))\n\n    async def compensate(self, completed_steps: List[SagaStep], context: dict):\n        \"\"\"Execute compensating actions in reverse order.\"\"\"\n        for step in reversed(completed_steps):\n            try:\n                await step.compensation(context)\n            except Exception as e:\n                # Log compensation failure\n                print(f\"Compensation failed for {step.name}: {e}\")\n\n    # Step implementations\n    async def create_order(self, context: dict) -> StepResult:\n        order = await order_service.create(context[\"order_data\"])\n        return StepResult(success=True, data={\"order_id\": order.id})\n\n    async def cancel_order(self, context: dict):\n        await order_service.cancel(context[\"order_id\"])\n\n    async def reserve_inventory(self, context: dict) -> StepResult:\n        result = await inventory_service.reserve(\n            context[\"order_id\"],\n            context[\"order_data\"][\"items\"]\n        )\n        return StepResult(\n            success=result.success,\n            data={\"reservation_id\": result.reservation_id}\n        )\n\n    async def release_inventory(self, context: dict):\n        await inventory_service.release(context[\"reservation_id\"])\n\n    async def process_payment(self, context: dict) -> StepResult:\n        result = await payment_service.charge(\n            context[\"order_id\"],\n            context[\"order_data\"][\"total\"]\n        )\n        return StepResult(\n            success=result.success,\n            data={\"transaction_id\": result.transaction_id},\n            error=result.error\n        )\n\n    async def refund_payment(self, context: dict):\n        await payment_service.refund(context[\"transaction_id\"])\n```\n\n## Resilience Patterns\n\n### Circuit Breaker Pattern\n\n```python\nfrom enum import Enum\nfrom datetime import datetime, timedelta\nfrom typing import Callable, Any\n\nclass CircuitState(Enum):\n    CLOSED = \"closed\"  # Normal operation\n    OPEN = \"open\"      # Failing, reject requests\n    HALF_OPEN = \"half_open\"  # Testing if recovered\n\nclass CircuitBreaker:\n    \"\"\"Circuit breaker for service calls.\"\"\"\n\n    def __init__(\n        self,\n        failure_threshold: int = 5,\n        recovery_timeout: int = 30,\n        success_threshold: int = 2\n    ):\n        self.failure_threshold = failure_threshold\n        self.recovery_timeout = recovery_timeout\n        self.success_threshold = success_threshold\n\n        self.failure_count = 0\n        self.success_count = 0\n        self.state = CircuitState.CLOSED\n        self.opened_at = None\n\n    async def call(self, func: Callable, *args, **kwargs) -> Any:\n        \"\"\"Execute function with circuit breaker.\"\"\"\n\n        if self.state == CircuitState.OPEN:\n            if self._should_attempt_reset():\n                self.state = CircuitState.HALF_OPEN\n            else:\n                raise CircuitBreakerOpenError(\"Circuit breaker is open\")\n\n        try:\n            result = await func(*args, **kwargs)\n            self._on_success()\n            return result\n\n        except Exception as e:\n            self._on_failure()\n            raise\n\n    def _on_success(self):\n        \"\"\"Handle successful call.\"\"\"\n        self.failure_count = 0\n\n        if self.state == CircuitState.HALF_OPEN:\n            self.success_count += 1\n            if self.success_count >= self.success_threshold:\n                self.state = CircuitState.CLOSED\n                self.success_count = 0\n\n    def _on_failure(self):\n        \"\"\"Handle failed call.\"\"\"\n        self.failure_count += 1\n\n        if self.failure_count >= self.failure_threshold:\n            self.state = CircuitState.OPEN\n            self.opened_at = datetime.now()\n\n        if self.state == CircuitState.HALF_OPEN:\n            self.state = CircuitState.OPEN\n            self.opened_at = datetime.now()\n\n    def _should_attempt_reset(self) -> bool:\n        \"\"\"Check if enough time passed to try again.\"\"\"\n        return (\n            datetime.now() - self.opened_at\n            > timedelta(seconds=self.recovery_timeout)\n        )\n\n# Usage\nbreaker = CircuitBreaker(failure_threshold=5, recovery_timeout=30)\n\nasync def call_payment_service(payment_data: dict):\n    return await breaker.call(\n        payment_client.process_payment,\n        payment_data\n    )\n```\n\n## Resources\n\n- **references\u002Fservice-decomposition-guide.md**: Breaking down monoliths\n- **references\u002Fcommunication-patterns.md**: Sync vs async patterns\n- **references\u002Fsaga-implementation.md**: Distributed transactions\n- **assets\u002Fcircuit-breaker.py**: Production circuit breaker\n- **assets\u002Fevent-bus-template.py**: Kafka event bus implementation\n- **assets\u002Fapi-gateway-template.py**: Complete API gateway\n\n## Best Practices\n\n1. **Service Boundaries**: Align with business capabilities\n2. **Database Per Service**: No shared databases\n3. **API Contracts**: Versioned, backward compatible\n4. **Async When Possible**: Events over direct calls\n5. **Circuit Breakers**: Fail fast on service failures\n6. **Distributed Tracing**: Track requests across services\n7. **Service Registry**: Dynamic service discovery\n8. **Health Checks**: Liveness and readiness probes\n\n## Common Pitfalls\n\n- **Distributed Monolith**: Tightly coupled services\n- **Chatty Services**: Too many inter-service calls\n- **Shared Databases**: Tight coupling through data\n- **No Circuit Breakers**: Cascade failures\n- **Synchronous Everything**: Tight coupling, poor resilience\n- **Premature Microservices**: Starting with microservices\n- **Ignoring Network Failures**: Assuming reliable network\n- **No Compensation Logic**: Can't undo failed transactions\n","# Microservices Patterns\n\nMaster microservices architecture patterns including service boundaries, inter-service communication, data management, and resilience patterns for building distributed systems.\n\n## When to Use This Skill\n\n- Decomposing monoliths into microservices\n- Designing service boundaries and contracts\n- Implementing inter-service communication\n- Managing distributed data and transactions\n- Building resilient distributed systems\n- Implementing service discovery and load balancing\n- Designing event-driven architectures\n\n## Core Concepts\n\n### 1. Service Decomposition Strategies\n\n**By Business Capability**\n\n- Organize services around business functions\n- Each service owns its domain\n- Example: OrderService, PaymentService, InventoryService\n\n**By Subdomain (DDD)**\n\n- Core domain, supporting subdomains\n- Bounded contexts map to services\n- Clear ownership and responsibility\n\n**Strangler Fig Pattern**\n\n- Gradually extract from monolith\n- New functionality as microservices\n- Proxy routes to old\u002Fnew systems\n\n### 2. Communication Patterns\n\n**Synchronous (Request\u002FResponse)**\n\n- REST APIs\n- gRPC\n- GraphQL\n\n**Asynchronous (Events\u002FMessages)**\n\n- Event streaming (Kafka)\n- Message queues (RabbitMQ, SQS)\n- Pub\u002FSub patterns\n\n### 3. Data Management\n\n**Database Per Service**\n\n- Each service owns its data\n- No shared databases\n- Loose coupling\n\n**Saga Pattern**\n\n- Distributed transactions\n- Compensating actions\n- Eventual consistency\n\n### 4. Resilience Patterns\n\n**Circuit Breaker**\n\n- Fail fast on repeated errors\n- Prevent cascade failures\n\n**Retry with Backoff**\n\n- Transient fault handling\n- Exponential backoff\n\n**Bulkhead**\n\n- Isolate resources\n- Limit impact of failures\n\n## Service Decomposition Patterns\n\n### Pattern 1: By Business Capability\n\n```python\n# E-commerce example\n\n# Order Service\nclass OrderService:\n    \"\"\"Handles order lifecycle.\"\"\"\n\n    async def create_order(self, order_data: dict) -> Order:\n        order = Order.create(order_data)\n\n        # Publish event for other services\n        await self.event_bus.publish(\n            OrderCreatedEvent(\n                order_id=order.id,\n                customer_id=order.customer_id,\n                items=order.items,\n                total=order.total\n            )\n        )\n\n        return order\n\n# Payment Service (separate service)\nclass PaymentService:\n    \"\"\"Handles payment processing.\"\"\"\n\n    async def process_payment(self, payment_request: PaymentRequest) -> PaymentResult:\n        # Process payment\n        result = await self.payment_gateway.charge(\n            amount=payment_request.amount,\n            customer=payment_request.customer_id\n        )\n\n        if result.success:\n            await self.event_bus.publish(\n                PaymentCompletedEvent(\n                    order_id=payment_request.order_id,\n                    transaction_id=result.transaction_id\n                )\n            )\n\n        return result\n\n# Inventory Service (separate service)\nclass InventoryService:\n    \"\"\"Handles inventory management.\"\"\"\n\n    async def reserve_items(self, order_id: str, items: List[OrderItem]) -> ReservationResult:\n        # Check availability\n        for item in items:\n            available = await self.inventory_repo.get_available(item.product_id)\n            if available \u003C item.quantity:\n                return ReservationResult(\n                    success=False,\n                    error=f\"Insufficient inventory for {item.product_id}\"\n                )\n\n        # Reserve items\n        reservation = await self.create_reservation(order_id, items)\n\n        await self.event_bus.publish(\n            InventoryReservedEvent(\n                order_id=order_id,\n                reservation_id=reservation.id\n            )\n        )\n\n        return ReservationResult(success=True, reservation=reservation)\n```\n\n### Pattern 2: API Gateway\n\n```python\nfrom fastapi import FastAPI, HTTPException, Depends\nimport httpx\nfrom circuitbreaker import circuit\n\napp = FastAPI()\n\nclass APIGateway:\n    \"\"\"Central entry point for all client requests.\"\"\"\n\n    def __init__(self):\n        self.order_service_url = \"http:\u002F\u002Forder-service:8000\"\n        self.payment_service_url = \"http:\u002F\u002Fpayment-service:8001\"\n        self.inventory_service_url = \"http:\u002F\u002Finventory-service:8002\"\n        self.http_client = httpx.AsyncClient(timeout=5.0)\n\n    @circuit(failure_threshold=5, recovery_timeout=30)\n    async def call_order_service(self, path: str, method: str = \"GET\", **kwargs):\n        \"\"\"Call order service with circuit breaker.\"\"\"\n        response = await self.http_client.request(\n            method,\n            f\"{self.order_service_url}{path}\",\n            **kwargs\n        )\n        response.raise_for_status()\n        return response.json()\n\n    async def create_order_aggregate(self, order_id: str) -> dict:\n        \"\"\"Aggregate data from multiple services.\"\"\"\n        # Parallel requests\n        order, payment, inventory = await asyncio.gather(\n            self.call_order_service(f\"\u002Forders\u002F{order_id}\"),\n            self.call_payment_service(f\"\u002Fpayments\u002Forder\u002F{order_id}\"),\n            self.call_inventory_service(f\"\u002Freservations\u002Forder\u002F{order_id}\"),\n            return_exceptions=True\n        )\n\n        # Handle partial failures\n        result = {\"order\": order}\n        if not isinstance(payment, Exception):\n            result[\"payment\"] = payment\n        if not isinstance(inventory, Exception):\n            result[\"inventory\"] = inventory\n\n        return result\n\n@app.post(\"\u002Fapi\u002Forders\")\nasync def create_order(\n    order_data: dict,\n    gateway: APIGateway = Depends()\n):\n    \"\"\"API Gateway endpoint.\"\"\"\n    try:\n        # Route to order service\n        order = await gateway.call_order_service(\n            \"\u002Forders\",\n            method=\"POST\",\n            json=order_data\n        )\n        return {\"order\": order}\n    except httpx.HTTPError as e:\n        raise HTTPException(status_code=503, detail=\"Order service unavailable\")\n```\n\n## Communication Patterns\n\n### Pattern 1: Synchronous REST Communication\n\n```python\n# Service A calls Service B\nimport httpx\nfrom tenacity import retry, stop_after_attempt, wait_exponential\n\nclass ServiceClient:\n    \"\"\"HTTP client with retries and timeout.\"\"\"\n\n    def __init__(self, base_url: str):\n        self.base_url = base_url\n        self.client = httpx.AsyncClient(\n            timeout=httpx.Timeout(5.0, connect=2.0),\n            limits=httpx.Limits(max_keepalive_connections=20)\n        )\n\n    @retry(\n        stop=stop_after_attempt(3),\n        wait=wait_exponential(multiplier=1, min=2, max=10)\n    )\n    async def get(self, path: str, **kwargs):\n        \"\"\"GET with automatic retries.\"\"\"\n        response = await self.client.get(f\"{self.base_url}{path}\", **kwargs)\n        response.raise_for_status()\n        return response.json()\n\n    async def post(self, path: str, **kwargs):\n        \"\"\"POST request.\"\"\"\n        response = await self.client.post(f\"{self.base_url}{path}\", **kwargs)\n        response.raise_for_status()\n        return response.json()\n\n# Usage\npayment_client = ServiceClient(\"http:\u002F\u002Fpayment-service:8001\")\nresult = await payment_client.post(\"\u002Fpayments\", json=payment_data)\n```\n\n### Pattern 2: Asynchronous Event-Driven\n\n```python\n# Event-driven communication with Kafka\nfrom aiokafka import AIOKafkaProducer, AIOKafkaConsumer\nimport json\nfrom dataclasses import dataclass, asdict\nfrom datetime import datetime\n\n@dataclass\nclass DomainEvent:\n    event_id: str\n    event_type: str\n    aggregate_id: str\n    occurred_at: datetime\n    data: dict\n\nclass EventBus:\n    \"\"\"Event publishing and subscription.\"\"\"\n\n    def __init__(self, bootstrap_servers: List[str]):\n        self.bootstrap_servers = bootstrap_servers\n        self.producer = None\n\n    async def start(self):\n        self.producer = AIOKafkaProducer(\n            bootstrap_servers=self.bootstrap_servers,\n            value_serializer=lambda v: json.dumps(v).encode()\n        )\n        await self.producer.start()\n\n    async def publish(self, event: DomainEvent):\n        \"\"\"Publish event to Kafka topic.\"\"\"\n        topic = event.event_type\n        await self.producer.send_and_wait(\n            topic,\n            value=asdict(event),\n            key=event.aggregate_id.encode()\n        )\n\n    async def subscribe(self, topic: str, handler: callable):\n        \"\"\"Subscribe to events.\"\"\"\n        consumer = AIOKafkaConsumer(\n            topic,\n            bootstrap_servers=self.bootstrap_servers,\n            value_deserializer=lambda v: json.loads(v.decode()),\n            group_id=\"my-service\"\n        )\n        await consumer.start()\n\n        try:\n            async for message in consumer:\n                event_data = message.value\n                await handler(event_data)\n        finally:\n            await consumer.stop()\n\n# Order Service publishes event\nasync def create_order(order_data: dict):\n    order = await save_order(order_data)\n\n    event = DomainEvent(\n        event_id=str(uuid.uuid4()),\n        event_type=\"OrderCreated\",\n        aggregate_id=order.id,\n        occurred_at=datetime.now(),\n        data={\n            \"order_id\": order.id,\n            \"customer_id\": order.customer_id,\n            \"total\": order.total\n        }\n    )\n\n    await event_bus.publish(event)\n\n# Inventory Service listens for OrderCreated\nasync def handle_order_created(event_data: dict):\n    \"\"\"React to order creation.\"\"\"\n    order_id = event_data[\"data\"][\"order_id\"]\n    items = event_data[\"data\"][\"items\"]\n\n    # Reserve inventory\n    await reserve_inventory(order_id, items)\n```\n\n### Pattern 3: Saga Pattern (Distributed Transactions)\n\n```python\n# Saga orchestration for order fulfillment\nfrom enum import Enum\nfrom typing import List, Callable\n\nclass SagaStep:\n    \"\"\"Single step in saga.\"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        action: Callable,\n        compensation: Callable\n    ):\n        self.name = name\n        self.action = action\n        self.compensation = compensation\n\nclass SagaStatus(Enum):\n    PENDING = \"pending\"\n    COMPLETED = \"completed\"\n    COMPENSATING = \"compensating\"\n    FAILED = \"failed\"\n\nclass OrderFulfillmentSaga:\n    \"\"\"Orchestrated saga for order fulfillment.\"\"\"\n\n    def __init__(self):\n        self.steps: List[SagaStep] = [\n            SagaStep(\n                \"create_order\",\n                action=self.create_order,\n                compensation=self.cancel_order\n            ),\n            SagaStep(\n                \"reserve_inventory\",\n                action=self.reserve_inventory,\n                compensation=self.release_inventory\n            ),\n            SagaStep(\n                \"process_payment\",\n                action=self.process_payment,\n                compensation=self.refund_payment\n            ),\n            SagaStep(\n                \"confirm_order\",\n                action=self.confirm_order,\n                compensation=self.cancel_order_confirmation\n            )\n        ]\n\n    async def execute(self, order_data: dict) -> SagaResult:\n        \"\"\"Execute saga steps.\"\"\"\n        completed_steps = []\n        context = {\"order_data\": order_data}\n\n        try:\n            for step in self.steps:\n                # Execute step\n                result = await step.action(context)\n                if not result.success:\n                    # Compensate\n                    await self.compensate(completed_steps, context)\n                    return SagaResult(\n                        status=SagaStatus.FAILED,\n                        error=result.error\n                    )\n\n                completed_steps.append(step)\n                context.update(result.data)\n\n            return SagaResult(status=SagaStatus.COMPLETED, data=context)\n\n        except Exception as e:\n            # Compensate on error\n            await self.compensate(completed_steps, context)\n            return SagaResult(status=SagaStatus.FAILED, error=str(e))\n\n    async def compensate(self, completed_steps: List[SagaStep], context: dict):\n        \"\"\"Execute compensating actions in reverse order.\"\"\"\n        for step in reversed(completed_steps):\n            try:\n                await step.compensation(context)\n            except Exception as e:\n                # Log compensation failure\n                print(f\"Compensation failed for {step.name}: {e}\")\n\n    # Step implementations\n    async def create_order(self, context: dict) -> StepResult:\n        order = await order_service.create(context[\"order_data\"])\n        return StepResult(success=True, data={\"order_id\": order.id})\n\n    async def cancel_order(self, context: dict):\n        await order_service.cancel(context[\"order_id\"])\n\n    async def reserve_inventory(self, context: dict) -> StepResult:\n        result = await inventory_service.reserve(\n            context[\"order_id\"],\n            context[\"order_data\"][\"items\"]\n        )\n        return StepResult(\n            success=result.success,\n            data={\"reservation_id\": result.reservation_id}\n        )\n\n    async def release_inventory(self, context: dict):\n        await inventory_service.release(context[\"reservation_id\"])\n\n    async def process_payment(self, context: dict) -> StepResult:\n        result = await payment_service.charge(\n            context[\"order_id\"],\n            context[\"order_data\"][\"total\"]\n        )\n        return StepResult(\n            success=result.success,\n            data={\"transaction_id\": result.transaction_id},\n            error=result.error\n        )\n\n    async def refund_payment(self, context: dict):\n        await payment_service.refund(context[\"transaction_id\"])\n```\n\n## Resilience Patterns\n\n### Circuit Breaker Pattern\n\n```python\nfrom enum import Enum\nfrom datetime import datetime, timedelta\nfrom typing import Callable, Any\n\nclass CircuitState(Enum):\n    CLOSED = \"closed\"  # Normal operation\n    OPEN = \"open\"      # Failing, reject requests\n    HALF_OPEN = \"half_open\"  # Testing if recovered\n\nclass CircuitBreaker:\n    \"\"\"Circuit breaker for service calls.\"\"\"\n\n    def __init__(\n        self,\n        failure_threshold: int = 5,\n        recovery_timeout: int = 30,\n        success_threshold: int = 2\n    ):\n        self.failure_threshold = failure_threshold\n        self.recovery_timeout = recovery_timeout\n        self.success_threshold = success_threshold\n\n        self.failure_count = 0\n        self.success_count = 0\n        self.state = CircuitState.CLOSED\n        self.opened_at = None\n\n    async def call(self, func: Callable, *args, **kwargs) -> Any:\n        \"\"\"Execute function with circuit breaker.\"\"\"\n\n        if self.state == CircuitState.OPEN:\n            if self._should_attempt_reset():\n                self.state = CircuitState.HALF_OPEN\n            else:\n                raise CircuitBreakerOpenError(\"Circuit breaker is open\")\n\n        try:\n            result = await func(*args, **kwargs)\n            self._on_success()\n            return result\n\n        except Exception as e:\n            self._on_failure()\n            raise\n\n    def _on_success(self):\n        \"\"\"Handle successful call.\"\"\"\n        self.failure_count = 0\n\n        if self.state == CircuitState.HALF_OPEN:\n            self.success_count += 1\n            if self.success_count >= self.success_threshold:\n                self.state = CircuitState.CLOSED\n                self.success_count = 0\n\n    def _on_failure(self):\n        \"\"\"Handle failed call.\"\"\"\n        self.failure_count += 1\n\n        if self.failure_count >= self.failure_threshold:\n            self.state = CircuitState.OPEN\n            self.opened_at = datetime.now()\n\n        if self.state == CircuitState.HALF_OPEN:\n            self.state = CircuitState.OPEN\n            self.opened_at = datetime.now()\n\n    def _should_attempt_reset(self) -> bool:\n        \"\"\"Check if enough time passed to try again.\"\"\"\n        return (\n            datetime.now() - self.opened_at\n            > timedelta(seconds=self.recovery_timeout)\n        )\n\n# Usage\nbreaker = CircuitBreaker(failure_threshold=5, recovery_timeout=30)\n\nasync def call_payment_service(payment_data: dict):\n    return await breaker.call(\n        payment_client.process_payment,\n        payment_data\n    )\n```\n\n## Resources\n\n- **references\u002Fservice-decomposition-guide.md**: Breaking down monoliths\n- **references\u002Fcommunication-patterns.md**: Sync vs async patterns\n- **references\u002Fsaga-implementation.md**: Distributed transactions\n- **assets\u002Fcircuit-breaker.py**: Production circuit breaker\n- **assets\u002Fevent-bus-template.py**: Kafka event bus implementation\n- **assets\u002Fapi-gateway-template.py**: Complete API gateway\n\n## Best Practices\n\n1. **Service Boundaries**: Align with business capabilities\n2. **Database Per Service**: No shared databases\n3. **API Contracts**: Versioned, backward compatible\n4. **Async When Possible**: Events over direct calls\n5. **Circuit Breakers**: Fail fast on service failures\n6. **Distributed Tracing**: Track requests across services\n7. **Service Registry**: Dynamic service discovery\n8. **Health Checks**: Liveness and readiness probes\n\n## Common Pitfalls\n\n- **Distributed Monolith**: Tightly coupled services\n- **Chatty Services**: Too many inter-service calls\n- **Shared Databases**: Tight coupling through data\n- **No Circuit Breakers**: Cascade failures\n- **Synchronous Everything**: Tight coupling, poor resilience\n- **Premature Microservices**: Starting with microservices\n- **Ignoring Network Failures**: Assuming reliable network\n- **No Compensation Logic**: Can't undo failed transactions\n",{"name":5,"description":7},"main","18d0e63d1313ca87098f614aa7c1e2dcf6de79c7","backend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Fbackend-development\u002Fskills\u002Fmicroservices-patterns",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":51,"prompt":61,"zipAvailable":62},[52,55,58],{"tool":53,"command":54},"npx","npx skills add welflau\u002Fai-dev-system --skill microservices-patterns",{"tool":56,"command":57},"bunx","bunx skills add welflau\u002Fai-dev-system --skill microservices-patterns",{"tool":59,"command":60},"pnpm","pnpm dlx skills add welflau\u002Fai-dev-system --skill microservices-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fwelflau\u002Fai-dev-system\u002Fblob\u002Fmain\u002Fbackend\u002Fskills\u002Fmarketplace\u002Fcodebuddy-plugins-official\u002Fexternal_plugins\u002Fbackend-development\u002Fskills\u002Fmicroservices-patterns\u002FSKILL.md",true,[],[65,91,117,142,161,184],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":69,"licenseFileUrl":70,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":90},"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",[],[74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,26,89],"testing","webapp testing","webapp","frontend","screenshots","playwright","web","debugging","toolkit","browser","ui","logs","applications","behavior","local","for","2026-11-11 15:11:14",{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":69,"licenseFileUrl":95,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":90},"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",[],[99,100,101,102,103,104,34,105,106,107,108,109,110,111,112,113,114,115,116],"internal comms","comms","status","help","SET","write","reports","me","incident","leadership","project","resources","communications","internal communications","formats","sort","my","updates",{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":69,"licenseFileUrl":121,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":38},"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",[],[125,80,126,127,128,77,129,130,131,132,133,134,135,136,34,137,138,139,140,89,141],"web artifacts builder","artifacts","artifacts builder","builder","css","components","react","routing","state management","state","file","Tailwind","single-file","simple","ui components","multi","single",{"skillNo":143,"name":144,"nameZh":6,"description":145,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":69,"licenseFileUrl":146,"sourceHtmlUrl":147,"categories":148,"keywords":149,"publishedAt":38},"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",[],[77,31,150,129,80,130,131,151,152,153,126,154,86,155,34,156,157,158,159,26,160,22],"frontend design","react components","create","code","examples","landing","ui design","pages","aesthetics","web ui","generic",{"skillNo":162,"name":163,"nameZh":6,"description":164,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":69,"licenseFileUrl":165,"sourceHtmlUrl":166,"categories":167,"keywords":168,"publishedAt":38},"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",[],[169,170,171,152,153,172,173,174,175,34,176,177,21,178,26,179,180,181,182,183,22],"algorithmic art","Art","algorithmic","flow","js","work","interactive","generative art","exploration","users","Existing","request","generative","copyright","fields",{"skillNo":185,"name":186,"nameZh":6,"description":187,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":69,"licenseFileUrl":188,"sourceHtmlUrl":189,"categories":190,"keywords":191,"publishedAt":38},"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",[],[192,193,194,195,82,196,126,103,197,198,155,199,200,157,201,26,202,203,204,89,205,206],"theme factory","factory","theme","docs","generate","fly","slides","styling","artifact","themes","you","fonts","can","apply","new"]