Consistency Models
What is Consistency?
Section titled “What is Consistency?”Consistency answers a fundamental question: When you update data in one place, when do other parts of your system see that change?
Think of it like updating a shared document. Do you want everyone to see changes instantly (strong consistency), or is it okay if they see them a few seconds later (eventual consistency)?
The Consistency Spectrum
Section titled “The Consistency Spectrum”Consistency isn’t binary—it’s a spectrum from strongest to weakest:
Real-World Examples
Section titled “Real-World Examples”Understanding how major companies use different consistency models helps illustrate their practical importance:
Strong Consistency: Banking Systems
Section titled “Strong Consistency: Banking Systems”The Challenge: Banks need to ensure account balances are always accurate. A user’s balance must be the same across all systems immediately after any transaction.
The Solution: Banks use strong consistency:
- Account Balance: All systems see the same balance immediately
- Transaction Processing: Locks ensure no double-spending
- Critical: Money accuracy is more important than speed
Example: User transfers $100:
- Strong Consistency: Lock Account A → Deduct $100 → Lock Account B → Add $100 → Unlock both
- Result: Both accounts always show correct balance
- Trade-off: Slower (waits for locks), but guaranteed accuracy
Impact: Zero incorrect balances. All transactions are accurate. Critical for financial systems.
Eventual Consistency: Social Media Platforms
Section titled “Eventual Consistency: Social Media Platforms”The Challenge: Social media platforms need fast user experience. Like counts, comments, and posts need to update instantly, but perfect accuracy across all data centers isn’t critical.
The Solution: Social media platforms use eventual consistency:
- Like Counts: Update immediately on local node, replicate to other nodes asynchronously
- Posts: Write to local node, propagate to other regions within seconds
- Trade-off: Temporary inconsistencies acceptable for speed
Example: User likes a post:
- Eventual Consistency: Update like count locally → Return success → Replicate to other data centers asynchronously
- Result: User sees instant feedback, other users see update within seconds
- Trade-off: Fast response, but temporary inconsistencies possible
Impact: Fast user experience. Handles millions of interactions. Acceptable inconsistencies for non-critical data.
Causal Consistency: Chat Applications
Section titled “Causal Consistency: Chat Applications”The Challenge: Chat applications need to preserve message order. If User B replies to User A’s message, all users must see the original message before the reply.
The Solution: Chat applications use causal consistency:
- Message Order: Preserves cause-and-effect relationships
- Threads: Ensures replies appear after original messages
- Trade-off: Stronger than eventual, but weaker than strong consistency
Example: User A posts message, User B replies:
- Causal Consistency: Track dependencies → Ensure reply is seen only after original message
- Result: All users see messages in logical order
- Trade-off: Preserves causality without global coordination
Impact: Logical message order. No confusion. Better than eventual consistency for chat.
Hybrid Approach: E-commerce Platforms
Section titled “Hybrid Approach: E-commerce Platforms”The Challenge: E-commerce platforms have different consistency needs for different data types.
The Solution: E-commerce platforms use hybrid approaches:
- Product Catalog: Eventual consistency (fast updates, acceptable inconsistencies)
- Inventory: Strong consistency (prevent overselling)
- Reviews: Causal consistency (preserve reply order)
Example: Product page load:
- Product Info: Eventual consistency (fast, may be slightly stale)
- Inventory: Strong consistency (must be accurate)
- Reviews: Causal consistency (preserve thread order)
Impact: Optimized for different data types. Right consistency model for each use case.
Model 1: Strong Consistency
Section titled “Model 1: Strong Consistency”Strong consistency guarantees that all nodes see the same data immediately after a write completes.
How It Works
Section titled “How It Works”Key Characteristic: The write operation blocks until all replicas confirm. Only then does the client get a success response.
Real-World Example: Bank Account Balance
Section titled “Real-World Example: Bank Account Balance”Trade-offs
Section titled “Trade-offs”| Aspect | Strong Consistency |
|---|---|
| Data Accuracy | Always correct, no stale reads |
| Write Latency | Higher (waits for all replicas) |
| Availability | Lower (if one node is down, writes may fail) |
| Complexity | Higher (need coordination, locks) |
| Use Cases | Financial systems, inventory, critical state |
Model 2: Eventual Consistency
Section titled “Model 2: Eventual Consistency”Eventual consistency allows temporary differences between nodes, but guarantees all nodes will eventually converge to the same state.
How It Works
Section titled “How It Works”Key Characteristic: The write returns immediately after updating the leader. Replication happens asynchronously in the background.
Real-World Example: Social Media Likes
Section titled “Real-World Example: Social Media Likes”Trade-offs
Section titled “Trade-offs”| Aspect | Eventual Consistency |
|---|---|
| Data Accuracy | ⚠️ Temporary inconsistencies possible |
| Write Latency | Lower (returns immediately) |
| Availability | Higher (can write even if some nodes down) |
| Complexity | Lower (no coordination needed) |
| Use Cases | Social media, analytics, non-critical data |
Model 3: Causal Consistency
Section titled “Model 3: Causal Consistency”Causal consistency preserves cause-and-effect relationships. If event A causes event B, all nodes that see B must have already seen A.
The Problem It Solves
Section titled “The Problem It Solves”How It Works
Section titled “How It Works”Causal consistency uses vector clocks or logical timestamps to track dependencies:
Key Characteristic: Events are delivered in causal order, even if they arrive out of order.
Real-World Example: Chat Application
Section titled “Real-World Example: Chat Application”Trade-offs
Section titled “Trade-offs”| Aspect | Causal Consistency |
|---|---|
| Data Accuracy | Preserves logical relationships |
| Write Latency | Lower than strong (no global coordination) |
| Availability | Higher than strong consistency |
| Complexity | ⚠️ Medium (need dependency tracking) |
| Use Cases | Chat, comments, collaborative editing |
Choosing the Right Consistency Model
Section titled “Choosing the Right Consistency Model”Decision Framework
Section titled “Decision Framework”| Use Case | Consistency Model | Why |
|---|---|---|
| Bank balance | Strong | Can’t have incorrect balances |
| Inventory count | Strong | Can’t oversell products |
| Social media likes | Eventual | Speed > exact count |
| View counts | Eventual | Approximate is fine |
| Chat messages | Causal | Need logical order |
| Comment threads | Causal | Replies must follow posts |
| User profiles | Eventual | Can tolerate slight delays |
LLD ↔ HLD Connection
Section titled “LLD ↔ HLD Connection”How consistency models affect your class design:
Strong Consistency → Use Locks
Section titled “Strong Consistency → Use Locks”When you need strong consistency, use synchronization primitives:
Eventual Consistency → Use Version Numbers
Section titled “Eventual Consistency → Use Version Numbers”For eventual consistency, track versions to detect conflicts:
Causal Consistency → Track Dependencies
Section titled “Causal Consistency → Track Dependencies”For causal consistency, maintain dependency graphs:
from typing import List, Set
class Event: def __init__(self, data, dependencies: List[int]): self.data = data self.dependencies = set(dependencies) # Events this depends on self.id = None # Assigned by system
class EventStore: def __init__(self): self.events = {} # id -> Event self.seen = set() # Events this node has seen
def can_deliver(self, event: Event) -> bool: # Can only deliver if all dependencies are seen return event.dependencies.issubset(self.seen)
def deliver(self, event: Event): if self.can_deliver(event): self.seen.add(event.id) # Process event...import java.util.*;
public class Event { private String data; private Set<Integer> dependencies; // Events this depends on private Integer id;
public boolean canDeliver(Set<Integer> seen) { // Can only deliver if all dependencies are seen return seen.containsAll(dependencies); }}
class EventStore { private Map<Integer, Event> events = new HashMap<>(); private Set<Integer> seen = new HashSet<>();
public boolean canDeliver(Event event) { return event.canDeliver(seen); }
public void deliver(Event event) { if (canDeliver(event)) { seen.add(event.id); // Process event... } }}Key Takeaways
Section titled “Key Takeaways”What’s Next?
Section titled “What’s Next?”Now that you understand consistency models, let’s explore the fundamental theorem that governs these trade-offs:
Next up: CAP Theorem Deep Dive — Learn why you can’t have everything: Consistency, Availability, and Partition tolerance.