[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6CD1DHCCJQ56G15EZTESMSQ":3,"skill-same:01M6CD1DHCCJQ56G15EZTESMSQ":71},{"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":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":6,"ownerHtmlUrl":50,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":51,"install":52,"resources":64},"01M6CD1DHCCJQ56G15EZTESMSQ","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.","cercova-studios\u002F10x-swe","cercova-studios","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F217108198?v=4","01M6CCYGHXTH80N3BXRW6KESTE","Cercova Studios","01M6CCYGPADH5MJDR0VNNR775C",1,"MIT","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\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 patterns","microservices","patterns","driven","service","systems","event-driven","with","distributed systems","when","implementing","event","resilience patterns","design microservices","architectures","distributed","use","design","communication","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.\ndisable-model-invocation: true\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## 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## 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,"disable-model-invocation":44},true,"main","224d7699a283a75bd3f75d4d8b03b15aca0ae309","plugins\u002F10x-swe\u002Fskills\u002Fmicroservices-patterns",0,"https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe","https:\u002F\u002Fgithub.com\u002Fcercova-studios","2026-11-12 07:39:44",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":44},[54,57,60],{"tool":55,"command":56},"npx","npx skills add cercova-studios\u002F10x-swe --skill microservices-patterns",{"tool":58,"command":59},"bunx","bunx skills add cercova-studios\u002F10x-swe --skill microservices-patterns",{"tool":61,"command":62},"pnpm","pnpm dlx skills add cercova-studios\u002F10x-swe --skill microservices-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Fmicroservices-patterns\u002FSKILL.md",[65],{"path":66,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":69,"sourceHtmlUrl":70},"agents\u002Fopenai.yaml","REFERENCE","参考文档",43,"https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Fmicroservices-patterns\u002Fagents\u002Fopenai.yaml",[72,112,147,167,186,198],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":76,"licenseFileUrl":77,"sourceHtmlUrl":78,"categories":79,"keywords":85,"publishedAt":39},"01M6CD3T6EQ9N5KPNXCM6ABHVA","turnstile-spin","Set up Cloudflare Turnstile end-to-end in a project. Scan the codebase, create the widget via the Cloudflare API, embed it where user requests need bot verification (form submissions, SPA actions, API endpoints, download links, comment or vote submissions, etc.), wire canonical server-side siteverify in the customer's existing backend, validate, and persist the skill. Load this when a user asks to add Turnstile, set up CAPTCHA, protect a form or endpoint from bots, or fix a Turnstile integration. Uses Cloudflare's documented Turnstile contract.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Fturnstile-spin\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Fturnstile-spin\u002FSKILL.md",[80],{"categoryNo":81,"categoryName":82,"taxonomyType":83,"taxonomyTypeDesc":84},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",[86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,28],"turnstile spin","SET","nextjs","actions","up","fix","cloudflare","bot","api","permissions","create","astro","server","verification","plugin","endpoints","customer","backend","sveltekit","integration","app","bots","spa","project","end","SWE",{"skillNo":113,"name":114,"nameZh":6,"description":115,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":76,"licenseFileUrl":116,"sourceHtmlUrl":117,"categories":118,"keywords":130,"publishedAt":39},"01M6CD0BJYRNV610HYYPX933RE","frontend-design","Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Ffrontend-design\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Ffrontend-design\u002FSKILL.md",[119,122,125],{"categoryNo":120,"categoryName":121,"taxonomyType":83,"taxonomyTypeDesc":84},"01JBSEEDCAT000000000000009","前端开发",{"categoryNo":123,"categoryName":124,"taxonomyType":83,"taxonomyTypeDesc":84},"01JBSEEDCAT000000000000015","视觉设计",{"categoryNo":126,"categoryName":127,"taxonomyType":128,"taxonomyTypeDesc":129},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[131,132,36,96,133,134,135,136,137,138,35,139,140,141,142,143,144,28,26,145,146],"frontend design","frontend","web","quality","applications","creative","web components","Production","code","components","user","generic","aesthetics","pages","high","build",{"skillNo":148,"name":149,"nameZh":6,"description":150,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":151,"categories":152,"keywords":153,"publishedAt":39},"01M6CD4QX8C4DST98AY21HEYCM","source-insights","Prepare inspected source evidence, preserve exact citations, and publish reviewed insights into an explicit local library.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002Fknowledge\u002Fskills\u002Fsource-insights\u002FSKILL.md",[],[154,155,156,157,158,159,160,161,162,163,164,165,166],"source insights","insights","source","publish","Citations","evidence","library","workflows","prepare","session","global","local","preserve",{"skillNo":168,"name":169,"nameZh":6,"description":170,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":171,"categories":172,"keywords":176,"publishedAt":39},"01M6CD4N1HVNC1EXPEBZT7YS31","skill-graph","Discover skills and workflows through independent lexical search, relationship paths and a terminal graph.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002Fknowledge\u002Fskills\u002Fskill-graph\u002FSKILL.md",[173],{"categoryNo":174,"categoryName":175,"taxonomyType":83,"taxonomyTypeDesc":84},"01JBSEEDCAT000000000000023","Skill与智能体开发",[177,178,100,161,179,180,181,164,182,183,184,111,185],"graph","skill graph","terminal","10x","search","discover skills","discover","paths","relationship",{"skillNo":187,"name":188,"nameZh":6,"description":189,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":190,"categories":191,"keywords":192,"publishedAt":39},"01M6CD4HQKXNZ57YEGD8QVK6Z6","session-search","Recall public session turns with exact provenance, bounded excerpts and independent piped exports.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002Fknowledge\u002Fskills\u002Fsession-search\u002FSKILL.md",[],[181,163,193,194,161,195,196,164,26,155,156,197],"session search","public","provenance","recall","bounded",{"skillNo":199,"name":200,"nameZh":6,"description":201,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":202,"categories":203,"keywords":210,"publishedAt":39},"01M6CD4ET7DVNBYPDAMAYMSK2T","newsletter","Produce a private local AI newsletter from bounded public research, with cited deep dives, HTML\u002FMarkdown output, Dagu scheduling and seven-day retention.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002Fknowledge\u002Fskills\u002Fnewsletter\u002FSKILL.md",[204,207],{"categoryNo":205,"categoryName":206,"taxonomyType":83,"taxonomyTypeDesc":84},"01JBSEEDCAT000000000000005","邮件与沟通",{"categoryNo":208,"categoryName":209,"taxonomyType":83,"taxonomyTypeDesc":84},"01JBSEEDCAT000000000000021","资料检索与研究",[200,211,212,213,214,194,161,215,216,217,218,164,26,219,220,165,197,221],"local ai","dagu","produce","research","markdown","scheduling","html","daily","deep","retention","output"]