MCP HubMCP Hub
返回技能列表

microservices-patterns

lifangda
更新于 Today
45 次查看
11
11
在 GitHub 上查看
design

关于

This Claude Skill helps developers design microservices architectures by providing patterns for service boundaries, event-driven communication, and resilience. It's useful for building distributed systems, decomposing monoliths, and implementing microservices. The skill covers core concepts like service decomposition, inter-service communication, and distributed data management.

技能文档

Microservices Patterns

Master microservices architecture patterns including service boundaries, inter-service communication, data management, and resilience patterns for building distributed systems.

When to Use This Skill

  • Decomposing monoliths into microservices
  • Designing service boundaries and contracts
  • Implementing inter-service communication
  • Managing distributed data and transactions
  • Building resilient distributed systems
  • Implementing service discovery and load balancing
  • Designing event-driven architectures

Core Concepts

1. Service Decomposition Strategies

By Business Capability

  • Organize services around business functions
  • Each service owns its domain
  • Example: OrderService, PaymentService, InventoryService

By Subdomain (DDD)

  • Core domain, supporting subdomains
  • Bounded contexts map to services
  • Clear ownership and responsibility

Strangler Fig Pattern

  • Gradually extract from monolith
  • New functionality as microservices
  • Proxy routes to old/new systems

See detailed guide: Service Decomposition

2. Communication Patterns

Synchronous (Request/Response)

  • REST APIs
  • gRPC
  • GraphQL

Asynchronous (Events/Messages)

  • Event streaming (Kafka)
  • Message queues (RabbitMQ, SQS)
  • Pub/Sub patterns

See detailed patterns: Communication Patterns

3. Data Management

Database Per Service

  • Each service owns its data
  • No shared databases
  • Loose coupling

Saga Pattern

  • Distributed transactions
  • Compensating actions
  • Eventual consistency

See detailed patterns: Data Management

4. Resilience Patterns

Circuit Breaker

  • Fail fast on repeated errors
  • Prevent cascade failures

Retry with Backoff

  • Transient fault handling
  • Exponential backoff

Bulkhead

  • Isolate resources
  • Limit impact of failures

See detailed implementations: Resilience Patterns

Quick Start

Basic Service Structure

from fastapi import FastAPI

app = FastAPI()

class OrderService:
    """Handles order lifecycle."""

    async def create_order(self, order_data: dict) -> Order:
        order = Order.create(order_data)

        # Publish event for other services
        await self.event_bus.publish(
            OrderCreatedEvent(
                order_id=order.id,
                customer_id=order.customer_id,
                items=order.items,
                total=order.total
            )
        )

        return order

@app.post("/orders")
async def create_order(order_data: dict):
    service = OrderService()
    return await service.create_order(order_data)

API Gateway Pattern

class APIGateway:
    """Central entry point for all client requests."""

    async def call_order_service(self, path: str, method: str = "GET", **kwargs):
        response = await self.http_client.request(
            method,
            f"{self.order_service_url}{path}",
            **kwargs
        )
        return response.json()

    async def create_order_aggregate(self, order_id: str) -> dict:
        """Aggregate data from multiple services."""
        order, payment, inventory = await asyncio.gather(
            self.call_order_service(f"/orders/{order_id}"),
            self.call_payment_service(f"/payments/order/{order_id}"),
            self.call_inventory_service(f"/reservations/order/{order_id}"),
            return_exceptions=True
        )

        return {"order": order, "payment": payment, "inventory": inventory}

See detailed patterns: API Gateway

Service Decomposition Patterns

Break monoliths into microservices using business capabilities and DDD principles.

See detailed guide: Service Decomposition

Communication Patterns

Synchronous Communication

REST APIs with retry logic and timeouts.

from tenacity import retry, stop_after_attempt, wait_exponential

class ServiceClient:
    @retry(
        stop=stop_after_attempt(3),
        wait=wait_exponential(multiplier=1, min=2, max=10)
    )
    async def get(self, path: str, **kwargs):
        response = await self.client.get(f"{self.base_url}{path}", **kwargs)
        response.raise_for_status()
        return response.json()

See detailed patterns: Communication Patterns

Asynchronous Event-Driven

Event bus with Kafka for decoupled communication.

async def publish_event(event: DomainEvent):
    await event_bus.publish(event)

async def subscribe_to_events(topic: str, handler: callable):
    await event_bus.subscribe(topic, handler)

See detailed implementation: Event-Driven Architecture

Data Management Patterns

Saga Pattern

Manage distributed transactions with compensating actions.

class OrderFulfillmentSaga:
    """Orchestrated saga for order fulfillment."""

    async def execute(self, order_data: dict) -> SagaResult:
        try:
            for step in self.steps:
                result = await step.action(context)
                if not result.success:
                    await self.compensate(completed_steps, context)
                    return SagaResult(status=SagaStatus.FAILED)

                completed_steps.append(step)

            return SagaResult(status=SagaStatus.COMPLETED)
        except Exception:
            await self.compensate(completed_steps, context)

See detailed implementation: Saga Pattern

Resilience Patterns

Circuit Breaker

Prevent cascade failures by failing fast.

class CircuitBreaker:
    async def call(self, func: Callable, *args, **kwargs) -> Any:
        if self.state == CircuitState.OPEN:
            raise CircuitBreakerOpenError("Circuit breaker is open")

        try:
            result = await func(*args, **kwargs)
            self._on_success()
            return result
        except Exception:
            self._on_failure()
            raise

See detailed implementations: Resilience Patterns

Best Practices

  1. Service Boundaries: Align with business capabilities
  2. Database Per Service: No shared databases
  3. API Contracts: Versioned, backward compatible
  4. Async When Possible: Events over direct calls
  5. Circuit Breakers: Fail fast on service failures
  6. Distributed Tracing: Track requests across services
  7. Service Registry: Dynamic service discovery
  8. Health Checks: Liveness and readiness probes

See detailed guide: Best Practices

Common Pitfalls

  • Distributed Monolith: Tightly coupled services
  • Chatty Services: Too many inter-service calls
  • Shared Databases: Tight coupling through data
  • No Circuit Breakers: Cascade failures
  • Synchronous Everything: Tight coupling, poor resilience
  • Premature Microservices: Starting with microservices
  • Ignoring Network Failures: Assuming reliable network
  • No Compensation Logic: Can't undo failed transactions

See detailed solutions: Common Pitfalls

快速安装

/plugin add https://github.com/lifangda/claude-plugins/tree/main/microservices-patterns

在 Claude Code 中复制并粘贴此命令以安装该技能

GitHub 仓库

lifangda/claude-plugins
路径: cli-tool/skills-library/backend-development/microservices-patterns

相关推荐技能

langchain

LangChain是一个用于构建LLM应用程序的框架,支持智能体、链和RAG应用开发。它提供多模型提供商支持、500+工具集成、记忆管理和向量检索等核心功能。开发者可用它快速构建聊天机器人、问答系统和自主代理,适用于从原型验证到生产部署的全流程。

查看技能

project-structure

这个Skill为开发者提供全面的项目目录结构设计指南和最佳实践。它涵盖了多种项目类型包括monorepo、前后端框架、库和扩展的标准组织结构。帮助团队创建可扩展、易维护的代码架构,特别适用于新项目设计、遗留项目迁移和团队规范制定。

查看技能

issue-documentation

该Skill为开发者提供标准化的issue文档模板和指南,适用于创建bug报告、GitHub/Linear/Jira问题等场景。它能系统化地记录问题状况、复现步骤、根本原因、解决方案和影响范围,确保团队沟通清晰高效。通过实施主流问题跟踪系统的最佳实践,帮助开发者生成结构完整的故障排除文档和事件报告。

查看技能

llamaindex

LlamaIndex是一个专门构建RAG应用的开发框架,提供300多种数据连接器用于文档摄取、索引和查询。它具备向量索引、查询引擎和智能代理等核心功能,支持构建文档问答、知识检索和聊天机器人等数据密集型应用。开发者可用它快速搭建连接私有数据与LLM的RAG管道。

查看技能