[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6EAR2WV73XGKXWW44SEJNJG":3,"skill-same:01M6EAR2WV73XGKXWW44SEJNJG":60},{"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":32,"linkOnly":33,"markdownContent":34,"markdownBody":35,"frontMatter":36,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":42,"ownerHtmlUrl":43,"ownerBlogUrl":6,"ownerDescription":44,"updatedAt":45,"install":46,"resources":59},"01M6EAR2WV73XGKXWW44SEJNJG","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.","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FHarmeet10000\u002Fskills\u002Fmicroservices-patterns\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31],"microservices","microservices patterns","patterns","design","resilience","distributed","communication","use","distributed systems","service","systems","driven","architectures","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","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002FHarmeet10000\u002Fskills\u002Fmicroservices-patterns",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":47,"prompt":57,"zipAvailable":58},[48,51,54],{"tool":49,"command":50},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill microservices-patterns",{"tool":52,"command":53},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill microservices-patterns",{"tool":55,"command":56},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill microservices-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FHarmeet10000\u002Fskills\u002Fmicroservices-patterns\u002FSKILL.md",true,[],[61,75,85,94,100,107],{"skillNo":62,"name":63,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":71,"publishedAt":32},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[66],{"categoryNo":67,"categoryName":68,"taxonomyType":69,"taxonomyTypeDesc":70},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[72,73,74],"model","model hierarchy","model hierarchy skill",{"skillNo":76,"name":77,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":81,"publishedAt":32},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[80],{"categoryNo":67,"categoryName":68,"taxonomyType":69,"taxonomyTypeDesc":70},[82,83,84],"MCP","zoom","zoom mcp",{"skillNo":86,"name":87,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":32},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[91,92,93,83],"sdk","zoom apps sdk","apps",{"skillNo":95,"name":96,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":32},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[96],{"skillNo":101,"name":102,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":106,"publishedAt":32},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[105],{"categoryNo":67,"categoryName":68,"taxonomyType":69,"taxonomyTypeDesc":70},[102],{"skillNo":108,"name":109,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":32},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[109]]