distributed-patterns

Implementation guide and selection matrix for core distributed system patterns (Saga, CQRS, Circuit Breaker, Event Sourcing, etc.). Use this skill for 'distributed transactions', 'Saga pattern', 'CQRS', 'circuit breaker', 'event sourcing', 'distributed patterns', 'compensating transactions', 'eventual consistency', and other distributed system pattern applications. Enhances the distributed system design capabilities of communication-designer and service-architect. Note: infrastructure setup and monitoring configuration are outside the scope of this skill.

495 stars

Best use case

distributed-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Implementation guide and selection matrix for core distributed system patterns (Saga, CQRS, Circuit Breaker, Event Sourcing, etc.). Use this skill for 'distributed transactions', 'Saga pattern', 'CQRS', 'circuit breaker', 'event sourcing', 'distributed patterns', 'compensating transactions', 'eventual consistency', and other distributed system pattern applications. Enhances the distributed system design capabilities of communication-designer and service-architect. Note: infrastructure setup and monitoring configuration are outside the scope of this skill.

Teams using distributed-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/distributed-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/revfactory/harness-100/main/en/23-microservice-designer/.claude/skills/distributed-patterns/skill.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/distributed-patterns/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How distributed-patterns Compares

Feature / Agentdistributed-patternsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Implementation guide and selection matrix for core distributed system patterns (Saga, CQRS, Circuit Breaker, Event Sourcing, etc.). Use this skill for 'distributed transactions', 'Saga pattern', 'CQRS', 'circuit breaker', 'event sourcing', 'distributed patterns', 'compensating transactions', 'eventual consistency', and other distributed system pattern applications. Enhances the distributed system design capabilities of communication-designer and service-architect. Note: infrastructure setup and monitoring configuration are outside the scope of this skill.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Distributed Patterns — Core Distributed System Pattern Guide

Detailed pattern implementations for inter-microservice communication, data consistency, and fault tolerance.

## 1. Saga Pattern

### Choreography vs Orchestration Selection

| Criteria | Choreography | Orchestration |
|----------|-------------|---------------|
| Number of services | 2-4 | 5 or more |
| Flow complexity | Linear | Branching/conditional |
| Coupling | Event-driven loose coupling | Centralized in orchestrator |
| Visibility | Difficult to trace flow | Central state management |
| Failure handling | Each service self-compensates | Orchestrator coordinates compensation |

### Orchestration Saga Implementation

```
Order Saga:
T1: Create Order   --> C1: Cancel Order
T2: Reserve Stock  --> C2: Restore Stock
T3: Process Payment --> C3: Refund Payment
T4: Request Shipping --> C4: Cancel Shipping

Failure scenario (T3 fails):
T1 -> T2 -> T3(fail) -> C2(restore stock) -> C1(cancel order)
```

### Saga State Machine

```
STARTED -> INVENTORY_RESERVED -> PAYMENT_PROCESSED -> SHIPPING_REQUESTED -> COMPLETED
    |           |                    |                    |
 FAILED -> COMPENSATING_INVENTORY -> COMPENSATING_PAYMENT -> COMPENSATING_SHIPPING
                                                              |
                                                         COMPENSATED
```

## 2. CQRS (Command Query Responsibility Segregation)

```
+----------+     Command     +---------------+
|  Client   | -------------->| Write Model   |--> Event Store
|           |                | (Normalized DB)|
|           |     Query      +---------------+
|           | <------------- | Read Model    |<-- Projection
|           |                | (Denormalized) |
+----------+                +---------------+
```

**Application Criteria:**

| When to Apply | When NOT to Apply |
|--------------|-------------------|
| Asymmetric read/write load (100:1) | Simple CRUD apps |
| Read model and write model are very different | Read/write models are nearly identical |
| Complex domain logic + diverse views | Cannot tolerate eventual consistency |
| Used with event sourcing | Small team size (< 3 people) |

## 3. Circuit Breaker

### State Transitions

```
CLOSED --(failure rate > threshold)--> OPEN
   ^                                    |
   |                               (after timeout)
   |                                    v
   +---(success)--- HALF_OPEN ---(failure)---> OPEN
```

### Configuration Guide

| Parameter | Recommended Value | Description |
|-----------|------------------|-------------|
| failureRateThreshold | 50% | Failure rate to trigger OPEN |
| slowCallRateThreshold | 80% | Slow call rate threshold |
| slowCallDurationThreshold | 3s | Slow call criteria |
| waitDurationInOpenState | 30s | Wait before HALF_OPEN transition |
| slidingWindowSize | 100 | Measurement window size |
| minimumNumberOfCalls | 10 | Minimum call count |

### Fallback Strategies

| Strategy | Application | Example |
|----------|-------------|---------|
| Cached response | Read APIs | Return last successful response |
| Default value | Non-critical features | Popular products instead of recommendations |
| Alternate service | Payment | Secondary PG when primary PG fails |
| Queuing | Can be async | Store order in queue for later processing |
| Error response | Critical features | Clear error message |

## 4. Event Sourcing

```
Traditional approach: Store only current state
  Account { balance: 750 }

Event Sourcing: Store all change history
  1. AccountOpened  { id: A1 }
  2. MoneyDeposited { amount: 1000 }
  3. MoneyWithdrawn { amount: 250 }
  -> Reconstruct current state: balance = 0 + 1000 - 250 = 750
```

**Snapshot Strategies:**

| Strategy | Condition | Advantage |
|----------|-----------|-----------|
| Event count-based | Snapshot every N events | Predictable performance |
| Time-based | Snapshot every N minutes | Consistent recovery time |
| On-demand | On cache miss during read | Storage space savings |

## 5. API Gateway Patterns

| Pattern | Description | Application |
|---------|-------------|-------------|
| **API Composition** | Compose responses from multiple services | BFF (Backend for Frontend) |
| **Rate Limiting** | Limit request rate | Token Bucket / Sliding Window |
| **Request Routing** | Path-based routing | /api/v1/orders -> order-service |
| **Protocol Translation** | Protocol conversion | REST -> gRPC, WebSocket -> HTTP |

## Pattern Combination Recipes

### E-commerce Order Processing
```
Saga(Orchestration) + Event Sourcing + CQRS
+-- Order Saga: Coordinate inventory -> payment -> shipping
+-- Each service: Event sourcing for audit trail
+-- Order queries: Fast lookups via CQRS Read Model
```

### Real-time Chat
```
Event-Driven + Circuit Breaker + API Gateway
+-- Messages: Event streaming (Kafka)
+-- Auxiliary features: Circuit Breaker (translation, filtering)
+-- Client: WebSocket Gateway
```

## CAP Theorem Practical Application

```
              Consistency
                    /\
                   /  \
              CP  /    \ CA
                 /      \
                /________\
    Availability -------- Partition Tolerance
                  AP

Practical choices:
- CP: Payment, inventory (accuracy first)
- AP: Product browsing, recommendations (availability first)
- CA: Single-node DB (not distributed)
```

Related Skills

risk-response-patterns

495
from revfactory/harness-100

risk response strategy pattern library. response-strategist and monitoring-planner agent risk response plan establishto do when reference. 'risk response', 'mitigation strategy', 'response plan' request when usage. However, insurance design legal risk specialistdocument scope outside.

rhetoric-patterns

495
from revfactory/harness-100

numbercompany pattern library. speech-writer and debate-preparer agent persuasioncapability speech and buildingto do when reference. 'numbercompany', ' structure', 'persuasion technique' request when usage. However, actual presentation nature training scope outside.

kpi-dashboard-patterns

495
from revfactory/harness-100

KPI dashboard design pattern. analyst agent core indicator analysisand executive-summarizer management reporting dashboard compositionto do when reference. 'KPI analysis', 'dashboard design', ' indicator' request when usage. However, actualtime BI whensystem building scope outside.

diagram-patterns

495
from revfactory/harness-100

Mermaid diagram pattern library. diagram-maker agent technical document diagram writingto do when reference verifydone pattern . 'diagram pattern', 'Mermaid template', ' diagram pattern' request when usage. However, actual un-degree specialistperson tool work scope outside.

code-example-patterns

495
from revfactory/harness-100

technical document code example pattern library. doc-writer agent code example, writingto do when reference. 'code example pattern', ' code writing' request when usage. However, actual code file test execution scope outside.

claim-drafting-patterns

495
from revfactory/harness-100

Strategic drafting patterns and claim scope design guide for patent claims. The 'claim-drafter' and 'patent-reviewer' agents must use this skill's drafting patterns, terminology rules, and dependent claim strategies when writing or verifying claims. Used for 'claim drafting', 'claim scope design', 'dependent claim strategy', etc. Note: Overall patent orchestration or prior art search is outside the scope of this skill.

sdk-design-patterns

495
from revfactory/harness-100

SDK/API client design patterns: builder pattern, interceptor chain, retry strategy, type-safe design, error handling, and pagination wrapper guide. Use this skill for requests involving 'SDK design', 'client patterns', 'retry strategy', 'interceptor', 'builder pattern', 'SDK error handling', 'type safety', 'SDK architecture', etc. Enhances sdk-developer's SDK design capabilities. Note: API spec parsing, test authoring, and documentation are outside the scope of this skill.

openapi-spec-patterns

495
from revfactory/harness-100

OpenAPI 3.x spec analysis patterns, schema normalization, authentication method mapping, pagination/error pattern extraction, and GraphQL/gRPC spec interpretation guide. Use this skill for requests involving 'OpenAPI', 'Swagger', 'spec analysis', 'schema normalization', 'API authentication', 'pagination patterns', 'GraphQL schema', 'gRPC proto', etc. Enhances spec-parser's spec analysis capabilities. Note: SDK code generation and test authoring are outside the scope of this skill.

data-validation-patterns

495
from revfactory/harness-100

Migration data validation patterns: row count comparison, checksums, sampling validation, FK integrity, and business rule validation query design guide. Use this skill for requests involving 'data validation', 'migration validation', 'checksum', 'row count comparison', 'integrity validation', 'regression testing', 'Go/No-Go checklist', etc. Enhances validation-engineer's validation design capabilities. Note: schema mapping and rollback planning are outside the scope of this skill.

query-optimization-patterns

495
from revfactory/harness-100

SQL/NoSQL query optimization pattern, execution plan analysis, index strategy, N+1 resolution etc. database performance optimization guide. 'query optimization', 'execution plan', 'EXPLAIN', 'index ', 'N+1 ', 'slow query', 'slow query', 'DB performance' etc. database query performance improvement this for. bottleneck-analystand optimization-engineerof DB performance analysis -ize. , before system profilingthis benchmark execution this of scope .

test-design-patterns

495
from revfactory/harness-100

Patterns for effective test design, including boundary value analysis, equivalence partitioning, state transition testing, and other systematic test case derivation methodologies. Use this skill for 'test design', 'test case derivation', 'boundary value analysis', 'equivalence partitioning', 'state transition testing', 'pairwise', 'test matrix', and other test design tasks. Enhances the test design capabilities of test-strategist and unit-tester. Note: test infrastructure setup and CI/CD configuration are outside the scope of this skill.

strangler-fig-patterns

495
from revfactory/harness-100

Detailed implementation guide for the Strangler Fig pattern and related migration patterns for incrementally replacing legacy systems. Use this skill for 'strangler fig', 'incremental migration', 'refactoring patterns', 'branch by abstraction', 'parallel run', 'gradual replacement', 'migration pattern selection', and other legacy migration pattern applications. Enhances pattern selection and implementation for refactoring-strategist and migration-engineer. Note: full team orchestration and project management are outside the scope of this skill.