Sub topic 7
Consistency Models and the CAP/PACELC Trade-offs
This chapter covers what "consistent" can mean for a replicated key-value store, and why the choice costs availability or latency. It assumes you know how keys are partitioned and how each key is replicated to N nodes on a preference list, as covered in the previous chapters. It also assumes you can read short Python snippets. The next chapter turns these trade-offs into concrete read and write quorum settings.
Why replication forces a choice
Once a key lives on several nodes, those copies can disagree. A write reaches some replicas before others. A replica can be down or cut off by the network. A client can read from a replica that has not seen the latest write.
A consistency model is a contract. It says which values a read is allowed to return, given the writes that came before it. Stronger contracts are easier to program against. They also require more coordination between replicas, and coordination costs time and availability.
The consistency spectrum
Consistency models form a spectrum. These are the ones you will meet most often in key-value stores.
| Model | What a read may return | Typical cost |
|---|---|---|
| Linearizable (strong) | The latest completed write, as if there were one copy | Coordination on every operation, unavailable on some partitions |
| Sequential | Operations appear in one global order that respects each client's own order, but not real time | Still needs global ordering |
| Causal | Effects never appear before their causes | Dependency tracking, such as vector clocks |
| Read-your-writes, monotonic reads | A client sees its own writes and never sees time go backward | Session stickiness or version tracking |
| Eventual | Any past value, but replicas converge if writes stop | Lowest latency, highest availability |
Linearizability
Linearizability makes a replicated register behave like a single copy. Each operation takes effect at one instant between its start and its end. After a write returns, every later read, from any client, sees that write or a newer one.
This is what most people mean by "strong consistency". It is needed for things like locks, unique-username checks, and leader election. It is usually implemented with a leader or a consensus protocol, which later chapters cover.
Causal consistency
Causal consistency keeps cause before effect. If you read a post and then write a reply, nobody should see the reply without the post. Writes with no causal link may appear in different orders on different replicas.
A store can offer this without blocking on a partition, because it only has to track dependencies. This is why vector clocks, covered later, matter.
Session guarantees
Session guarantees are weaker, cheaper promises made to one client:
- Read-your-writes: after you write a value, your reads see it or something newer.
- Monotonic reads: once you have seen a value, you never see an older one.
You can often provide these by pinning a client to a replica or by passing a version token between requests.
Eventual consistency
Eventual consistency promises only convergence. If writes stop and the network heals, all replicas end up with the same value. It says nothing about what a read returns before then. Most Dynamo-style stores default to this model and let you tighten it per request.
The CAP theorem
CAP describes what a replicated system can promise during a network partition. A partition is a failure in which some nodes cannot talk to others. The three letters are:
- Consistency: here it means linearizability, not the "C" in database ACID.
- Availability: every request to a non-failed node gets a non-error response.
- Partition tolerance: the system keeps working when messages between nodes are lost.
Real networks do partition, so you cannot opt out of P. The theorem therefore reduces to a choice made at the moment of a partition: refuse some requests to stay consistent, or answer every request and risk stale or divergent data.
What CP and AP look like in practice
A CP store requires a majority of replicas to agree before it answers. The side of a partition holding a minority cannot make progress, so clients there see errors or timeouts. Systems built on Raft or Paxos behave this way.
An AP store accepts reads and writes on both sides of the partition. Both sides keep working, and conflicting writes must be reconciled later with versioning and conflict resolution. This is the Dynamo approach.
Limits of CAP
CAP is often misused, so keep these points in mind:
- It is a statement about the partition case only. It says nothing about how the system behaves when the network is healthy.
- "Availability" in the theorem is strict: every non-failed node must answer. A real service may count "mostly available" as enough.
- A system is not simply "CP" or "AP". Many stores let you choose per request.
- Consistency here means linearizability. Weaker models, like causal, can remain available during a partition.
PACELC: the trade-off with no failure
Partitions are rare. Latency is a cost you pay on every request. PACELC extends CAP to cover that normal case. It reads: if there is a Partition, choose between Availability and Consistency. Else, choose between Latency and Consistency.
The "else" half is where most of the daily cost lives. To give a strongly consistent read, a replica must confirm it holds the latest data, often by contacting other replicas, perhaps in other data centers. That round trip is added latency. Reading only the local copy is fast but may be stale.
| System style | During a partition | Normal operation | PACELC label |
|---|---|---|---|
| Dynamo-style, default settings | Stay available | Favor low latency | PA/EL |
| Consensus-replicated store (Raft, Paxos) | Favor consistency | Favor consistency | PC/EC |
| Leader-based store with async replicas | Favor consistency on the leader side | Favor low latency on replica reads | PC/EL |
These labels describe default behavior. Many systems can be configured to move between them.
Seeing staleness in code
This small simulation shows the "else" trade-off. Three replicas hold a value. A write is acknowledged after reaching one replica, and the others catch up later. Reading one replica can return stale data.
import random
replicas = [{"v": 1}, {"v": 1}, {"v": 1}]
def write_one(value: int) -> None:
"""Acknowledge after updating only one replica (fast, weak)."""
replicas[0]["v"] = value
def replicate_async() -> None:
"""Background propagation copies replica 0 to the others."""
for r in replicas[1:]:
r["v"] = replicas[0]["v"]
def read_any() -> int:
"""Read one random replica (fast, may be stale)."""
return random.choice(replicas)["v"]
def read_all_latest() -> int:
"""Ask every replica and take the highest version (slower, fresher)."""
return max(r["v"] for r in replicas)
write_one(2)
print("stale read possible:", read_any()) # 1 or 2
print("read all replicas:", read_all_latest()) # always 2
replicate_async()
print("after convergence:", read_any()) # always 2The fast path (write_one plus read_any) trades consistency for latency. The slow path (read_all_latest) trades latency for freshness. Real systems make this same choice with quorum sizes, which the next chapter covers.
Common errors when applying these ideas
- Calling a system "CP" or "AP" without saying what happens to reads versus writes. A store can reject writes during a partition and still serve stale reads.
- Treating eventual consistency as "no guarantees". Convergence is a guarantee, and you can add session guarantees on top.
- Assuming a majority quorum alone gives linearizability. Overlapping quorums are necessary but not sufficient, because concurrent writes, sloppy quorums, and clock-based conflict resolution can still return old or lost values.
- Ignoring the latency half of the trade-off. Cross-region strong reads can cost tens to hundreds of milliseconds each.
- Using wall-clock timestamps to order writes across nodes. Clocks drift, so a later write can carry an earlier timestamp.
Choosing for your key-value store
Use these questions to pick a default:
- What is the cost of a stale read? A wrong "likes" count is harmless. A stale account balance is not.
- What is the cost of rejecting a request? If users must always be able to write, favor availability.
- Are replicas in one data center or several? Across regions, PACELC's latency cost grows.
- Can the application merge conflicts? If yes, an AP design with versioning works. If not, prefer a leader or consensus.
The design in this tutorial starts from the AP, low-latency end. It then adds quorums so that callers can move along the spectrum per request.
Exercise
A three-replica store keeps working on both sides of a partition and accepts writes on each side. After the partition heals, two replicas hold different values for the same key. Using CAP and PACELC, classify this store's behavior during the partition and in normal operation, and name one consistency model it can still offer during the partition.
Show answer
During the partition it chose availability over consistency (the A in PA). Its writes were accepted on both sides, so reads are not linearizable and values can diverge. In normal operation, if it answers from one replica without coordinating, it favors latency over consistency (EL), giving PA/EL. During the partition it can still offer weaker models such as eventual consistency, read-your-writes through session pinning, or causal consistency if it tracks dependencies, because none of these require a majority to be reachable.
Exercise
Why does a strongly consistent read cost latency even when no partition exists?
Show answer
To guarantee the latest value, the serving replica must confirm with a leader or a quorum of other replicas that it has not missed a newer write. That confirmation needs at least one network round trip, which is extra latency on every read. This is the "else" part of PACELC.