What CAP really says, an interactive 3-replica partition simulator, PACELC, the ladder of consistency models, quorums measured, and conflict resolution with CRDTs.
The moment your data lives on more than one machine, you inherit a problem that no amount of clever code can remove: the network between those machines can fail. When it does, each machine has to choose between answering with what it knows (which might be stale) or refusing to answer (which means downtime). That choice is the CAP theorem.
CAP is quoted constantly and misunderstood almost as often ("pick two of three!"). This tutorial explains what it really says, lets you break a cluster yourself in an interactive simulator, and then goes beyond CAP to the more useful question: which consistency model does my system actually give me, and is that good enough?
Prerequisites: none, but it helps to know what replication is. If you've read How a Database Works Inside, you know the write-ahead log, which is also what most databases ship to their replicas.
A single database server is simple and perfectly consistent: there's one copy of the truth. Teams replicate data across machines for three reasons:
| Reason | Example |
|---|---|
| Survive failures | A replica takes over when the primary's disk dies |
| Scale reads | Ten replicas serve ten times the read traffic |
| Be close to users | A replica in Singapore answers Asian users in 5 ms instead of 250 ms |
Every one of these means the same data exists in several places, and keeping the copies in agreement takes messages over a network. Networks drop packets, switches fail, cloud regions lose connectivity, and a GC pause can make a perfectly healthy node look dead for 30 seconds. Distributed systems engineers call all of these partitions: some nodes can't talk to some others.
The CAP theorem (Brewer's conjecture in 2000, proved by Gilbert and Lynch in 2002) uses precise definitions:
And the theorem: when a network partition happens, a system must give up either C or A.
during a partition, a replica that can't reach the others
receives a request. It has exactly two options:
┌─────────────────────────┐ ┌─────────────────────────┐
│ REFUSE (or wait) │ │ ANSWER with local data │
│ "I can't confirm I'm │ │ "here's what I have, │
│ up to date" │ │ it may be stale" │
│ │ │ │
│ keeps C, loses A → CP │ │ keeps A, loses C → AP │
└─────────────────────────┘ └─────────────────────────┘
You can't choose "CA". Partitions aren't a feature you opt out of; they happen to every distributed system. So the real choice is only ever between C and A, and only while a partition is happening. When the network is healthy, a well-built system can be both consistent and available.
A better summary: CAP says what you lose during a failure, not what you get the rest of the time.
Below are three replicas, A, B and C. Pick a mode, cut the network so C is isolated, then write and read through different nodes. Watch which requests fail, which return stale data, and what happens to your writes when the partition heals.
Try this sequence in each mode: cut the network, write via A, write via C, read via C, then heal.
That last point is the real cost of AP: availability during the partition, paid for with conflicts afterwards.
| System | During a partition | Typical use |
|---|---|---|
| etcd, ZooKeeper, Consul | CP: the minority side stops accepting writes (Raft/ZAB majority) | Kubernetes state, leader election, configuration, locks |
| PostgreSQL / MySQL primary with synchronous replica | CP: commits block if the sync replica is unreachable | Financial data, anything that can't lose commits |
| PostgreSQL / MySQL with async replicas | Primary stays available; replicas may serve stale reads; failover can lose the last commits | Most web applications |
| Cassandra, ScyllaDB, DynamoDB (default) | AP-leaning, with tunable quorums per request | High-write workloads, global availability |
| Google Spanner, CockroachDB | CP, with consensus per data range | Global SQL with strong consistency |
| DNS, CDNs, shopping carts | AP: serve something now, converge later | Read-heavy data where staleness is acceptable |
Most real systems aren't purely one or the other. Cassandra lets you choose per query. MongoDB's behaviour depends on read and write concern settings. The label matters less than knowing what your configuration does when a node can't reach the others.
Partitions are rare. What about the other 99.9% of the time? Daniel Abadi's PACELC extends CAP:
if Partition: choose Availability or Consistency (CAP)
Else: choose Latency or Consistency (the everyday trade-off)
Even with a perfect network, keeping replicas consistent means waiting for other machines. A synchronous write to a replica in another region adds a round trip, maybe 80 ms, to every commit. Skip the wait and you're fast, but a read from the replica right after a write might not see it.
| System | P: A or C? | E: L or C? |
|---|---|---|
| DynamoDB, Cassandra (default settings) | A | L: fast, eventually consistent |
| etcd, ZooKeeper, Spanner | C | C: every write waits for a majority |
| PostgreSQL with async replicas | (primary) C | L: replicas lag |
| MongoDB (majority write concern) | C | C |
For most applications, the E half matters more than the P half, because it's the trade-off you pay on every request.
"Consistent" is not one thing. There's a whole ladder of guarantees, from strongest to weakest. Stronger means easier to program against, and slower or less available.
STRONGER ┌───────────────────────────────────────────────────────────────┐
▲ │ Linearizable one global order matching real time; behaves │
│ │ like a single copy (etcd, Spanner) │
│ ├───────────────────────────────────────────────────────────────┤
│ │ Sequential one global order everyone agrees on, but it │
│ │ may lag real time │
│ ├───────────────────────────────────────────────────────────────┤
│ │ Causal if A could have influenced B, everyone sees A │
│ │ before B; unrelated writes may be seen in │
│ │ different orders │
│ ├───────────────────────────────────────────────────────────────┤
│ │ Session per-client promises: read-your-writes, │
│ │ guarantees monotonic reads, monotonic writes │
│ ├───────────────────────────────────────────────────────────────┤
▼ │ Eventual if writes stop, replicas eventually agree; │
WEAKER │ no promise about what you read meanwhile │
└───────────────────────────────────────────────────────────────┘
Once a write completes, every later read, from any client on any node, sees it (or something newer). It's what CP in CAP means, and what you need for locks, leader election, unique usernames, and "don't sell the last ticket twice".
Operations that are causally related appear in the same order for everyone. If Alice posts "I got the job!" and Bob replies "Congratulations!", no one should see Bob's reply without Alice's post. Unrelated posts can appear in different orders for different users. Causal consistency is the strongest model that stays available during partitions, which makes it attractive for geo-distributed apps.
These are the promises users actually notice:
| Guarantee | Violation the user sees |
|---|---|
| Read-your-writes | "I updated my profile photo, refreshed, and the old one came back." |
| Monotonic reads | "My comment appeared, then vanished on refresh, then came back." (Reads hit replicas with different lag) |
| Monotonic writes | "I changed my password twice and the first new password is the one that stuck." |
| Consistent prefix | "I saw the answer before the question." |
Session guarantees are often cheap to add on top of an eventually consistent system. To get read-your-writes, route a user's reads to the primary for a few seconds after they write, or remember the log position (LSN) of their last write and only read from replicas that have caught up to it.
The weakest useful promise: stop writing, wait, and all replicas converge. It says nothing about how long, or what you read meanwhile. It's often fine (likes, view counts, product recommendations), and occasionally a disaster (account balances, inventory).
Dynamo-style databases (Cassandra, Riak, ScyllaDB, DynamoDB internally) store each item on N replicas and let you choose per request:
If R + W > N, every read set overlaps every write set in at least one replica, so a read always sees the latest completed write:
N = 3 replicas: [ r1 ] [ r2 ] [ r3 ]
write, W = 2: [ v2 ] [ v2 ] [ v1 ] ← r3 hasn't received it yet
read, R = 2: [ v2 ] [ v1 ] ← any 2 replicas include at least one v2
→ return the newest: v2 ✓
This simulation writes to exactly W of N replicas and then reads from R random ones before background replication catches up, which is the worst case:
import random
def stale_rate(n, w, r, trials=100_000, seed=42):
"""Write version 1 to exactly W of N replicas (the rest still lag at version 0),
then read from R random replicas and return the highest version seen."""
rng = random.Random(seed)
stale = 0
for _ in range(trials):
replicas = [0] * n
for i in rng.sample(range(n), w):
replicas[i] = 1 # the write has reached these W replicas
seen = max(replicas[i] for i in rng.sample(range(n), r))
stale += seen == 0
return stale / trials
N W R R+W>N stale reads
3 1 1 no 66.5%
3 2 1 no 33.2%
3 1 2 no 33.4%
3 2 2 yes 0.0%
3 3 1 yes 0.0%
3 1 3 yes 0.0%
5 3 3 yes 0.0%
5 2 2 no 30.1%
The rule is exact: R + W > N gives zero stale reads; anything less gives a measurable fraction of them. In practice, background replication shrinks the window, so real stale rates for R = W = 1 are much lower than 66%. But they aren't zero, and they spike exactly when the system is under stress.
| Setting (N = 3) | Behaviour |
|---|---|
| W = 3, R = 1 | Fast reads, but any one node down blocks all writes |
| W = 1, R = 3 | Fast writes, but any one node down blocks reads that need all three |
| W = 2, R = 2 (QUORUM) | Tolerates one node down for both reads and writes. The usual choice |
| W = 1, R = 1 (ONE) | Fastest and most available, eventually consistent |
Warning: R + W > N is necessary but not quite sufficient for linearizability. Concurrent writes, "sloppy quorums" (writing to substitute nodes during failures) and clock-based conflict resolution can still produce anomalies. For true linearizability you need consensus, the subject of Consensus: Raft, Visualized.
AP systems accept writes on both sides of a partition, so after healing they must merge. The strategies, from crudest to smartest:
| Strategy | How it works | Risk |
|---|---|---|
| Last-writer-wins (LWW) | Keep the value with the highest timestamp | Silently loses acknowledged writes; clock skew can make an older write win |
| Version vectors + siblings | Detect concurrent writes and keep both; the application merges on read | Complexity is pushed onto the application |
| CRDTs | Data types whose merges always converge: counters, sets, maps, text | Not every invariant fits ("balance ≥ 0" can't be a CRDT) |
| Avoid conflicts | Route all writes for a key to one "home" region | That key is unavailable when its home is cut off |
The simulator above used LWW, and you watched it discard a write. Here's a tiny CRDT for comparison, a grow-only counter that merges without losing anything:
class GCounter:
"""Each replica increments only its own slot; merge takes the max per slot."""
def __init__(self, replica_id):
self.id, self.counts = replica_id, {}
def increment(self, n=1):
self.counts[self.id] = self.counts.get(self.id, 0) + n
def value(self):
return sum(self.counts.values())
def merge(self, other):
for rid, c in other.counts.items():
self.counts[rid] = max(self.counts.get(rid, 0), c)
a, c = GCounter("A"), GCounter("C")
a.increment(3) # 3 likes counted on A during the partition
c.increment(2) # 2 likes counted on C during the partition
a.merge(c); c.merge(a) # partition heals
print(a.value(), c.value()) # 5 5: no lost increments, same answer on both
Ask these questions about every piece of state in your system:
Then choose per data type, not per system. A typical e-commerce site uses a strongly consistent database for orders and payments, an eventually consistent cache for product pages, a CRDT-style counter for views, and a CP coordination service for leader election. That isn't inconsistent design. It's matching the guarantee to the cost of getting it wrong.
| Data | Sensible model |
|---|---|
| Payments, inventory, unique usernames | Linearizable (single primary or consensus) |
| User profile, settings | Read-your-writes on top of async replicas |
| Social feed, comments | Causal, or eventual with consistent prefix |
| Counters, likes, metrics | Eventual (CRDTs) |
| Leader election, locks, config | Linearizable (etcd / ZooKeeper) |
The one idea to keep: CAP isn't a menu you order from once. It's a reminder that during a network failure every replica must either wait or guess. Decide in advance, per piece of data, which one is the right failure.