[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M70NNTQMA9T5CD68Y1C0V5JM":3,"skill-same:01M70NNTQMA9T5CD68Y1C0V5JM":68},{"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":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":49,"ownerHtmlUrl":50,"ownerBlogUrl":51,"ownerDescription":52,"updatedAt":53,"install":54,"resources":67},"01M70NNTQMA9T5CD68Y1C0V5JM","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.","shengdabai\u002FTony-Claude-Code-Skills","shengdabai","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F116417419?v=4","01M70F6D2WY5PQV5A92BKYJQEW","Tony Sheng","01M70F6D3GAAAYZ5H4CC1G8VXM",3,"MIT","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fwshobson-agents\u002Fplugins\u002Fbackend-development\u002Fskills\u002Fmicroservices-patterns\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"microservices","microservices patterns","patterns","driven","service","systems","event-driven","with","distributed systems","distributed","use","event","architectures","communication","resilience","when","design","implementing","resilience patterns","design microservices","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- Organize services around business functions\n- Each service owns its domain\n- Example: OrderService, PaymentService, InventoryService\n\n**By Subdomain (DDD)**\n- Core domain, supporting subdomains\n- Bounded contexts map to services\n- Clear ownership and responsibility\n\n**Strangler Fig Pattern**\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- REST APIs\n- gRPC\n- GraphQL\n\n**Asynchronous (Events\u002FMessages)**\n- Event streaming (Kafka)\n- Message queues (RabbitMQ, SQS)\n- Pub\u002FSub patterns\n\n### 3. Data Management\n\n**Database Per Service**\n- Each service owns its data\n- No shared databases\n- Loose coupling\n\n**Saga Pattern**\n- Distributed transactions\n- Compensating actions\n- Eventual consistency\n\n### 4. Resilience Patterns\n\n**Circuit Breaker**\n- Fail fast on repeated errors\n- Prevent cascade failures\n\n**Retry with Backoff**\n- Transient fault handling\n- Exponential backoff\n\n**Bulkhead**\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- Organize services around business functions\n- Each service owns its domain\n- Example: OrderService, PaymentService, InventoryService\n\n**By Subdomain (DDD)**\n- Core domain, supporting subdomains\n- Bounded contexts map to services\n- Clear ownership and responsibility\n\n**Strangler Fig Pattern**\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- REST APIs\n- gRPC\n- GraphQL\n\n**Asynchronous (Events\u002FMessages)**\n- Event streaming (Kafka)\n- Message queues (RabbitMQ, SQS)\n- Pub\u002FSub patterns\n\n### 3. Data Management\n\n**Database Per Service**\n- Each service owns its data\n- No shared databases\n- Loose coupling\n\n**Saga Pattern**\n- Distributed transactions\n- Compensating actions\n- Eventual consistency\n\n### 4. Resilience Patterns\n\n**Circuit Breaker**\n- Fail fast on repeated errors\n- Prevent cascade failures\n\n**Retry with Backoff**\n- Transient fault handling\n- Exponential backoff\n\n**Bulkhead**\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","7850740bd837adb32f0a109ab2af82482196c6f2","skills\u002Fwshobson-agents\u002Fplugins\u002Fbackend-development\u002Fskills\u002Fmicroservices-patterns",1,"https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills","https:\u002F\u002Fzturnsgo.com","https:\u002F\u002Fgithub.com\u002Fshengdabai","https:\u002F\u002Fzturnsgo.com\u002F","AI × education creator — producer, not consumer. Taught 6,000+ learners; shipping learning tools & daily essays with Claude Code, practicing @xiaolai's way 🥋","2026-11-01 21:28:23",{"source":8,"skillName":5,"commands":55,"prompt":65,"zipAvailable":66},[56,59,62],{"tool":57,"command":58},"npx","npx skills add shengdabai\u002FTony-Claude-Code-Skills --skill microservices-patterns",{"tool":60,"command":61},"bunx","bunx skills add shengdabai\u002FTony-Claude-Code-Skills --skill microservices-patterns",{"tool":63,"command":64},"pnpm","pnpm dlx skills add shengdabai\u002FTony-Claude-Code-Skills --skill microservices-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fwshobson-agents\u002Fplugins\u002Fbackend-development\u002Fskills\u002Fmicroservices-patterns\u002FSKILL.md",true,[],[69,78,86,94,102,110],{"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":73,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":77},"01M73H7XKBHE1ETQDZT94MF9HH","seedance-prompt-en","Write effective prompts for Jimeng Seedance 2.0 multimodal AI video generation. Use when users want to create video prompts using text, images, videos, and audio inputs with the @ reference system. Covers camera movements, effects replication, video extension, editing, music beat-matching, e-commerce ads, short dramas, and educational content.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-prompt-en\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-prompt-en\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":82,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":77},"01M73GRE9998Q1DZWC71N41JWG","onepage-pdf","Convert an HTML page into a single continuous-page PDF (one tall page, no pagination breaks), preserving desktop layout, backgrounds and selectable text. Use when the user asks to turn an HTML file\u002Freport\u002Fproposal into a \"single-page PDF\", \"long PDF\", \"不分页 PDF\", \"单页 PDF\", \"长图式 PDF\", or complains that an HTML-to-PDF export breaks into pages or cuts content. Supports optional string redaction with leak verification.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fonepage-pdf\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fonepage-pdf\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":90,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":77},"01M73GQG1KZDADVPV3MHAT1J5A","native-feel-cross-platform-desktop","Use when the user is designing, prototyping, or rewriting a desktop app that must run on multiple OSes (macOS + Windows, optionally Linux) AND feel indistinguishable from a native app to its users — fast launch, native windowing, native input handling, native materials. Trigger words include \"cross-platform desktop\", \"Electron alternative\", \"Tauri vs native\", \"WebView wrapper\", \"near-native performance\", \"Raycast architecture\", \"WebKit\u002FWebView2 quirks\", \"WKWebView\", \"system tray app\", \"global hotkey app\", \"launcher app\". Do NOT trigger this skill for pure web apps, pure mobile apps, or for greenfield projects that have no native-feel requirement.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fnative-feel-cross-platform-desktop\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fnative-feel-cross-platform-desktop\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":98,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":77},"01M73G87PDNSMKG2FHWCYER6N8","gstack","Router for the gstack skill suite. (gstack)","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fgstack\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fgstack\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":106,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":77},"01M73G3EAQWKCM8DB8D0N0QSVG","fireworks-tech-graph","Use when the user wants to create any technical diagram - architecture, data flow, flowchart, sequence, agent\u002Fmemory, or concept map - and export as SVG+PNG. Trigger on: \"画图\" \"帮我画\" \"生成图\" \"做个图\" \"架构图\" \"流程图\" \"可视化一下\" \"出图\" \"generate diagram\" \"draw diagram\" \"visualize\" or any system\u002Fflow description the user wants illustrated.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ffireworks-tech-graph\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ffireworks-tech-graph\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":77},"01M73G086AXAH9DW1H5G5N3CPB","dbs-video-extract","接收抖音、小红书、微信视频号等短视频链接或分享文案，查询作品／账号数据并提取语音文字稿，按作者和标题归档为 Markdown。用户希望完整解析短视频、取得数据或文字稿时使用；运行前检查 TikHub 与轻抖使用凭证，缺少时用新手能理解的方式引导购买和安全配置。","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdbs-video-extract\u002FSKILL.md",[],[]]