Designing Distributed Systems
Design scalable, reliable, and fault-tolerant distributed systems using proven patterns and consistency models.
Purpose
Distributed systems are the foundation of modern cloud-native applications. Understanding fundamental trade-offs (CAP theorem, PACELC), consistency models, replication patterns, and resilience strategies is essential for building systems that scale globally while maintaining correctness and availability.
When to Use This Skill
Apply when:
- Designing microservices architectures with multiple services
- Building systems that must scale across multiple datacenters or regions
- Choosing between consistency vs availability during network partitions
- Selecting replication strategies (single-leader, multi-leader, leaderless)
- Implementing distributed transactions (saga pattern, event sourcing, CQRS)
- Designing partition-tolerant systems with proper consistency guarantees
- Building resilient services with circuit breakers, bulkheads, retries
- Implementing service discovery and inter-service communication
Core Concepts
CAP Theorem Fundamentals
CAP Theorem: In a distributed system experiencing a network partition, choose between Consistency (C) or Availability (A). Partition tolerance (P) is mandatory.
Network partitions WILL occur → Always design for P
During partition:
├─ CP (Consistency + Partition Tolerance)
│ Use when: Financial transactions, inventory, seat booking
│ Trade-off: System unavailable during partition
│ Examples: HBase, MongoDB (default), etcd
│
└─ AP (Availability + Partition Tolerance)
Use when: Social media, caching, analytics, shopping carts
Trade-off: Stale reads possible, conflicts need resolution
Examples: Cassandra, DynamoDB, Riak
PACELC: Extends CAP to consider normal operations (no partition).
- If Partition: Choose Availability (A) or Consistency (C)
- Else (normal): Choose Latency (L) or Consistency (C)
Consistency Models Spectrum
Strong Consistency ◄─────────────────────► Eventual Consistency
│ │ │
Linearizable Causal Consistency Convergent
(Slowest, (Middle Ground, (Fastest,
Most Consistent) Causally Ordered) Eventually Consistent)
Strong Consistency (Linearizability):
- All operations appear atomically in sequential order
- Reads always return most recent write
- Use for: Bank balances, inventory stock, seat booking
- Trade-off: Higher latency, reduced availability
Eventual Consistency:
- If no new updates, all replicas eventually converge
- Use for: Social feeds, product catalogs, user profiles, DNS
- Trade-off: Stale reads possible, conflict resolution needed
Causal Consistency:
- Causally related operations seen in same order by all nodes
- Use for: Chat apps, collaborative editing, comment threads
- Trade-off: More complex than eventual, requires causality tracking
Bounded Staleness:
- Staleness bounded by time or version count
- Use for: Real-time dashboards, leaderboards, monitoring
- Trade-off: Must monitor lag, more complex than eventual
Replication Patterns
1. Leader-Follower (Single-Leader):
- All writes to leader, replicated to followers
- Followers handle reads (load distribution)
- Synchronous: Wait for follower ACK (strong consistency, higher latency)
- Asynchronous: Don't wait (eventual consistency, possible data loss)
- Use for: Most common pattern, strong consistency with sync replication
2. Multi-Leader:
- Multiple leaders accept writes in different datacenters
- Leaders replicate to each other
- Conflict resolution required: Last-Write-Wins, application merge, vector clocks
- Use for: Multi-datacenter, low write latency, geo-distributed users
- Trade-off: Conflict resolution complexity
3. Leaderless (Dynamo-style):
- No single leader, quorum-based reads/writes
- Quorum rule: W + R > N (W=write quorum, R=read quorum, N=replicas)
- Example: N=5, W=3, R=2 → Strong consistency (overlap guaranteed)
- Use for: Maximum availability, partition tolerance
- Trade-off: Complexity, read repair needed
Partitioning Strategies
Hash Partitioning (Consistent Hashing):
- Key → Hash(Key) → Partition assignment
- Even distribution, minimal rebalancing when nodes added/removed
- Use for: Point queries by ID, even distribution critical
- Examples: Cassandra, DynamoDB, Redis Cluster
Range Partitioning:
- Key ranges assigned to partitions (A-F, G-M, N-S, T-Z)
- Enables range queries, ordered data
- Risk: Hot spots if data skewed
- Use for: Time-series data, leaderboards, range scans
- Examples: HBase, Bigtable
Geographic Partitioning:
- Partition by location (US-East, EU-West, APAC)
- Use for: Data locality, GDPR compliance, low latency
- Examples: Spanner, Cosmos DB
Resilience Patterns
Circuit Breaker:
[Closed] → Normal operation
│ (failures exceed threshold)
▼
[Open] → Fail fast (don't call failing service)
│ (timeout expires)
▼
[Half-Open] → Try single request
│ success → [Closed]
│ failure → [Open]
- Prevents cascading failures
- Fast-fail instead of waiting for timeout
- See references/resilience-patterns.md
Bulkhead Isolation:
- Isolate resources (thread pools, connection pools)
- Failure in one partition doesn't affect others
- Like ship compartments preventing total flooding
Timeout and Retry:
- Timeout: Set deadlines, fail fast if exceeded
- Retry: Exponential backoff with jitter
- Idempotency: Ensure safe retry (critical)
Rate Limiting and Backpressure:
- Protect services from overload
- Token bucket, leaky bucket algorithms
- Backpressure: Signal upstream to slow down
Transaction Patterns
Saga Pattern:
- Coordinate distributed transactions across services
- No distributed 2PC (two-phase commit)
Choreography: Services react to events
Order Service → OrderCreated event
Payment Service → listens → PaymentProcessed event
Inventory Service → listens → InventoryReserved event
(Compensating: if payment fails → InventoryReleased event)
Orchestration: Central coordinator
Saga Orchestrator:
1. Call Order Service
2. Call Payment Service
3. Call Inventory Service
(If step fails → call compensating transactions in reverse)
Event Sourcing:
- Store state changes as immutable events
- Rebuild state by replaying events
- Audit trail, time travel, debugging
- Trade-off: Query complexity, snapshot optimization
CQRS (Command Query Responsibility Segregation):
- Separate read and write models
- Write model: Normalized, transactional
- Read model: Denormalized, cached, optimized
- Use for: Different read/write patterns, high read:write ratio (10:1+)
- Often paired with Event Sourcing
Service Discovery
Client-Side Discovery:
- Client queries service registry (Consul, etcd, Eureka)
- Client load balances and calls service directly
- Pro: No proxy overhead
- Con: Client complexity
Server-Side Discovery:
- Client calls load balancer
- Load balancer queries registry and routes
- Pro: Simple clients
- Con: Load balancer single point of failure
Service Mesh:
- Sidecar proxies handle discovery, routing, retry, circuit breaking
- Examples: Istio, Linkerd
- Pro: Decouples communication logic from services
- Con: Operational complexity
Caching Strategies
Cache-Aside (Lazy Loading):
Read:
1. Check cache → hit? return
2. Miss? Query database
3. Store in cache, return
Write-Through:
Write:
1. Write to cache
2. Cache writes to database synchronously
3. Return success
Write-Behind (Write-Back):
Write:
1. Write to cache
2. Return success
3. Cache writes to database asynchronously (batched)
Cache Invalidation:
- TTL (Time-To-Live): Expire after duration
- Event-based: Invalidate on data change
- Manual: Explicit invalidation on update
Decision Frameworks
Choosing Consistency Model
Decision Tree:
├─ Money involved? → Strong Consistency
├─ Double-booking unacceptable? → Strong Consistency
├─ Causality important (chat, edits)? → Causal Consistency
├─ Read-heavy, stale tolerable? → Eventual Consistency
└─ Default? → Eventual (then strengthen if needed)
Choosing Replication Pattern
├─ Single region writes? → Leader-Follower
├─ Multi-region writes + conflicts OK? → Multi-Leader
├─ Multi-region writes + no conflicts? → Leader-Follower with failover
└─ Maximum availability? → Leaderless (quorum)
Choosing Partitioning Strategy
├─ Need range scans? → Range Partitioning (risk: hot spots)
├─ Data residency requirements? → Geographic Partitioning
└─ Default? → Hash Partitioning (consistent hashing)
Quick Reference Tables
CAP/PACELC System Comparison
| System |
If Partition |
Else (Normal) |
Use Case |
| Spanner |
PC |
EC (strong) |
Global SQL |
| DynamoDB |
PA |
EL (eventual) |
High availability |
| Cassandra |
PA |
EL (tunable) |
Wide-column store |
| MongoDB |
PC |
EC (default) |
Document store |
| Cosmos DB |
PA/PC |
EL/EC (5 levels) |
Multi-model |
Consistency Model Use Cases
| Use Case |
Consistency Model |
| Bank account balance |
Strong (Linearizable) |
| Seat booking (airline) |
Strong (Linearizable) |
| Inventory stock count |
Strong or Bounded |
| Shopping cart |
Eventual |
| Product catalog |
Eventual |
| Collaborative editing |
Causal |
| Chat messages |
Causal |
| Social media likes |
Eventual |
| DNS records |
Eventual |
Quorum Configurations
| Configuration |
W |
R |
N |
Consistency |
Use Case |
| Strong |
3 |
3 |
5 |
Strong |
Banking |
| Balanced |
3 |
2 |
5 |
Strong |
Default |
| Write-heavy |
2 |
3 |
5 |
Strong |
Logs |
| Read-heavy |
3 |
1 |
5 |
Eventual |
Cache |
| Max Avail |
1 |
1 |
5 |
Eventual |
Analytics |
Progressive Disclosure
Detailed References
For comprehensive coverage of specific topics, see:
- references/cap-pacelc-theorem.md - CAP and PACELC deep-dive with PACELC matrix
- references/consistency-models.md - Strong, eventual, causal, bounded staleness patterns
- references/replication-patterns.md - Leader-follower, multi-leader, leaderless replication
- references/partitioning-strategies.md - Hash, range, geographic partitioning with examples
- references/consensus-algorithms.md - Raft and Paxos overview (when consensus needed)
- references/resilience-patterns.md - Circuit breaker, bulkhead, timeout, retry, rate limiting
- references/saga-pattern.md - Choreography vs orchestration with working examples
- references/event-sourcing-cqrs.md - Event sourcing and CQRS implementation patterns
- references/service-discovery.md - Client-side, server-side, service mesh patterns
- references/caching-strategies.md - Cache-aside, write-through, write-behind, invalidation
Working Examples
Complete, runnable examples demonstrating patterns:
- examples/consistent-hashing/ - Consistent hashing implementation with virtual nodes
- examples/circuit-breaker/ - Circuit breaker pattern with state transitions
- examples/saga-orchestration/ - Saga orchestrator with compensating transactions
- examples/event-sourcing/ - Event store with replay and snapshots
- examples/cqrs/ - CQRS with separate read/write models
- examples/service-discovery/ - Consul-based service discovery and registration
ASCII Diagrams
Visual representations for complex concepts:
- diagrams/cap-theorem.txt - CAP theorem decision tree
- diagrams/replication-topologies.txt - Leader-follower, multi-leader, leaderless
- diagrams/saga-flow.txt - Saga choreography and orchestration flows
- diagrams/caching-patterns.txt - Cache-aside, write-through, write-behind
Integration with Other Skills
Related Skills:
For Kubernetes deployment: See kubernetes-operations skill for pod anti-affinity, service mesh
For infrastructure: See infrastructure-as-code skill for deploying distributed systems
For databases: See databases-sql and databases-nosql for replication configuration
For messaging: See message-queues skill for event-driven architectures, saga orchestration
For monitoring: See observability skill for distributed tracing, monitoring patterns
For testing: See performance-engineering skill for load testing distributed systems
For security: See security-hardening skill for mTLS, service authentication
Common Patterns
Multi-Datacenter Pattern
1. Choose replication: Multi-leader or Leaderless
2. Partition data geographically
3. Implement conflict resolution (LWW, vector clocks, app-specific)
4. Monitor replication lag
5. Add circuit breakers between datacenters
Event-Driven Saga Pattern
1. Define saga steps and compensating actions
2. Choose choreography (events) or orchestration (coordinator)
3. Implement idempotent handlers (retries safe)
4. Publish events with outbox pattern (transactional)
5. Monitor saga progress and timeouts
High-Availability Pattern
1. Use leaderless replication (N=5, W=3, R=2)
2. Partition with consistent hashing
3. Add circuit breakers for failing nodes
4. Implement read repair and anti-entropy
5. Monitor quorum health
Best Practices
Design for Failure:
- Network partitions will occur - always design for partition tolerance
- Use timeouts, retries with exponential backoff
- Implement circuit breakers to prevent cascading failures
- Test chaos engineering scenarios (partition nodes, inject latency)
Choose Consistency Carefully:
- Default to eventual consistency, strengthen only where needed
- Strong consistency has real costs (latency, availability)
- Use bounded staleness for middle ground
Idempotency is Critical:
- Design operations to be safely retryable
- Use unique request IDs for deduplication
- Essential for saga compensating transactions
Monitor and Observe:
- Distributed tracing with correlation IDs
- Monitor replication lag, quorum health
- Alert on circuit breaker state changes
- Track saga progress and failures
Partition Strategically:
- Hash partitioning for even distribution
- Range partitioning for range queries (monitor hot spots)
- Geographic partitioning for compliance, latency
Version Everything:
- Event schemas evolve - use versioning
- API versioning for service compatibility
- Database schema migrations in distributed systems
Anti-Patterns to Avoid
Distributed Monolith:
- Microservices with tight coupling
- Shared database across services
- Fix: Database per service, async communication
Two-Phase Commit (2PC) Overuse:
- Slow, blocking, reduces availability
- Fix: Use saga pattern for distributed transactions
Ignoring Network Failures:
- Assuming network is reliable
- Fix: Always add timeouts, retries, circuit breakers
Strong Consistency Everywhere:
- Unnecessary latency and complexity
- Fix: Use eventual consistency by default, strengthen where needed
No Conflict Resolution Strategy:
- Multi-leader without handling conflicts
- Fix: Choose LWW, vector clocks, or app-specific merge
Cache Stampede:
- TTL expires, all clients query database
- Fix: Probabilistic early expiration, request coalescing
Troubleshooting
Replication Lag Too High:
- Check network bandwidth between datacenters
- Monitor write throughput on leader
- Consider async replication or multi-leader
Split-Brain Scenario:
- Multiple leaders elected during partition
- Fix: Use consensus (Raft, Paxos) for leader election
- Implement fencing tokens to prevent dual writes
Hot Partitions:
- Range partitioning with skewed data
- Fix: Add hash component, manually redistribute, use composite keys
Saga Timeout/Stalled:
- Service unavailable, saga can't complete
- Fix: Implement saga timeout with automated rollback
- Dead letter queue for manual intervention
Conflict Resolution Failures:
- Multi-leader conflicts unhandled
- Fix: Implement clear resolution strategy (LWW, merge, manual)
- Monitor conflict rate, alert on spikes
Source: ancoleman/ai-design-components — distributed by TomeVault.
1---2name: designing-distributed-systems3description: When designing distributed systems for scalability, reliability, and consistency. Covers CAP/PACELC theorems, consistency models (strong, eventual, causal), replication patterns (leader-follower, multi-leader, leaderless), partitioning strategies (hash, range, geographic), transaction patterns (saga, event sourcing, CQRS), resilience patterns (circuit breaker, bulkhead), service discovery, and caching strategies for building fault-tolerant distributed architectures. Use when this capability is needed.4---56# Designing Distributed Systems78Design scalable, reliable, and fault-tolerant distributed systems using proven patterns and consistency models.910## Purpose1112Distributed systems are the foundation of modern cloud-native applications. Understanding fundamental trade-offs (CAP theorem, PACELC), consistency models, replication patterns, and resilience strategies is essential for building systems that scale globally while maintaining correctness and availability.1314## When to Use This Skill1516Apply when:17- Designing microservices architectures with multiple services18- Building systems that must scale across multiple datacenters or regions19- Choosing between consistency vs availability during network partitions20- Selecting replication strategies (single-leader, multi-leader, leaderless)21- Implementing distributed transactions (saga pattern, event sourcing, CQRS)22- Designing partition-tolerant systems with proper consistency guarantees23- Building resilient services with circuit breakers, bulkheads, retries24- Implementing service discovery and inter-service communication2526## Core Concepts2728### CAP Theorem Fundamentals2930**CAP Theorem:** In a distributed system experiencing a network partition, choose between Consistency (C) or Availability (A). Partition tolerance (P) is mandatory.3132```33Network partitions WILL occur → Always design for P3435During partition:36├─ CP (Consistency + Partition Tolerance)37│ Use when: Financial transactions, inventory, seat booking38│ Trade-off: System unavailable during partition39│ Examples: HBase, MongoDB (default), etcd40│41└─ AP (Availability + Partition Tolerance)42 Use when: Social media, caching, analytics, shopping carts43 Trade-off: Stale reads possible, conflicts need resolution44 Examples: Cassandra, DynamoDB, Riak45```4647**PACELC:** Extends CAP to consider normal operations (no partition).48- **If Partition:** Choose Availability (A) or Consistency (C)49- **Else (normal):** Choose Latency (L) or Consistency (C)5051### Consistency Models Spectrum5253```54Strong Consistency ◄─────────────────────► Eventual Consistency55 │ │ │56 Linearizable Causal Consistency Convergent57 (Slowest, (Middle Ground, (Fastest,58 Most Consistent) Causally Ordered) Eventually Consistent)59```6061**Strong Consistency (Linearizability):**62- All operations appear atomically in sequential order63- Reads always return most recent write64- Use for: Bank balances, inventory stock, seat booking65- Trade-off: Higher latency, reduced availability6667**Eventual Consistency:**68- If no new updates, all replicas eventually converge69- Use for: Social feeds, product catalogs, user profiles, DNS70- Trade-off: Stale reads possible, conflict resolution needed7172**Causal Consistency:**73- Causally related operations seen in same order by all nodes74- Use for: Chat apps, collaborative editing, comment threads75- Trade-off: More complex than eventual, requires causality tracking7677**Bounded Staleness:**78- Staleness bounded by time or version count79- Use for: Real-time dashboards, leaderboards, monitoring80- Trade-off: Must monitor lag, more complex than eventual8182### Replication Patterns8384**1. Leader-Follower (Single-Leader):**85- All writes to leader, replicated to followers86- Followers handle reads (load distribution)87- **Synchronous:** Wait for follower ACK (strong consistency, higher latency)88- **Asynchronous:** Don't wait (eventual consistency, possible data loss)89- Use for: Most common pattern, strong consistency with sync replication9091**2. Multi-Leader:**92- Multiple leaders accept writes in different datacenters93- Leaders replicate to each other94- **Conflict resolution required:** Last-Write-Wins, application merge, vector clocks95- Use for: Multi-datacenter, low write latency, geo-distributed users96- Trade-off: Conflict resolution complexity9798**3. Leaderless (Dynamo-style):**99- No single leader, quorum-based reads/writes100- **Quorum rule:** W + R > N (W=write quorum, R=read quorum, N=replicas)101- Example: N=5, W=3, R=2 → Strong consistency (overlap guaranteed)102- Use for: Maximum availability, partition tolerance103- Trade-off: Complexity, read repair needed104105### Partitioning Strategies106107**Hash Partitioning (Consistent Hashing):**108- Key → Hash(Key) → Partition assignment109- Even distribution, minimal rebalancing when nodes added/removed110- Use for: Point queries by ID, even distribution critical111- Examples: Cassandra, DynamoDB, Redis Cluster112113**Range Partitioning:**114- Key ranges assigned to partitions (A-F, G-M, N-S, T-Z)115- Enables range queries, ordered data116- Risk: Hot spots if data skewed117- Use for: Time-series data, leaderboards, range scans118- Examples: HBase, Bigtable119120**Geographic Partitioning:**121- Partition by location (US-East, EU-West, APAC)122- Use for: Data locality, GDPR compliance, low latency123- Examples: Spanner, Cosmos DB124125### Resilience Patterns126127**Circuit Breaker:**128```129[Closed] → Normal operation130 │ (failures exceed threshold)131 ▼132[Open] → Fail fast (don't call failing service)133 │ (timeout expires)134 ▼135[Half-Open] → Try single request136 │ success → [Closed]137 │ failure → [Open]138```139- Prevents cascading failures140- Fast-fail instead of waiting for timeout141- See references/resilience-patterns.md142143**Bulkhead Isolation:**144- Isolate resources (thread pools, connection pools)145- Failure in one partition doesn't affect others146- Like ship compartments preventing total flooding147148**Timeout and Retry:**149- **Timeout:** Set deadlines, fail fast if exceeded150- **Retry:** Exponential backoff with jitter151- **Idempotency:** Ensure safe retry (critical)152153**Rate Limiting and Backpressure:**154- Protect services from overload155- Token bucket, leaky bucket algorithms156- Backpressure: Signal upstream to slow down157158### Transaction Patterns159160**Saga Pattern:**161- Coordinate distributed transactions across services162- No distributed 2PC (two-phase commit)163164**Choreography:** Services react to events165```166Order Service → OrderCreated event167Payment Service → listens → PaymentProcessed event168Inventory Service → listens → InventoryReserved event169(Compensating: if payment fails → InventoryReleased event)170```171172**Orchestration:** Central coordinator173```174Saga Orchestrator:1751. Call Order Service1762. Call Payment Service1773. Call Inventory Service178(If step fails → call compensating transactions in reverse)179```180181**Event Sourcing:**182- Store state changes as immutable events183- Rebuild state by replaying events184- Audit trail, time travel, debugging185- Trade-off: Query complexity, snapshot optimization186187**CQRS (Command Query Responsibility Segregation):**188- Separate read and write models189- Write model: Normalized, transactional190- Read model: Denormalized, cached, optimized191- Use for: Different read/write patterns, high read:write ratio (10:1+)192- Often paired with Event Sourcing193194### Service Discovery195196**Client-Side Discovery:**197- Client queries service registry (Consul, etcd, Eureka)198- Client load balances and calls service directly199- Pro: No proxy overhead200- Con: Client complexity201202**Server-Side Discovery:**203- Client calls load balancer204- Load balancer queries registry and routes205- Pro: Simple clients206- Con: Load balancer single point of failure207208**Service Mesh:**209- Sidecar proxies handle discovery, routing, retry, circuit breaking210- Examples: Istio, Linkerd211- Pro: Decouples communication logic from services212- Con: Operational complexity213214### Caching Strategies215216**Cache-Aside (Lazy Loading):**217```218Read:2191. Check cache → hit? return2202. Miss? Query database2213. Store in cache, return222```223224**Write-Through:**225```226Write:2271. Write to cache2282. Cache writes to database synchronously2293. Return success230```231232**Write-Behind (Write-Back):**233```234Write:2351. Write to cache2362. Return success2373. Cache writes to database asynchronously (batched)238```239240**Cache Invalidation:**241- TTL (Time-To-Live): Expire after duration242- Event-based: Invalidate on data change243- Manual: Explicit invalidation on update244245## Decision Frameworks246247### Choosing Consistency Model248249```250Decision Tree:251├─ Money involved? → Strong Consistency252├─ Double-booking unacceptable? → Strong Consistency253├─ Causality important (chat, edits)? → Causal Consistency254├─ Read-heavy, stale tolerable? → Eventual Consistency255└─ Default? → Eventual (then strengthen if needed)256```257258### Choosing Replication Pattern259260```261├─ Single region writes? → Leader-Follower262├─ Multi-region writes + conflicts OK? → Multi-Leader263├─ Multi-region writes + no conflicts? → Leader-Follower with failover264└─ Maximum availability? → Leaderless (quorum)265```266267### Choosing Partitioning Strategy268269```270├─ Need range scans? → Range Partitioning (risk: hot spots)271├─ Data residency requirements? → Geographic Partitioning272└─ Default? → Hash Partitioning (consistent hashing)273```274275## Quick Reference Tables276277### CAP/PACELC System Comparison278279| System | If Partition | Else (Normal) | Use Case |280|------------|--------------|---------------|--------------------|281| Spanner | PC | EC (strong) | Global SQL |282| DynamoDB | PA | EL (eventual) | High availability |283| Cassandra | PA | EL (tunable) | Wide-column store |284| MongoDB | PC | EC (default) | Document store |285| Cosmos DB | PA/PC | EL/EC (5 levels) | Multi-model |286287### Consistency Model Use Cases288289| Use Case | Consistency Model |290|----------------------------|------------------------|291| Bank account balance | Strong (Linearizable) |292| Seat booking (airline) | Strong (Linearizable) |293| Inventory stock count | Strong or Bounded |294| Shopping cart | Eventual |295| Product catalog | Eventual |296| Collaborative editing | Causal |297| Chat messages | Causal |298| Social media likes | Eventual |299| DNS records | Eventual |300301### Quorum Configurations302303| Configuration | W | R | N | Consistency | Use Case |304|--------------|---|---|---|-------------|-------------|305| Strong | 3 | 3 | 5 | Strong | Banking |306| Balanced | 3 | 2 | 5 | Strong | Default |307| Write-heavy | 2 | 3 | 5 | Strong | Logs |308| Read-heavy | 3 | 1 | 5 | Eventual | Cache |309| Max Avail | 1 | 1 | 5 | Eventual | Analytics |310311## Progressive Disclosure312313### Detailed References314315For comprehensive coverage of specific topics, see:316317- **references/cap-pacelc-theorem.md** - CAP and PACELC deep-dive with PACELC matrix318- **references/consistency-models.md** - Strong, eventual, causal, bounded staleness patterns319- **references/replication-patterns.md** - Leader-follower, multi-leader, leaderless replication320- **references/partitioning-strategies.md** - Hash, range, geographic partitioning with examples321- **references/consensus-algorithms.md** - Raft and Paxos overview (when consensus needed)322- **references/resilience-patterns.md** - Circuit breaker, bulkhead, timeout, retry, rate limiting323- **references/saga-pattern.md** - Choreography vs orchestration with working examples324- **references/event-sourcing-cqrs.md** - Event sourcing and CQRS implementation patterns325- **references/service-discovery.md** - Client-side, server-side, service mesh patterns326- **references/caching-strategies.md** - Cache-aside, write-through, write-behind, invalidation327328### Working Examples329330Complete, runnable examples demonstrating patterns:331332- **examples/consistent-hashing/** - Consistent hashing implementation with virtual nodes333- **examples/circuit-breaker/** - Circuit breaker pattern with state transitions334- **examples/saga-orchestration/** - Saga orchestrator with compensating transactions335- **examples/event-sourcing/** - Event store with replay and snapshots336- **examples/cqrs/** - CQRS with separate read/write models337- **examples/service-discovery/** - Consul-based service discovery and registration338339### ASCII Diagrams340341Visual representations for complex concepts:342343- **diagrams/cap-theorem.txt** - CAP theorem decision tree344- **diagrams/replication-topologies.txt** - Leader-follower, multi-leader, leaderless345- **diagrams/saga-flow.txt** - Saga choreography and orchestration flows346- **diagrams/caching-patterns.txt** - Cache-aside, write-through, write-behind347348## Integration with Other Skills349350**Related Skills:**351352For Kubernetes deployment: See `kubernetes-operations` skill for pod anti-affinity, service mesh353For infrastructure: See `infrastructure-as-code` skill for deploying distributed systems354For databases: See `databases-sql` and `databases-nosql` for replication configuration355For messaging: See `message-queues` skill for event-driven architectures, saga orchestration356For monitoring: See `observability` skill for distributed tracing, monitoring patterns357For testing: See `performance-engineering` skill for load testing distributed systems358For security: See `security-hardening` skill for mTLS, service authentication359360## Common Patterns361362### Multi-Datacenter Pattern363364```3651. Choose replication: Multi-leader or Leaderless3662. Partition data geographically3673. Implement conflict resolution (LWW, vector clocks, app-specific)3684. Monitor replication lag3695. Add circuit breakers between datacenters370```371372### Event-Driven Saga Pattern373374```3751. Define saga steps and compensating actions3762. Choose choreography (events) or orchestration (coordinator)3773. Implement idempotent handlers (retries safe)3784. Publish events with outbox pattern (transactional)3795. Monitor saga progress and timeouts380```381382### High-Availability Pattern383384```3851. Use leaderless replication (N=5, W=3, R=2)3862. Partition with consistent hashing3873. Add circuit breakers for failing nodes3884. Implement read repair and anti-entropy3895. Monitor quorum health390```391392## Best Practices393394**Design for Failure:**395- Network partitions will occur - always design for partition tolerance396- Use timeouts, retries with exponential backoff397- Implement circuit breakers to prevent cascading failures398- Test chaos engineering scenarios (partition nodes, inject latency)399400**Choose Consistency Carefully:**401- Default to eventual consistency, strengthen only where needed402- Strong consistency has real costs (latency, availability)403- Use bounded staleness for middle ground404405**Idempotency is Critical:**406- Design operations to be safely retryable407- Use unique request IDs for deduplication408- Essential for saga compensating transactions409410**Monitor and Observe:**411- Distributed tracing with correlation IDs412- Monitor replication lag, quorum health413- Alert on circuit breaker state changes414- Track saga progress and failures415416**Partition Strategically:**417- Hash partitioning for even distribution418- Range partitioning for range queries (monitor hot spots)419- Geographic partitioning for compliance, latency420421**Version Everything:**422- Event schemas evolve - use versioning423- API versioning for service compatibility424- Database schema migrations in distributed systems425426## Anti-Patterns to Avoid427428**Distributed Monolith:**429- Microservices with tight coupling430- Shared database across services431- Fix: Database per service, async communication432433**Two-Phase Commit (2PC) Overuse:**434- Slow, blocking, reduces availability435- Fix: Use saga pattern for distributed transactions436437**Ignoring Network Failures:**438- Assuming network is reliable439- Fix: Always add timeouts, retries, circuit breakers440441**Strong Consistency Everywhere:**442- Unnecessary latency and complexity443- Fix: Use eventual consistency by default, strengthen where needed444445**No Conflict Resolution Strategy:**446- Multi-leader without handling conflicts447- Fix: Choose LWW, vector clocks, or app-specific merge448449**Cache Stampede:**450- TTL expires, all clients query database451- Fix: Probabilistic early expiration, request coalescing452453## Troubleshooting454455**Replication Lag Too High:**456- Check network bandwidth between datacenters457- Monitor write throughput on leader458- Consider async replication or multi-leader459460**Split-Brain Scenario:**461- Multiple leaders elected during partition462- Fix: Use consensus (Raft, Paxos) for leader election463- Implement fencing tokens to prevent dual writes464465**Hot Partitions:**466- Range partitioning with skewed data467- Fix: Add hash component, manually redistribute, use composite keys468469**Saga Timeout/Stalled:**470- Service unavailable, saga can't complete471- Fix: Implement saga timeout with automated rollback472- Dead letter queue for manual intervention473474**Conflict Resolution Failures:**475- Multi-leader conflicts unhandled476- Fix: Implement clear resolution strategy (LWW, merge, manual)477- Monitor conflict rate, alert on spikes478479---480> Source: [ancoleman/ai-design-components](https://github.com/ancoleman/ai-design-components) — distributed by [TomeVault](https://tomevault.io).481<!-- tomevault:4.0:skill_md:2026-06-22 -->