FullStack AI Hub
Studio
System Design · 03. Data & Storage
11 min
10 steps
Intermediate

CAP & Consistency Models

Navigate network partitions, CP vs AP tradeoffs, Dynamo R + W > N quorums, and linearizable vs causal reads.

System Design03. Data & StorageLesson 6 of 11
11 minIntermediate10 steps

CAP & Consistency Models

Navigate network partitions, CP vs AP tradeoffs, Dynamo R + W > N quorums, and linearizable vs causal reads.

CONSISTENCY
Fresh
AVAILABILITY
100% (3/3)
WRITE P95
14 ms
PARTITION
None
3-REPLICA CLUSTER (N=3) · Healthy MeshApp ClientsRouter24%Replica 132%v=42Replica 232%v=42Replica 332%v=42
replicated write
quorum read
consistent ACK
stale / repair sync
partition / blocked
In This LessonStep 1 of 10
What You Will Master
  • ✓Explain why Network Partitions (P) are unavoidable and force a strict choice between CP and AP
  • ✓Tune Dynamo-style leaderless quorums (`R + W > N`) to balance read/write latency against staleness
  • ✓Heal divergent replicas cleanly using Read Repair, Hinted Handoff, and Merkle-tree Anti-Entropy
  • ✓Distinguish Linearizability, Causal Consistency, Read-Your-Writes, and Eventual Consistency

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
CP (Consistency over Availability)Distributed locks, leader election, and bank balances where split-brain writes cause corruptionMinority side of a network partition rejects writes (returns errors) until the link heals
AP (Availability over Consistency)Shopping carts, likes, DNS caches, and product catalogs where staying writable beats instant syncNodes diverge during a partition and require conflict resolution (LWW or CRDTs) afterward
Leaderless Quorums (`R + W > N`)Tunable multi-node stores (Cassandra/DynamoDB): `N=3, W=2, R=2` guarantees overlapping read/write setsSloppy quorums or clock skew can still expose brief stale reads without full linearizability
PACELC TheoremEveryday architecture decisions: even with NO partition (E), you still trade Latency (L) vs Consistency (C)Synchronous cross-region consistency adds speed-of-light RTT to every single write

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for CAP & Consistency Models.

STEP 01 · SETUPJump to step →

When the network is healthy, you get both C and A

Start with a 3-node replicated database cluster across three racks. When every network link is healthy, writes replicate quickly and reads return the exact latest value with 100% availability.

That’s why CAP is often misunderstood: you don’t "throw away Consistency" on normal days—**CAP only forces a binary choice the moment a Network Partition (P) cuts the cluster in two**.

idea:Network cables get cut, switches reboot, and GC pauses drop packets—in real distributed systems, Partition Tolerance (P) is mandatory, never optional.

CAP TheoremPACELCReplication Baseline
STEP 02 · PROBLEMJump to step →

A fiber cut hits: Replica 3 is partitioned from Replicas 1 & 2

A switch failure severs the link between **Replica 3 (EU)** and **Replicas 1 & 2 (US)**. Both sides are still alive and receiving user requests, but they **cannot talk to each other**.

Now a user in EU tries to write `price = $50` to isolated Replica 3. You face the fundamental CAP fork: **reject the write (CP)** or **accept it and diverge (AP)**?

watch:When Replica 3 cannot reach its peers, there is no magic third option: either it stops serving writes (sacrificing A) or it serves potentially divergent state (sacrificing C).

Network Partition (P)Split-Brain RiskMajority vs Minority
STEP 03 · TRADE-OFFJump to step →

CP vs AP in action: Bank Ledger (CP) vs Shopping Cart (AP)

A **CP system** (Raft, etcd, CockroachDB, Spanner) makes isolated Replica 3 **return `503 Unavailable`** so two conflicting balances can never exist. Integrity wins over uptime on the minority side.

An **AP system** (Dynamo, Cassandra `ONE`) lets Replica 3 **accept the shopper’s "Add to Cart"** locally—preserving 100% checkout availability and merging the two cart versions later using **CRDTs (add-wins set)**.

idea:Never classify an entire company as CP or AP—use CP for payments/inventory locks and AP for shopping carts, likes, and view counters.

CP (Safety First)AP (Uptime First)CRDT Conflict Merge
STEP 04 · SOLUTIONJump to step →

Tunable Consistency: Dynamo Quorums (R + W > N)

In leaderless clusters (`N = 3` replicas), you tune consistency per query using two knobs: **W** (how many replicas must ACK a write) and **R** (how many replicas you query on a read).

Whenever **`R + W > N`** (e.g., `N = 3, W = 2, R = 2`), the read set and write set are mathematically **guaranteed to overlap by at least 1 replica**—so the coordinator compares version numbers and returns the newest value!

idea:Pigeonhole principle in action: with `N=3, W=2, R=2`, at least one of the 2 replicas you read MUST hold the latest write—while still surviving any 1 dead node!

Quorum Formula (R + W > N)Pigeonhole OverlapTunable Consistency
STEP 05 · TECHNIQUEJump to step →

Healing stale nodes: Read Repair & Merkle-Tree Anti-Entropy

In the previous step, Replica 3 missed version `v=9` while rebooting. How does it catch up? Two complementary mechanisms keep leaderless replicas converged:

**(1) Read Repair**: When a quorum read sees Replica 2 has `v=9` and Replica 3 has `v=8`, the coordinator returns `v=9` to the user and asynchronously writes `v=9` back to Replica 3. **(2) Merkle Trees**: Background anti-entropy compares hash trees across peers to sync cold keys that nobody is reading.

idea:Read Repair heals hot keys on the fly; Merkle-Tree Anti-Entropy heals cold keys in the background with O(log N) network bandwidth.

Read RepairMerkle TreesAnti-Entropy Sync
STEP 06 · TRADE-OFFJump to step →

Sloppy Quorums & Hinted Handoff: maximum write uptime

What if 2 of a key’s 3 home replicas are unreachable at once? A **Strict Quorum** (`W=2`) rejects the write. A **Sloppy Quorum** writes temporarily to a healthy neighboring node (**Node 4**) with a **Hint** envelope saying *"Deliver to Node 3 when it returns."*

The trade-off: **Sloppy Quorums break strict `R + W > N` guarantees!** Until the hint replays back to Node 3, readers querying the home replicas won’t see the write.

watch:Sloppy Quorums optimize purely for write availability—never enable them if your application requires immediate read-after-write visibility.

Sloppy QuorumHinted HandoffStrict vs Tunable Availability
STEP 07 · TECHNIQUEJump to step →

Practical UX: Read-Your-Own-Writes & Monotonic Reads

Full global **Linearizability** is slow and expensive—yet raw Eventual Consistency feels terrible when a user updates their avatar, refreshes the page, and sees their *old* photo from a lagging read replica.

Fix the UX cleanly with **Read-Your-Writes** (route a user’s own reads to Primary for 5 seconds after they write, or pass a write LSN token) and **Monotonic Reads** (pin each user to one replica so time never appears to jump backward).

idea:Most consumer apps don’t need global linearizability—Read-Your-Own-Writes + Monotonic Reads feel 100% consistent to every human user at a fraction of the latency.

Read-Your-WritesMonotonic ReadsSession Consistency
STEP 08 · TECHNIQUEJump to step →

The Consistency Spectrum: Eventual → Causal → Linearizable

Consistency is a spectrum, not a binary switch. **Eventual Consistency** is fastest (local replica) but lets a reply appear before the original comment.

**Causal Consistency** (the strongest model still available during partitions!) tracks happens-before dependencies (Lamport/Vector clocks) so causes always precede effects. **Linearizability** (strict single-copy illusion via Raft/Spanner) is strongest—but requires cross-node consensus RTT on every operation.

idea:Pick the weakest consistency model that preserves your business invariant—stronger consistency always costs extra network round-trips and reduces partition uptime.

LinearizabilityCausal ConsistencyVector / Lamport Clocks
STEP 09 · TRADE-OFFJump to step →

PACELC in real life: the speed-of-light latency tax

Partitions are rare (<0.1% of the year), so why do systems still behave differently every single day? Daniel Abadi’s **PACELC** finishes CAP: *"If **P**, choose **A** or **C**; **E**lse (normal operation), choose **L**atency or **C**onsistency."*

Replicating synchronously from **US-East to Frankfurt (85 ms RTT)** guarantees global linearizability (PC/EC)—while replying locally in **6 ms** and replicating asynchronously (PA/EL) feels 14× snappier!

idea:PACELC explains real-world databases far better than CAP alone: Spanner is PC/EC, DynamoDB/Cassandra default to PA/EL, and MongoDB defaults to PC/EC with tunable read concerns.

PACELC TheoremPC/EC vs PA/ELCross-Region RTT
STEP 10 · RECAPJump to step →

Recap: mastering CAP, PACELC & Quorums

Distributed storage forces crystal-clear trade-offs: **CAP** governs behavior during rare network splits (CP safety vs AP uptime), while **PACELC** governs every normal request (Latency vs Consistency).

Use **`R + W > N`** strict quorums when you need overlap without a single leader, **Read Repair + Merkle Trees** to keep nodes converged, and **Session / Causal consistency** for snappy human UX.

idea:Interview cheat code: always state *both* CAP (partition behavior) and PACELC (normal latency vs consistency), then show `N=3, W=2, R=2` overlap math.

CAPPACELCR + W > N QuorumsCausal & Linearizable

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.