DS·70
CAP and PACELC
The CAP theorem stated precisely (Brewer's conjecture, Gilbert and Lynch's proof), what C, A and P actually mean, why "pick two of three" is misleading, what a system does during a partition (CP versus AP behaviour), PACELC's latency-versus-consistency trade-off in normal operation, classification of real databases with caveats, harvest and yield, and how to design for partitions per operation.
Start here: what happens when the network splits
The choice, demonstrated twice
A network partition splits machines into groups that can't reach each other, while each group keeps working and clients can still reach some of them. Nothing has crashed; messages just stop arriving. Each side must decide: keep serving requests (and risk disagreeing with the other side), or refuse (and stay correct).
etcd refuses on the minority side:
1) etcd, member 3 cut off from members 1 and 2:
write via member 1 (majority side): accepted
write via member 3 (minority side): refused (TimeoutError after 3.0 s)
A Redis primary with an asynchronous replica keeps serving on both sides, and then a failover makes it worse:
2) Redis primary and replica, link between them cut:
primary accepts a write: balance 1000 → 700
replica still answers reads: balance = 1000
replica promoted; new primary says 950 | old primary says 600
after healing, both say 950 and 950 -> the payments of 300 and 100 on the old primary are gone
During the split the replica served an old balance; after a failover there were two primaries accepting writes (split brain); when the old primary rejoined as a replica, it threw away its own writes and copied the new primary. Two payments vanished without an error anywhere.
The CAP theorem, stated properly
Eric Brewer's conjecture (2000), proved by Gilbert and Lynch (2002): a replicated system can't guarantee both Consistency (linearizability: every read sees the latest completed write) and Availability (every request to a non-failed node gets a non-error response) when there is a network Partition. Since partitions happen whether you like them or not, the real statement is: when a partition happens, each operation either waits/fails (CP) or answers possibly inconsistently (AP).
- CP behaviour: etcd, ZooKeeper, Consul, Spanner, CockroachDB, a single-primary PostgreSQL with synchronous replication. The minority side refuses.
- AP behaviour: Cassandra and DynamoDB at low consistency levels, Riak, CouchDB, DNS, caches, async replicas serving reads. Every side answers; conflicts are reconciled later.
"Pick two of three" is misleading: you don't give up P, you decide what to do when P happens, and you can decide per operation (the lab shows Redis refusing writes with min-replicas-to-write).
PACELC: the trade-off that exists every day
Daniel Abadi's extension: if Partition, choose A or C; Else (normal operation), choose Latency or Consistency. Waiting for replicas costs time even when nothing is broken:
Redis write, wait for 0 replica(s): median 0.12 ms
Redis write, wait for 1 replica(s): median 0.31 ms
Redis write, wait for 2 replica(s) (one 3 ms away): median 4.09 ms
Partitions are rare; latency is paid on every request. That's why many systems choose latency in normal operation (PA/EL: Cassandra, DynamoDB defaults) and others pay it for correctness (PC/EC: Spanner, etcd).
How deep to go in CAP and PACELC
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | State CAP correctly and explain partitions and split brain |
| L2 | Configure systems' partition behaviour: quorums, min replicas, fencing, failover settings |
| L3 | Classify systems with PACELC and caveats; explain harvest/yield and per-operation choices |
| L4 | Diagnose split brain, lost writes after failover, and unavailability during partitions |
| L5 | Design per-operation partition behaviour and failover for a system with explicit trade-offs |
| L6 | Run partition testing (game days, Jepsen) and set availability/consistency policy across platforms |
The CAP theorem
History and statement
Eric Brewer presented CAP as a conjecture at PODC 2000. Seth Gilbert and Nancy Lynch proved a formal version in 2002:
In an asynchronous network where messages can be lost, it's impossible for a read/write data store to guarantee both linearizable consistency and availability (every request to a non-failing node gets a non-error response) in the presence of network partitions.
Precise meanings in the theorem:
| Letter | Meaning in the proof | Not to be confused with |
|---|---|---|
| C: consistency | Linearizability of a single register (chapter 69) | The C in ACID (invariants), or "eventual consistency" |
| A: availability | Every request received by a non-failing node returns a (non-error) response, eventually, with no time bound | "99.99% uptime", or "a majority can still serve" |
| P: partition tolerance | The system keeps operating (doesn't violate C or A guarantees it claims) when the network drops arbitrary messages between nodes | A feature you can turn off |
The proof idea
Take two replicas, G1 and G2, partitioned so no messages pass. A client writes v1 to G1. For availability, G1 must acknowledge. A client then reads from G2. For availability, G2 must respond, but it has never heard of v1, so it returns the old value v0, violating linearizability. To preserve C, G2 would have to wait or refuse, violating A. That's the whole theorem: during a partition, a node cut off from the latest writes must either answer (possibly stale) or refuse/wait.
Why "pick two" is wrong
The roadmap's rule: do not reduce CAP to "you can only choose two." The slogan misleads in several ways (Brewer himself wrote "CAP Twelve Years Later" in 2012 to correct it):
- P isn't optional. In any system communicating over a network, partitions will happen (switch failures, misconfigured firewalls, GC pauses long enough to look like partitions, cloud zone isolation). A "CA" system is just one that hasn't decided what to do when partitions occur, or that's on a single node. So the real choice is C or A during a partition.
- The choice applies only during a partition. When the network is healthy, a system can be both consistent and available. Most of the time, there's no trade-off to make from CAP.
- The definitions are extreme. CAP's A means every non-failing node answers; CAP's C means linearizable. Real systems live between: a CP system (like etcd) stays available on the majority side of a partition; an AP system can still offer causal or session guarantees. "Not CAP-available" doesn't mean "down".
- The choice can be made per operation and per data item, not once per system. A shopping site can keep browsing and cart-adding AP while making checkout CP.
- CAP ignores latency. In practice, a slow response is often equivalent to unavailability. PACELC fixes this.
Martin Kleppmann (2015, "Please stop calling databases CP or AP") argues that most real systems are neither CAP-consistent nor CAP-available as defined, and that more precise vocabulary (consistency models, latency, fault models) works better. Use CAP as an intuition for partitions, not as a classification scheme.
What systems do during a partition
CP behaviour
A CP-leaning system refuses or delays operations it can't perform safely:
- Consensus-based stores (etcd, ZooKeeper, Consul, Raft-based databases such as CockroachDB, TiKV, YugabyteDB, Spanner): the majority side elects or keeps a leader and continues; the minority side can't commit writes or serve linearizable reads, and returns errors or times out.
- Kafka with
min.insync.replicas=2and unclean election disabled: partitions without enough in-sync replicas reject writes. - Single-leader SQL with synchronous replication: writes block if the synchronous replica is unreachable.
Consequence: clients on the minority side, or a region isolated from the majority, see errors. You need retries, fallbacks and good UX for "try again later".
AP behaviour
An AP-leaning system keeps accepting reads and writes on every side, and reconciles afterwards:
- Dynamo-style stores (Cassandra/ScyllaDB at consistency level ONE, Riak, DynamoDB global tables in default mode): each side accepts writes; after healing, anti-entropy (Merkle-tree repair), hinted handoff and read repair propagate them; conflicts are resolved by LWW, siblings, or CRDTs.
- DNS, CDN caches, shopping carts, offline-first mobile apps and local-first collaborative editors (CRDTs).
Consequence: stale reads and conflicts. You need conflict resolution that matches business rules, plus compensation for actions taken on stale data (chapter 73), such as an apology email for an oversold item.
Partition detection and recovery
Brewer's 2012 framing: a system should detect the partition (usually by timeout, so detection itself is uncertain), enter an explicit partition mode that limits some operations, and run partition recovery to restore consistency and compensate for mistakes.
| Phase | Decisions |
|---|---|
| Detect | Timeouts and failure detectors (chapter 77); detection is uncertain, so a slow node looks partitioned |
| Partition mode | Which operations continue (reads? low-risk writes?), which are refused, which are queued; record intent for later |
| Recovery | Merge state (CRDTs, version vectors, reconciliation jobs); fix invariant violations (refunds, oversell handling); notify humans |
Example: an ATM network. During a partition, ATMs may still allow withdrawals up to a limit (bounded risk: availability with a cap), and log them. After recovery, the bank reconciles and charges overdraft fees if needed. That's a business decision about acceptable risk, encoded in partition mode.
PACELC
Statement
Daniel Abadi (2010, published 2012) extended CAP to cover the normal case:
If there's a Partition, choose between Availability and Consistency; Else (normal operation), choose between Latency and Consistency.
The "else" half is the trade-off engineers face every day: even with a healthy network, stronger consistency costs round trips (wait for a quorum, wait for a remote leader, wait for commit-wait), which adds latency, especially across regions.
Classifying systems (with caveats)
| System (default config) | P → | E → | Notes |
|---|---|---|---|
| Cassandra / ScyllaDB (CL=ONE) | A | L | QUORUM reads + writes move it toward C at latency cost |
| DynamoDB (eventual reads) | A | L | Strongly consistent reads: EC within a region |
| Riak | A | L | Siblings or CRDTs for conflicts |
| MongoDB (w: majority, primary reads) | C | C | Secondary reads with local concern: EL |
| Spanner, CockroachDB, YugabyteDB | C | C | Follower/stale reads (AS OF SYSTEM TIME, bounded staleness) opt into EL per query |
| etcd, ZooKeeper, Consul | C | C | Serializable/stale read modes trade to EL |
| PostgreSQL + async replicas | C (primary) | L (replica reads) | A single primary is CP; replica reads are stale |
| Cosmos DB | Per level | Per level | Strong = PC/EC; eventual = PA/EL; session in between |
Most modern databases are tunable: the classification is per query, not per product. That's the practical lesson.
Latency as the everyday cost
Concrete numbers for a write that needs consensus across three regions (say Mumbai, Singapore, Frankfurt): the leader in Mumbai needs an ack from one other region for a majority of 3. The nearest is Singapore at about 60 ms RTT, so writes take at least ~60 ms plus processing. Reading linearizably from Frankfurt requires contacting the leader (about 120 ms RTT) unless leases or follower reads with timestamps are used. Techniques that reduce the cost:
- Place leaders near writers (per-partition leader placement; regional tables in CockroachDB, "home region" for rows).
- Follower reads at a slightly stale timestamp (Spanner stale reads, CockroachDB
follower_read_timestamp()): local latency, bounded staleness. - Leases for leader-local linearizable reads (relying on bounded clock drift).
- Asynchronous replication for non-critical data (PA/EL) and synchronous for critical data.
Beyond CAP
Harvest and yield
Fox and Brewer (1999) proposed thinking in degrees rather than absolutes:
- Yield: the fraction of requests answered successfully.
- Harvest: the fraction of the complete data reflected in an answer.
During failure, a search engine that loses one of 100 index shards can return results from 99 (99% harvest, 100% yield) rather than failing (0% yield). That's graceful degradation: decide which to sacrifice per feature. Recommendation widgets can drop harvest; checkout can't.
Related impossibility and trade-off results
- CALM theorem (Hellerstein and Alvaro): programs that are monotonic (only accumulate facts, never retract) can be computed consistently without coordination. Non-monotonic decisions ("is X absent?", "has everyone voted?", "is balance ≥ 0?") need coordination. That's a precise way to ask "does this operation need consensus?".
- Invariant confluence (Bailis et al.): an operation can run coordination-free if concurrent executions can't violate the invariant when merged. "Balance ≥ 0" with withdrawals isn't confluent (two withdrawals on different sides can overdraw); "IDs are unique" is confluent if IDs are generated with node prefixes.
- PRAM/causal impossibility bounds and latency lower bounds (Lipton and Sandberg; Attiya and Welch): linearizable operations need latency proportional to network delay. Physics, not engineering, sets the floor.
Designing with CAP and PACELC
- List operations and invariants: "seat can be sold once", "cart can be edited offline", "balance ≥ 0".
- For each, ask: what's the cost of a stale read or a conflicting write? An oversold seat costs a refund and an apology; double-spending a bank balance costs real money.
- Classify: invariants needing coordination (CP, consensus or a single leader); confluent/monotonic operations (AP, merge later).
- Define partition behaviour explicitly: errors with retry for CP operations; queue-and-reconcile for AP ones; limits for bounded risk.
- Define normal-case latency budgets and choose read modes (leader, follower, stale) per endpoint.
- Test partitions (Jepsen-style, chaos experiments with network faults), and verify the system behaves as you decided, not by accident.
// Java: per-operation choice with CockroachDB (via JDBC)
// Browsing: follower read, local latency, slightly stale (PA/EL-like behaviour within a CP database)
try (var st = conn.prepareStatement(
"SELECT name, price FROM products AS OF SYSTEM TIME follower_read_timestamp() WHERE id = ?")) { … }
// Checkout: serializable transaction on the leaseholder (PC/EC), retried on 40001 serialization failures
conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
# Python: Cassandra, choose per request
from cassandra import ConsistencyLevel
from cassandra.query import SimpleStatement
feed = SimpleStatement("SELECT * FROM timeline WHERE user_id=%s LIMIT 50",
consistency_level=ConsistencyLevel.ONE) # PA/EL: fastest, may be stale
claim = SimpleStatement("INSERT INTO usernames (name, user_id) VALUES (%s, %s) IF NOT EXISTS",
serial_consistency_level=ConsistencyLevel.LOCAL_SERIAL) # Paxos LWT: CP for this op
// Go: degrade gracefully (harvest over yield) when a shard is unreachable during a partition
results := make([]Result, 0, len(shards))
missing := 0
for r := range fanOut(ctx, shards, query) { // each with its own deadline
if r.Err != nil { missing++; continue }
results = append(results, r.Items...)
}
return SearchResponse{Items: results, Partial: missing > 0, MissingShards: missing} // tell the client
Lab: partitions on purpose
The 3-member etcd 3.6 cluster from chapter 69 (member 3 isolated with iptables), Redis 7 (one primary, one nearby replica, one replica behind a 3 ms Toxiproxy link), and a second Redis pair whose link Toxiproxy can silence in both directions. Python clients.
Experiment 1: the price of consistency with no partition (PACELC's "else")
1,000 Redis writes, each followed by WAIT n:
wait for 0 replica(s): median 0.12 ms, p99 0.55 ms
wait for 1 replica(s): median 0.31 ms, p99 1.42 ms
wait for 2 replica(s): median 4.09 ms, p99 5.26 ms
Waiting for the nearest replica tripled write latency; waiting for the far one multiplied it by 34. The cost is set by the slowest replica you wait for, which is why quorum systems wait for a majority (the fastest k of n), not all, and why cross-region synchronous replication is used sparingly.
Experiment 2: Redis choosing consistency over availability
Redis can refuse writes when it can't reach replicas: min-replicas-to-write 1, min-replicas-max-lag 2. The link to the only replica was silenced (packets dropped in both directions, no connection reset), and the client kept writing every 10 ms:
writes accepted for 1.7 s (154 writes), then refused with NOREPLICAS from 1.7 s
For a couple of seconds the primary couldn't know anything was wrong (the replica's last acknowledgement was still recent); once the replica's lag exceeded the limit, it refused writes. That bounds how much a split brain can lose to about max-lag seconds of writes, in exchange for availability. It's a per-system dial between AP and CP, and it's still not linearizable: the 154 writes in the window weren't replicated.
Experiment 3: each side of a follower partition
Member 3 cut off for 4 seconds while a client writes every 20 ms:
writes through the majority side (member 1): 174 of 174 succeeded
writes through the minority side (member 3): 0 of 2 succeeded
The majority didn't notice: it still had a quorum. The client stuck on member 3 got two 3-second timeouts. CP systems are available to clients that can reach a majority; good clients (etcd's, ZooKeeper's) try other endpoints when one stops answering, so a minority partition becomes a brief retry for them.
Experiment 4: partitioning the leader
Leadership moved to member 3, then member 3 cut off; a client hammered member 1 with 200 ms timeouts until a write succeeded. Five trials:
seconds until the majority accepted writes again: 1.41, 2.01, 1.62, 1.85, 1.81
Writes stopped for 1.4–2 seconds: the followers had to miss heartbeats for an election timeout (etcd's default is 1,000 ms, randomised so they don't all campaign at once), then elect a new leader. Meanwhile the old leader, alone, couldn't commit anything, so nothing was lost; this is the unavailability CAP promises for CP systems. Tuning shorter timeouts shortens the gap but risks needless elections on a slow network: etcd recommends heartbeat ≈ round-trip time and election timeout ≈ 10× that.
Try it yourself
- Add
--heartbeat-interval=50 --election-timeout=300to the etcd members and repeat experiment 4. - Repeat the on-ramp split brain with Redis Sentinel and
min-replicas-to-write 1on the primary. How many writes are lost now? - Put 50 ms of Toxiproxy latency between a client and a 3-node Cassandra (or ScyllaDB) cluster and compare
ONE,QUORUMandALLreads. - Write a "harvest and yield" degraded mode for a search page: when one shard is unreachable, return partial results with a banner instead of an error.
Revision sheet: CAP and PACELC
Key ideas
- CAP (Brewer 2000, Gilbert–Lynch 2002): under a partition, a system can't be both linearizable and available to every non-failed node.
- Precise terms: C = linearizability; A = every request to a live node eventually gets a non-error answer; P = arbitrary message loss between groups.
- Not "pick two": partitions aren't optional; the choice is per operation and only applies during partitions (Brewer's 2012 retrospective).
- CP: majority quorums (Raft, Paxos), minority sides refuse; AP: all sides answer, reconcile later (last-writer-wins, vector clocks, CRDTs, read repair).
- PACELC (Abadi 2010): else, latency vs consistency. PA/EL (Cassandra, DynamoDB defaults, Riak), PC/EC (Spanner, etcd, ZooKeeper, CockroachDB), PA/EC and PC/EL mixes exist (MongoDB defaults are often described as PA/EC).
- Beyond CAP: harvest and yield (Fox and Brewer), degraded modes, bounded staleness, fencing tokens to stop split brain.
- Failover is a CAP decision: promoting an async replica trades lost writes for availability.
Numbers to remember
- etcd default heartbeat 100 ms, election timeout 1,000 ms.
- Lab: waiting for a 3 ms replica took writes from 0.12 to 4.09 ms; Redis refused writes 1.7 s after its replica went silent; leader loss stopped writes for 1.4–2.0 s; minority-side writes 0 of 2.
Pitfalls
- Calling a single-node database "CA".
- Async failover without fencing (two primaries).
- Ignoring the everyday latency cost while debating partitions.
- Clients pinned to one endpoint, so a minority partition becomes an outage.
- Election timeouts shorter than real network jitter.
Glossary
- Partition: loss of communication between groups of nodes.
- Split brain: two nodes both acting as leader/primary.
- Quorum: a majority (or configured subset) whose agreement is required.
- Fencing token: increasing number that lets resources reject stale leaders.
- Harvest / yield: completeness of an answer / fraction of requests answered.