Consistency Models
A consistency model is a contract between a data store and its users: if you write this and then read that, which values may you see? Stronger models are easier to program against; weaker ones are faster and stay available during failures. Knowing the vocabulary lets you pick the weakest model your feature can safely live with.
The spectrum
| Model | Guarantee | Typical system |
|---|---|---|
| Linearizable (strong) | Every operation appears to happen at one instant between its start and end; reads see the latest write | etcd, ZooKeeper, Spanner, a single-leader DB read from the leader |
| Sequential | All clients see operations in the same order, consistent with each client's own order | Some replicated logs |
| Causal | If A could have caused B (B read A's result), everyone sees A before B; unrelated writes may appear in any order | MongoDB causal sessions, many CRDT systems |
| Read-your-writes | A client always sees its own writes | Session guarantees on top of replicas |
| Monotonic reads | A client never sees time go backwards (a newer value, then an older one) | Sticky replica per session |
| Eventual | If writes stop, all replicas converge to the same value eventually | DNS, Cassandra at ONE, caches |
Strong at the top, weak at the bottom. The middle "session guarantees" are often all a user-facing app really needs.
Eventual consistency in action
Writes go to a leader; followers apply them after a lag. A client that reads from a random replica may see old values, and even values that go backwards:
class Store:
def __init__(self, lag):
self.log = [] # (time, value) writes on the leader
self.lag = lag # each follower's replication delay
def write(self, t, value):
self.log.append((t, value))
def read(self, t, replica):
delay = self.lag[replica]
visible = [v for (wt, v) in self.log if wt + delay <= t]
return visible[-1] if visible else None
store = Store(lag={"leader": 0, "f1": 5, "f2": 12})
store.write(0, "v1")
store.write(10, "v2")
reads = [(12, "leader"), (14, "f2"), (16, "f1"), (20, "f2"), (45, "f2")]
for t, replica in reads:
print(f"t={t:2} read from {replica:<6} -> {store.read(t, replica)}")t=12 read from leader -> v2
t=14 read from f2 -> v1
t=16 read from f1 -> v2
t=20 read from f2 -> v1
t=45 read from f2 -> v2
The client saw v2, then v1, then v2 again: this violates monotonic reads. By t=45 every replica has caught up, which is all eventual consistency promises.
Adding session guarantees
A common fix is to remember, per client session, the newest version it has seen (or written). A replica may only serve the read if it has caught up to that version; otherwise the request goes to the leader or another replica.
class Store:
def __init__(self, lag):
self.log, self.lag = [], lag
def write(self, t, value):
self.log.append((t, value))
return len(self.log) # version number
def version_at(self, t, replica):
return sum(1 for (wt, _) in self.log if wt + self.lag[replica] <= t)
class Session:
def __init__(self, store):
self.store, self.seen = store, 0
def write(self, t, value):
self.seen = self.store.write(t, value)
def read(self, t, preferred):
replica = preferred
if self.store.version_at(t, replica) < self.seen:
replica = "leader" # replica too stale for this session
version = self.store.version_at(t, replica)
self.seen = max(self.seen, version)
return self.store.log[version - 1][1], replica
store = Store(lag={"leader": 0, "f1": 5, "f2": 12})
alice = Session(store)
alice.write(0, "profile v1")
alice.write(10, "profile v2")
for t, replica in [(12, "f2"), (14, "f1"), (16, "f1"), (45, "f2")]:
value, served_by = alice.read(t, replica)
print(f"t={t:2} wanted {replica} -> {value!r} served by {served_by}")t=12 wanted f2 -> 'profile v2' served by leader
t=14 wanted f1 -> 'profile v2' served by leader
t=16 wanted f1 -> 'profile v2' served by f1
t=45 wanted f2 -> 'profile v2' served by f2
Alice always sees her latest profile (read-your-writes) and never goes backwards (monotonic reads). The leader only takes the reads that followers can't safely serve.
Causal consistency
Causality matters for conversations. If Bob replies "Congrats!" after reading Alice's "I got the job", nobody should see the reply without the original post. Systems track causality with version vectors: each write carries the versions it depended on, and a replica delays showing a write until its dependencies arrived.
def deliver(arrival_order):
applied, waiting, shown = set(), [], []
for msg_id, depends_on in arrival_order:
waiting.append((msg_id, depends_on))
progress = True
while progress: # apply everything whose deps are present
progress = False
for item in list(waiting):
mid, deps = item
if deps <= applied:
applied.add(mid)
shown.append(mid)
waiting.remove(item)
progress = True
return shown
# The reply arrives before the post it answers (network reordering)
arrivals = [("bob: Congrats!", {"alice: I got the job"}),
("carol: hi all", set()),
("alice: I got the job", set())]
print("arrival order:", [m for m, _ in arrivals])
print("shown order: ", deliver(arrivals))arrival order: ['bob: Congrats!', 'carol: hi all', 'alice: I got the job']
shown order: ['carol: hi all', 'alice: I got the job', 'bob: Congrats!']
Carol's unrelated message shows immediately, while Bob's reply waits for Alice's post.
Choosing a model
- Money movements, unique usernames, locks: linearizable.
- A user editing their own data: read-your-writes at least.
- Comments, chats, collaborative edits: causal.
- Counters, feeds, recommendations, analytics: eventual is usually fine.
Tip: Write the consistency requirement per feature, not per system. One app can use a strongly consistent store for payments and an eventually consistent one for likes.
Test yourself
A user updates their profile and immediately reloads the page, but sees the old profile. Which guarantee is missing?
- Monotonic reads
- Read-your-writes
- Linearizability of other users
- Partition tolerance
What does eventual consistency guarantee?
- Reads always return the latest write
- Replicas converge to the same value if writes stop
- Writes are never lost
- Operations happen in real-time order
In the causal delivery model, why was Bob's reply delayed?
- It was larger than other messages
- Its dependency (Alice's post) had not arrived yet
- Bob has a slow connection
- Messages are sorted alphabetically