CAP Theorem Simplified
Summary of CAP Theorem Simplified from ByteByteGo · Published 2023-01-03 · Views: 251,591
This note was generated automatically from the video transcript.
TL;DR
CAP states that in the presence of a network partition a distributed system must sacrifice either Consistency or Availability. Real‑world systems often adopt hybrid or “best‑effort” strategies that lie between the extremes.
Key Insights
- CAP trade‑off: When a partition occurs, you can keep the system available (serve requests) or keep it consistent (all nodes see the same data), but not both.
- Bank ATM example illustrates the danger of choosing availability: two isolated ATMs can each let a customer withdraw the full balance, resulting in a negative total after reconnection.
- Social media workloads typically favor availability; occasional stale reads are acceptable, whereas strict consistency would make commenting unavailable during a partition.
- Real‑world nuance: CAP’s binary model (100 % consistency vs. 100 % availability) is oversimplified; systems can offer partial consistency/availability and employ hybrid rules (e.g., read‑only during partitions, limit write size).
- Reconciliation complexity grows with data structure richness (e.g., Google Docs concurrent edits require conflict‑resolution algorithms).
- Beyond CAP: When the network is healthy, the dominant trade‑off shifts to latency vs. consistency, captured by the PACELC theorem.
Detailed Breakdown
1. What is the CAP Theorem?
- Consistency (C) – every read sees the most recent write; all nodes have the same view.
- Availability (A) – every request receives a response (success or failure) without waiting for other nodes.
- Partition tolerance (P) – the system continues operating despite network partitions (loss of communication between subsets of nodes).
Network partition: a failure that isolates groups of nodes so they cannot exchange messages.
When a partition occurs, a system must choose between C and A.
2. Concrete Bank ATM Example
- Setup: Two ATMs, each stores the full account balance locally; no central database.
- Operations:
deposit,withdraw,check balance. Balance must never drop below 0. - Normal flow: A transaction updates both ATMs over the network, keeping them consistent.
Partition Scenarios
| Strategy | Behavior during partition | Result after partition resolves | |———-|—————————|———————————| | Prioritize Consistency | ATMs refuse deposits/withdrawals; only balance inquiries allowed. | No negative balance; system was unavailable. | | Prioritize Availability | ATMs allow all operations locally. | Both ATMs may have withdrawn the full balance → negative total after sync. | | Hybrid | Allow reads; block large writes; maybe allow small withdrawals. | Reduces risk of negative balance while keeping most services up. |
flowchart LR
client["Customer"] --> atm1["ATM 1"]
client --> atm2["ATM 2"]
atm1 <-->|"Network Link"| atm2
subgraph Partition[Network Partition]
atm1 -.-> atm2
end
3. Social Media Commenting Example
- Scenario: Two users comment on the same post during a partition.
- Availability‑first: Both comments are accepted locally; each user may not see the other’s comment until the partition heals.
- Consistency‑first: Commenting feature is disabled; users see a stale view but no divergent state.
sequenceDiagram
participant U1 as User A
participant U2 as User B
participant S1 as Service Replica 1
participant S2 as Service Replica 2
U1->>S1: Post comment
Note right of S1: Stored locally
U2->>S2: Post comment
Note right of S2: Stored locally
Note over S1,S2: Network partition prevents sync
S1-->>U1: Ack
S2-->>U2: Ack
%% After partition heals
S1->>S2: Replicate updates
S2->>S1: Replicate updates
4. Why CAP Can Be Misleading
- Binary assumption: CAP treats consistency and availability as all‑or‑nothing, while production systems often expose degrees (e.g., eventual consistency, read‑only mode).
- Reconciliation cost: Simple numeric balances are easy to fix; complex structures (documents, graphs) need sophisticated conflict‑resolution (CRDTs, OT).
- Latency vs. consistency: When the network is healthy, designers care more about how fast a read returns versus how fresh the data is—a trade‑off captured by PACELC (
PartitionAvailabilityConsistencyElseLatencyConsistency).
5. Practical Takeaways
- Use CAP as a mental model for failure scenarios, not as a prescriptive rule for normal operation.
- Design fallback modes (read‑only, limited‑write) that gracefully degrade during partitions.
- Choose data structures and replication strategies that match the acceptable level of inconsistency (e.g., CRDTs for collaborative editing).
- Complement CAP analysis with PACELC to reason about latency‑consistency trade‑offs when the network is intact.
Trade-offs and Gotchas
- Choosing Consistency → higher safety (no stale reads) but may block critical user actions during outages.
- Choosing Availability → better user experience during failures, but risk of divergent state and costly reconciliation.
- Hybrid policies can mitigate extremes but add implementation complexity and require careful threshold tuning (e.g., “small withdrawals only”).
- Reconciliation may be trivial (numeric totals) or extremely hard (rich text documents); underestimate this cost.
- Assuming 100 % of any property is unrealistic; design for acceptable percentages (e.g., 99.9 % availability, eventual consistency within seconds).
Takeaways
- Treat CAP as a starting point for thinking about partition handling; always layer additional constraints (latency, cost, data model) on top.
- Implement graceful degradation: define which operations stay available and which are blocked when a partition is detected.
- Prefer data models with built‑in conflict resolution (CRDTs, version vectors) when you must stay highly available.
- Remember that real‑world systems rarely operate at the extremes; aim for a balanced SLA that matches business requirements.
Glossary
- Consistency: All nodes see the same data at the same logical point in time.
- Availability: Every request receives a response, regardless of the state of other nodes.
- Partition tolerance: The ability of a system to keep functioning despite network splits.
- Network partition: A failure that isolates subsets of nodes, preventing them from communicating.
- Eventual consistency: Guarantees that, given no new updates, all replicas will converge to the same value.
- CRDT (Conflict‑free Replicated Data Type): Data structures that resolve concurrent updates automatically without coordination.
- PACELC theorem: Extends CAP by adding the trade‑off between latency and consistency when there is no partition (
Elsecase).
Leave a comment