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
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.4---5
6# Designing Distributed Systems
7
8Design scalable, reliable, and fault-tolerant distributed systems using proven patterns and consistency models.
9
10## Purpose
11
12Distributed 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.
13
14## When to Use This Skill
15
16Apply when:
17- Designing microservices architectures with multiple services
18- Building systems that must scale across multiple datacenters or regions
19- Choosing between consistency vs availability during network partitions
20- 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 guarantees
23- Building resilient services with circuit breakers, bulkheads, retries
24- Implementing service discovery and inter-service communication
25
26## Core Concepts
27
28### CAP Theorem Fundamentals
29
30**CAP Theorem:** In a distributed system experiencing a network partition, choose between Consistency (C) or Availability (A). Partition tolerance (P) is mandatory.
31
32```
33Network partitions WILL occur → Always design for P
34
35During partition:
36├─ CP (Consistency + Partition Tolerance)
37│ Use when: Financial transactions, inventory, seat booking
38│ Trade-off: System unavailable during partition
39│ Examples: HBase, MongoDB (default), etcd
40│
41└─ AP (Availability + Partition Tolerance)
42 Use when: Social media, caching, analytics, shopping carts
43 Trade-off: Stale reads possible, conflicts need resolution
44 Examples: Cassandra, DynamoDB, Riak
45```
46
47**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)
50
51### Consistency Models Spectrum
52
53```
54Strong Consistency ◄─────────────────────► Eventual Consistency
55 │ │ │
56 Linearizable Causal Consistency Convergent
57 (Slowest, (Middle Ground, (Fastest,
58 Most Consistent) Causally Ordered) Eventually Consistent)
59```
60
61**Strong Consistency (Linearizability):**
62- All operations appear atomically in sequential order
63- Reads always return most recent write
64- Use for: Bank balances, inventory stock, seat booking
65- Trade-off: Higher latency, reduced availability
66
67**Eventual Consistency:**
68- If no new updates, all replicas eventually converge
69- Use for: Social feeds, product catalogs, user profiles, DNS
70- Trade-off: Stale reads possible, conflict resolution needed
71
72**Causal Consistency:**
73- Causally related operations seen in same order by all nodes
74- Use for: Chat apps, collaborative editing, comment threads
75- Trade-off: More complex than eventual, requires causality tracking
76
77**Bounded Staleness:**
78- Staleness bounded by time or version count
79- Use for: Real-time dashboards, leaderboards, monitoring
80- Trade-off: Must monitor lag, more complex than eventual
81
82### Replication Patterns
83
84**1. Leader-Follower (Single-Leader):**
85- All writes to leader, replicated to followers
86- 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 replication
90
91**2. Multi-Leader:**
92- Multiple leaders accept writes in different datacenters
93- Leaders replicate to each other
94- **Conflict resolution required:** Last-Write-Wins, application merge, vector clocks
95- Use for: Multi-datacenter, low write latency, geo-distributed users
96- Trade-off: Conflict resolution complexity
97
98**3. Leaderless (Dynamo-style):**
99- No single leader, quorum-based reads/writes
100- **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 tolerance
103- Trade-off: Complexity, read repair needed
104
105### Partitioning Strategies
106
107**Hash Partitioning (Consistent Hashing):**
108- Key → Hash(Key) → Partition assignment
109- Even distribution, minimal rebalancing when nodes added/removed
110- Use for: Point queries by ID, even distribution critical
111- Examples: Cassandra, DynamoDB, Redis Cluster
112
113**Range Partitioning:**
114- Key ranges assigned to partitions (A-F, G-M, N-S, T-Z)
115- Enables range queries, ordered data
116- Risk: Hot spots if data skewed
117- Use for: Time-series data, leaderboards, range scans
118- Examples: HBase, Bigtable
119
120**Geographic Partitioning:**
121- Partition by location (US-East, EU-West, APAC)
122- Use for: Data locality, GDPR compliance, low latency
123- Examples: Spanner, Cosmos DB
124
125### Resilience Patterns
126
127**Circuit Breaker:**
128```
129[Closed] → Normal operation
130 │ (failures exceed threshold)
131 ▼
132[Open] → Fail fast (don't call failing service)
133 │ (timeout expires)
134 ▼
135[Half-Open] → Try single request
136 │ success → [Closed]
137 │ failure → [Open]
138```
139- Prevents cascading failures
140- Fast-fail instead of waiting for timeout
141- See references/resilience-patterns.md
142
143**Bulkhead Isolation:**
144- Isolate resources (thread pools, connection pools)
145- Failure in one partition doesn't affect others
146- Like ship compartments preventing total flooding
147
148**Timeout and Retry:**
149- **Timeout:** Set deadlines, fail fast if exceeded
150- **Retry:** Exponential backoff with jitter
151- **Idempotency:** Ensure safe retry (critical)
152
153**Rate Limiting and Backpressure:**
154- Protect services from overload
155- Token bucket, leaky bucket algorithms
156- Backpressure: Signal upstream to slow down
157
158### Transaction Patterns
159
160**Saga Pattern:**
161- Coordinate distributed transactions across services
162- No distributed 2PC (two-phase commit)
163
164**Choreography:** Services react to events
165```
166Order Service → OrderCreated event
167Payment Service → listens → PaymentProcessed event
168Inventory Service → listens → InventoryReserved event
169(Compensating: if payment fails → InventoryReleased event)
170```
171
172**Orchestration:** Central coordinator
173```
174Saga Orchestrator:
1751. Call Order Service
1762. Call Payment Service
1773. Call Inventory Service
178(If step fails → call compensating transactions in reverse)
179```
180
181**Event Sourcing:**
182- Store state changes as immutable events
183- Rebuild state by replaying events
184- Audit trail, time travel, debugging
185- Trade-off: Query complexity, snapshot optimization
186
187**CQRS (Command Query Responsibility Segregation):**
188- Separate read and write models
189- Write model: Normalized, transactional
190- Read model: Denormalized, cached, optimized
191- Use for: Different read/write patterns, high read:write ratio (10:1+)
192- Often paired with Event Sourcing
193
194### Service Discovery
195
196**Client-Side Discovery:**
197- Client queries service registry (Consul, etcd, Eureka)
198- Client load balances and calls service directly
199- Pro: No proxy overhead
200- Con: Client complexity
201
202**Server-Side Discovery:**
203- Client calls load balancer
204- Load balancer queries registry and routes
205- Pro: Simple clients
206- Con: Load balancer single point of failure
207
208**Service Mesh:**
209- Sidecar proxies handle discovery, routing, retry, circuit breaking
210- Examples: Istio, Linkerd
211- Pro: Decouples communication logic from services
212- Con: Operational complexity
213
214### Caching Strategies
215
216**Cache-Aside (Lazy Loading):**
217```
218Read:
2191. Check cache → hit? return
2202. Miss? Query database
2213. Store in cache, return
222```
223
224**Write-Through:**
225```
226Write:
2271. Write to cache
2282. Cache writes to database synchronously
2293. Return success
230```
231
232**Write-Behind (Write-Back):**
233```
234Write:
2351. Write to cache
2362. Return success
2373. Cache writes to database asynchronously (batched)
238```
239
240**Cache Invalidation:**
241- TTL (Time-To-Live): Expire after duration
242- Event-based: Invalidate on data change
243- Manual: Explicit invalidation on update
244
245## Decision Frameworks
246
247### Choosing Consistency Model
248
249```
250Decision Tree:
251├─ Money involved? → Strong Consistency
252├─ Double-booking unacceptable? → Strong Consistency
253├─ Causality important (chat, edits)? → Causal Consistency
254├─ Read-heavy, stale tolerable? → Eventual Consistency
255└─ Default? → Eventual (then strengthen if needed)
256```
257
258### Choosing Replication Pattern
259
260```
261├─ Single region writes? → Leader-Follower
262├─ Multi-region writes + conflicts OK? → Multi-Leader
263├─ Multi-region writes + no conflicts? → Leader-Follower with failover
264└─ Maximum availability? → Leaderless (quorum)
265```
266
267### Choosing Partitioning Strategy
268
269```
270├─ Need range scans? → Range Partitioning (risk: hot spots)
271├─ Data residency requirements? → Geographic Partitioning
272└─ Default? → Hash Partitioning (consistent hashing)
273```
274
275## Quick Reference Tables
276
277### CAP/PACELC System Comparison
278
279| 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 |
286
287### Consistency Model Use Cases
288
289| 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 |
300
301### Quorum Configurations
302
303| 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 |
310
311## Progressive Disclosure
312
313### Detailed References
314
315For comprehensive coverage of specific topics, see:
316
317- **references/cap-pacelc-theorem.md** - CAP and PACELC deep-dive with PACELC matrix
318- **references/consistency-models.md** - Strong, eventual, causal, bounded staleness patterns
319- **references/replication-patterns.md** - Leader-follower, multi-leader, leaderless replication
320- **references/partitioning-strategies.md** - Hash, range, geographic partitioning with examples
321- **references/consensus-algorithms.md** - Raft and Paxos overview (when consensus needed)
322- **references/resilience-patterns.md** - Circuit breaker, bulkhead, timeout, retry, rate limiting
323- **references/saga-pattern.md** - Choreography vs orchestration with working examples
324- **references/event-sourcing-cqrs.md** - Event sourcing and CQRS implementation patterns
325- **references/service-discovery.md** - Client-side, server-side, service mesh patterns
326- **references/caching-strategies.md** - Cache-aside, write-through, write-behind, invalidation
327
328### Working Examples
329
330Complete, runnable examples demonstrating patterns:
331
332- **examples/consistent-hashing/** - Consistent hashing implementation with virtual nodes
333- **examples/circuit-breaker/** - Circuit breaker pattern with state transitions
334- **examples/saga-orchestration/** - Saga orchestrator with compensating transactions
335- **examples/event-sourcing/** - Event store with replay and snapshots
336- **examples/cqrs/** - CQRS with separate read/write models
337- **examples/service-discovery/** - Consul-based service discovery and registration
338
339### ASCII Diagrams
340
341Visual representations for complex concepts:
342
343- **diagrams/cap-theorem.txt** - CAP theorem decision tree
344- **diagrams/replication-topologies.txt** - Leader-follower, multi-leader, leaderless
345- **diagrams/saga-flow.txt** - Saga choreography and orchestration flows
346- **diagrams/caching-patterns.txt** - Cache-aside, write-through, write-behind
347
348## Integration with Other Skills
349
350**Related Skills:**
351
352For Kubernetes deployment: See `kubernetes-operations` skill for pod anti-affinity, service mesh
353For infrastructure: See `infrastructure-as-code` skill for deploying distributed systems
354For databases: See `databases-sql` and `databases-nosql` for replication configuration
355For messaging: See `message-queues` skill for event-driven architectures, saga orchestration
356For monitoring: See `observability` skill for distributed tracing, monitoring patterns
357For testing: See `performance-engineering` skill for load testing distributed systems
358For security: See `security-hardening` skill for mTLS, service authentication
359
360## Common Patterns
361
362### Multi-Datacenter Pattern
363
364```
3651. Choose replication: Multi-leader or Leaderless
3662. Partition data geographically
3673. Implement conflict resolution (LWW, vector clocks, app-specific)
3684. Monitor replication lag
3695. Add circuit breakers between datacenters
370```
371
372### Event-Driven Saga Pattern
373
374```
3751. Define saga steps and compensating actions
3762. Choose choreography (events) or orchestration (coordinator)
3773. Implement idempotent handlers (retries safe)
3784. Publish events with outbox pattern (transactional)
3795. Monitor saga progress and timeouts
380```
381
382### High-Availability Pattern
383
384```
3851. Use leaderless replication (N=5, W=3, R=2)
3862. Partition with consistent hashing
3873. Add circuit breakers for failing nodes
3884. Implement read repair and anti-entropy
3895. Monitor quorum health
390```
391
392## Best Practices
393
394**Design for Failure:**
395- Network partitions will occur - always design for partition tolerance
396- Use timeouts, retries with exponential backoff
397- Implement circuit breakers to prevent cascading failures
398- Test chaos engineering scenarios (partition nodes, inject latency)
399
400**Choose Consistency Carefully:**
401- Default to eventual consistency, strengthen only where needed
402- Strong consistency has real costs (latency, availability)
403- Use bounded staleness for middle ground
404
405**Idempotency is Critical:**
406- Design operations to be safely retryable
407- Use unique request IDs for deduplication
408- Essential for saga compensating transactions
409
410**Monitor and Observe:**
411- Distributed tracing with correlation IDs
412- Monitor replication lag, quorum health
413- Alert on circuit breaker state changes
414- Track saga progress and failures
415
416**Partition Strategically:**
417- Hash partitioning for even distribution
418- Range partitioning for range queries (monitor hot spots)
419- Geographic partitioning for compliance, latency
420
421**Version Everything:**
422- Event schemas evolve - use versioning
423- API versioning for service compatibility
424- Database schema migrations in distributed systems
425
426## Anti-Patterns to Avoid
427
428**Distributed Monolith:**
429- Microservices with tight coupling
430- Shared database across services
431- Fix: Database per service, async communication
432
433**Two-Phase Commit (2PC) Overuse:**
434- Slow, blocking, reduces availability
435- Fix: Use saga pattern for distributed transactions
436
437**Ignoring Network Failures:**
438- Assuming network is reliable
439- Fix: Always add timeouts, retries, circuit breakers
440
441**Strong Consistency Everywhere:**
442- Unnecessary latency and complexity
443- Fix: Use eventual consistency by default, strengthen where needed
444
445**No Conflict Resolution Strategy:**
446- Multi-leader without handling conflicts
447- Fix: Choose LWW, vector clocks, or app-specific merge
448
449**Cache Stampede:**
450- TTL expires, all clients query database
451- Fix: Probabilistic early expiration, request coalescing
452
453## Troubleshooting
454
455**Replication Lag Too High:**
456- Check network bandwidth between datacenters
457- Monitor write throughput on leader
458- Consider async replication or multi-leader
459
460**Split-Brain Scenario:**
461- Multiple leaders elected during partition
462- Fix: Use consensus (Raft, Paxos) for leader election
463- Implement fencing tokens to prevent dual writes
464
465**Hot Partitions:**
466- Range partitioning with skewed data
467- Fix: Add hash component, manually redistribute, use composite keys
468
469**Saga Timeout/Stalled:**
470- Service unavailable, saga can't complete
471- Fix: Implement saga timeout with automated rollback
472- Dead letter queue for manual intervention
473
474**Conflict Resolution Failures:**
475- Multi-leader conflicts unhandled
476- Fix: Implement clear resolution strategy (LWW, merge, manual)
477- Monitor conflict rate, alert on spikes