Consistency models from linearizable to eventual
What a consistency model promises, read from small histories of reads and writes: linearizable, sequential, causal, read-your-writes, monotonic reads and eventual consistency, what each costs, how a script can check a history, and why none of them is the same thing as a transaction isolation level.
Contentsand lesson path
On this page
- Why it matters
- Reading a history
- Linearizable and sequential: one copy, with or without real time
- Causal consistency
- Session guarantees and eventual consistency
- Consistency models are not isolation levels
- Choosing a model per operation
- Check your understanding
- Apply it
- Review prompt
Lessons of Distributed Systems Fundamentals
- Partial failure and the fallacies of distributed computing Concept · 20 min
- Time, clocks and ordering Concept · 20 min
- Consistency models from linearizable to eventual Concept · 25 min
- CAP and PACELC applied to real databases Worked example · 20 min
- Quorums, Raft and leader leases, step by step Lab · 25 min
- Distributed reasoning check Knowledge check · 8 questions
What you will learn
- Place a design on the consistency spectrum (linearizable, sequential, causal, read-your-writes, eventual) and explain the trade-offs with CAP and PACELC.
01. Why it matters
Ask a team whether their replicated store is "consistent" and you will get a yes or a no. Neither answer helps. Imagine a theatre booking app. Reserving seat 14C must never succeed for two people. The "my bookings" page must show a booking the user just made. The "popular tonight" list can be a minute old. These are three different promises, and a store can keep one while breaking another.
A consistency model is a precise contract about which results reads may return, given the writes that happened. A stronger model allows fewer surprising results and usually needs more coordination between replicas, which costs latency and, during a partition, availability. This lesson walks down the spectrum from the strongest common model to the weakest, using small histories that a script checks for you.
02. Reading a history
A history records operations on a shared value as clients saw them: who did what, when each operation started and when it returned. Two operations whose time intervals overlap are concurrent: either may take effect first. A model is a rule that says whether a history is allowed.
The script below holds five tiny histories of one register x, which starts at 0. For each model it tries every possible order of the operations and asks whether some order obeys the model's rule while every read returns the value that a single copy of x would hold. Brute force is fine for four operations; real checkers such as Jepsen's need cleverer search. Predict the five rows before you run it.
"""Check tiny histories of one register x against four consistency models.
An operation is (client, kind, value, start, end): kind "w" writes value,
kind "r" read value. Times are in ms. x starts at 0.
Simplification: every write stores a bigger number than all earlier writes,
so for the session checks "newer" simply means "bigger".
"""
from itertools import permutations
def legal(order) -> bool:
"""Do the reads in this order return what a single copy of x would hold?"""
x = 0
for _client, kind, value, _s, _e in order:
if kind == "w":
x = value
elif value != x:
return False
return True
def linearizable(history) -> bool:
"""Some legal order in which an op that ended earlier comes first."""
for order in permutations(history):
pos = {op: i for i, op in enumerate(order)}
if legal(order) and all(pos[a] < pos[b] for a in history
for b in history if a[4] < b[3]):
return True
return False
def sequential(history) -> bool:
"""Some legal order that keeps each client's own operations in order."""
for order in permutations(history):
pos = {op: i for i, op in enumerate(order)}
if legal(order) and all(pos[a] < pos[b] for a in history
for b in history if a[0] == b[0] and a[4] < b[3]):
return True
return False
def read_your_writes(history) -> bool:
return all(r[2] >= w[2] for w in history for r in history
if w[1] == "w" and r[1] == "r" and w[0] == r[0] and w[4] < r[3])
def monotonic_reads(history) -> bool:
return all(r2[2] >= r1[2] for r1 in history for r2 in history
if r1[1] == r2[1] == "r" and r1[0] == r2[0] and r1[4] < r2[3])
HISTORIES = {
"H1 Q reads old x after P's write ended": [
("P", "w", 1, 0, 10), ("Q", "r", 0, 20, 25)],
"H2 P reads old x after its own write": [
("P", "w", 1, 0, 10), ("P", "r", 0, 20, 25)],
"H3 Q sees x go from 2 back to 1": [
("P", "w", 1, 0, 10), ("P", "w", 2, 12, 18),
("Q", "r", 2, 20, 22), ("Q", "r", 1, 30, 32)],
"H4 Q reads new x, then R reads old x": [
("P", "w", 1, 0, 30), ("Q", "r", 1, 5, 10), ("R", "r", 0, 12, 15)],
"H5 reads overlap a slow write": [
("P", "w", 1, 0, 30), ("Q", "r", 0, 5, 10), ("R", "r", 1, 12, 15)],
}
CHECKS = [("linearizable", linearizable), ("sequential", sequential),
("RYW", read_your_writes), ("MR", monotonic_reads)]
WIDTHS = [14, 12, 5, 5]
print(f"{'history':38}" + "".join(
f"{name:>{w}}" for (name, _), w in zip(CHECKS, WIDTHS)))
for label, history in HISTORIES.items():
marks = ["yes" if check(history) else "NO" for _, check in CHECKS]
print(f"{label:38}" + "".join(f"{m:>{w}}" for m, w in zip(marks, WIDTHS)))history linearizable sequential RYW MR
H1 Q reads old x after P's write ended NO yes yes yes
H2 P reads old x after its own write NO NO NO yes
H3 Q sees x go from 2 back to 1 NO NO yes NO
H4 Q reads new x, then R reads old x NO yes yes yes
H5 reads overlap a slow write yes yes yes yes03. Linearizable and sequential: one copy, with or without real time
Linearizability is the strongest common model for a single object. The operations must fit into one total order that respects real time (if A returned before B started, A comes first), and every read returns the latest write in that order. To clients, the store behaves as if there were one copy and each operation took effect at an instant between its start and its end.
H5 is linearizable: the slow write overlaps both reads, so it can take effect between them, and Q seeing 0 then R seeing 1 is exactly what one copy would show. H1 is not: Q started reading after P's write had returned, yet saw 0. H4 is not either, and it is the subtle one: Q already saw the new value, and R, starting later, saw the old one. No single copy can go back like that.
Sequential consistency, defined by Lamport in 1979, keeps the single total order and each client's own order but drops real time. H1 and H4 are sequential, because some order puts the stale read before the write. Real time matters as soon as clients can talk outside the store. If P tells Q "done" by chat, or one service calls another after its write, a sequentially consistent store may still show Q the old value.
Both models have a price. The Jepsen consistency reference notes that neither can be totally available or even sticky available: during a partition, some nodes must refuse or wait instead of answering. Use them where a stale answer is a real bug: claiming a seat or a username, electing a leader, taking a lock, or any compare-and-set.
04. Causal consistency
Causal consistency uses the happened-before relation from lesson 2. Operations that are causally related must be seen in that order by everyone; concurrent ones may appear in different orders to different readers. A write counts as caused by everything its writer had read or written before it.
Picture a team chat. Ola posts "the build is broken". Pat reads it and replies "fixed it". Meanwhile Kim, who has seen neither, posts "lunch at noon". Causal consistency forbids any reader from seeing "fixed it" without "the build is broken". It allows one reader to see Kim's post first and another to see it last, because it is concurrent with both.
Causal consistency is sticky available: during a partition every client can keep reading and writing, provided it keeps talking to the same server. That makes it attractive for apps whose users must not see effects before causes but can live with concurrent updates arriving in different orders.
05. Session guarantees and eventual consistency
Some promises are made to one client, or session, rather than to everybody:
- Read-your-writes: after a client writes, its own later reads reflect the write. H2 breaks it: P could not see its own write. Other clients get no such promise.
- Monotonic reads: a client's reads never go back in time. H3 breaks it: Q saw 2 and then 1, as can happen when successive reads land on replicas with different lag.
- Monotonic writes and writes-follow-reads are the two siblings: a client's writes apply in order, and a write lands after the writes its author had read.
These guarantees are defined by the session, not by a time window. "Read from the leader for five seconds after a write" is one way to approximate read-your-writes, and it fails when lag exceeds five seconds. Sturdier ways are to keep a session on one replica, or to have the client remember the version, such as a log position, of its last write or read, and let a replica answer only once it has caught up to that version. You measured the lag these protect against in Observing replication lag with a read replica.
Eventual consistency is the weakest common promise: if writes stop, all replicas eventually hold the same value. It says nothing about what reads return in the meantime, and convergence still needs a rule for concurrent writes, such as last-write-wins or a merge (lesson 2). Monotonic reads can be kept even during a partition (totally available); read-your-writes needs sticky sessions. That is why eventual stores often add session guarantees on top.
06. Consistency models are not isolation levels
Database isolation levels such as READ COMMITTED and SERIALIZABLE answer a different question: how may concurrent transactions, each touching many objects, interleave? See How MVCC gives each transaction its own snapshot. Linearizability is about single operations on one object, and about real time.
Serializability requires that transactions appear to run in some total order, but not one that matches the clock. The Jepsen reference points out that if one process finishes a write and another process then starts a read, a serializable system may still let the read miss the write. Strict serializability adds the real-time rule; it is serializability plus linearizability. So "our database is SERIALIZABLE" does not tell you whether a read is fresh: also ask where reads are served and what the store promises about recency.
07. Choosing a model per operation
Go back to the theatre. Reserving a seat needs linearizability for that seat, usually a conditional write or a transaction on the leader. "My bookings" needs read-your-writes, and monotonic reads so a refresh never hides a booking it showed a moment ago. "Popular tonight" can be eventually consistent. Paying for the strongest model everywhere would make every page read wait for coordination; paying for the weakest everywhere would sell seat 14C twice.
Do not choose linearizable reads for high-volume pages where data a few seconds old is harmless, or for users spread across regions when every read would then pay a cross-region round trip. Lesson 4 puts numbers on that trade-off with CAP and PACELC.
08. Check your understanding
09. Apply it
For each store on your guarantee sheet, list its main operations and write the consistency model each one gets with the settings you would use, and the model it needs. Mark every operation where the two differ. Then add a sixth history to histories.py in which a client reads 1, then 0, from two replicas, predict all four columns, and run it.
10. Review prompt
Without looking back:
- What does linearizability add to sequential consistency, and why does it matter when clients talk outside the store?
- Give an example that causal consistency forbids and one it allows.
- Define read-your-writes and monotonic reads, and name two ways to provide them.
- What does eventual consistency promise, and what does it leave out?
- Why is SERIALIZABLE isolation not a promise that reads are fresh?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.