CAP and PACELC
As soon as data lives on more than one machine, the network between them can fail. The CAP theorem describes what a distributed data store can promise when that happens.
| Letter | Property | Meaning |
|---|---|---|
| C | Consistency (linearisability) | Every read sees the most recent successful write, as if there were one copy |
| A | Availability | Every request to a non-failed node gets a non-error response |
| P | Partition tolerance | The system keeps working even when messages between nodes are lost |
The theorem says that during a network partition you must choose between C and A. You can't "choose" to give up P: partitions happen whether you like it or not (a switch fails, a cable is cut, a GC pause makes a node look dead). So the real question is: when a partition happens, does the system refuse some requests (CP) or answer with possibly stale data (AP)?
partition
+-----+ X +-----+
| A |--X--| B | client writes x=2 to node A
+-----+ X +-----+ another client reads x from node B
x=2 x=1
CP choice: B refuses to answer (or A refuses the write) -> consistent, not available
AP choice: B answers x=1 -> available, not consistentA two-node model
The model below keeps a value on two replicas. Writes go to one node and are copied to the other only while the link is up. We flip a switch between CP and AP behaviour and watch what each client sees.
class Replica:
def __init__(self, name):
self.name, self.value, self.version = name, 0, 0
class Cluster:
def __init__(self, mode):
self.mode = mode # "CP" or "AP"
self.a, self.b = Replica("A"), Replica("B")
self.link_up = True
def write(self, node, value):
other = self.b if node is self.a else self.a
if not self.link_up and self.mode == "CP":
return "error: cannot reach peer, write refused"
node.value, node.version = value, node.version + 1
if self.link_up:
other.value, other.version = node.value, node.version
return f"ok (written on {node.name})"
def read(self, node):
if not self.link_up and self.mode == "CP":
return "error: cannot confirm latest value"
return f"{node.value} (from {node.name})"
for mode in ["CP", "AP"]:
c = Cluster(mode)
print(f"--- {mode} ---")
print("write 1 on A:", c.write(c.a, 1))
c.link_up = False # the partition starts
print("write 2 on A:", c.write(c.a, 2))
print("read on B: ", c.read(c.b))--- CP ---
write 1 on A: ok (written on A)
write 2 on A: error: cannot reach peer, write refused
read on B: error: cannot confirm latest value
--- AP ---
write 1 on A: ok (written on A)
write 2 on A: ok (written on A)
read on B: 1 (from B)
The CP cluster stays correct by returning errors; the AP cluster stays responsive but B serves the old value 1 while A already has 2. Neither is wrong; they suit different products.
Which one do I want?
| Use case | Usual choice | Why |
|---|---|---|
| Bank balance, inventory count, leader election, locks | CP | A wrong answer is worse than no answer |
| Shopping cart, social likes, DNS, product catalogue | AP | Being up matters more; small staleness is fine and can be repaired |
| Configuration store (etcd, ZooKeeper) | CP | Everyone must agree on the config |
| Session cache, view counters | AP | Losing or delaying a little data is acceptable |
Real systems are often tunable: Cassandra and DynamoDB let each request choose its consistency level; MongoDB and many SQL setups are CP by default.
PACELC: what about normal days?
CAP only talks about partitions, which are rare. PACELC extends it:
if Partition: choose Availability or Consistency (the CAP part)
Else: choose Latency or ConsistencyEven without failures, strong consistency costs latency, because a write must reach (or be confirmed by) other replicas before it is acknowledged. Some replicas are in other zones or regions, so this cost can be large:
replica_rtt_ms = {"same zone": 1, "other zone": 2, "other region": 70}
def write_latency(mode):
if mode == "async (EL)": # acknowledge after the local write
return 1
if mode == "quorum (2 of 3)": # wait for the fastest other replica
return 1 + sorted(replica_rtt_ms.values())[0]
if mode == "all replicas (EC)": # wait for every replica
return 1 + max(replica_rtt_ms.values())
for mode in ["async (EL)", "quorum (2 of 3)", "all replicas (EC)"]:
print(f"{mode:<20} write latency ~ {write_latency(mode):3} ms")async (EL) write latency ~ 1 ms
quorum (2 of 3) write latency ~ 2 ms
all replicas (EC) write latency ~ 71 ms
| System | PACELC class | Meaning |
|---|---|---|
| Cassandra, DynamoDB (default) | PA/EL | Available in a partition, low latency otherwise |
| Spanner, etcd, ZooKeeper | PC/EC | Consistent always, pays latency for it |
| MongoDB (default) | PA/EC | Prefers consistency normally, some availability under partition |
Probability of seeing stale data
An AP system with asynchronous replication is usually almost consistent. If replication takes a few milliseconds and reads are spread over replicas, only reads arriving right after a write see old data. A seeded simulation estimates how often:
import random
def stale_fraction(replication_lag_ms, n_reads=10_000, seed=42):
rng = random.Random(seed)
stale = 0
for _ in range(n_reads):
ms_since_write = rng.expovariate(1 / 200) # writes every ~200 ms on average
on_follower = rng.random() < 2 / 3 # 2 of 3 replicas are followers
if on_follower and ms_since_write < replication_lag_ms:
stale += 1
return stale / n_reads
for lag in [1, 10, 50, 200]:
print(f"replication lag {lag:3} ms -> {stale_fraction(lag):6.2%} of reads are stale")replication lag 1 ms -> 0.32% of reads are stale
replication lag 10 ms -> 2.89% of reads are stale
replication lag 50 ms -> 14.58% of reads are stale
replication lag 200 ms -> 41.34% of reads are stale
Small lag means rare staleness, but under load lag can grow to seconds. Design the product so stale reads are harmless, or route reads that must be fresh to the leader.
Note: "Consistency" in CAP means linearisability, which is different from the C in ACID (keeping database invariants). The next lesson covers the whole spectrum of consistency models.
Test yourself
According to CAP, what must a distributed store choose between during a network partition?
- Latency and throughput
- Consistency and availability
- Partition tolerance and durability
- SQL and NoSQL
What does the 'ELC' part of PACELC describe?
- Behaviour during a partition
- Else (no partition): the trade-off between latency and consistency
- Elastic load control
- Event log compaction
Which use case most clearly needs a CP system?
- A like counter
- A product catalogue
- A distributed lock for leader election
- A CDN