You change your profile name on a social app, refresh the page, and the old name is back. Refresh again and the new one appears. Nothing is broken, and no data was lost. You just read from a copy of the data that had not caught up yet.
In the Database Replication chapter we saw why this happens: replicas receive changes a little late. In the CAP Theorem & PACELC chapter we saw that "C" is something you sometimes trade for availability or latency. But "consistent or not" is too coarse. Between "every read sees the latest write" and "reads will catch up eventually" there is a whole ladder of guarantees, and real databases sit at different steps of it.
This chapter climbs that ladder. For each consistency model you will learn what it promises, what it forbids, what it costs, and which real systems give it.
stronger, slower, needs coordination
▲ Linearizable (strong)
│ Sequential
│ Causal
│ Session guarantees (read-your-writes, monotonic reads ...)
▼ Eventual
weaker, faster, stays available
What Is a Consistency Model?
A consistency model is a contract between a data store and the programs that use it. It states which values a read is allowed to return, given the writes that happened before and in parallel with it.
On one machine with one copy of the data, the contract is obvious: a read returns the last value written. Once the data is copied to several machines (for availability and speed), "the last value" becomes fuzzy. Which copy? Last according to whose clock? A consistency model removes the fuzziness by stating the rules precisely.
Why does a system designer care?
Correctness. A bank balance, a seat booking, or a unique username needs a strong guarantee. Showing a slightly old like count does not.
Cost. Stronger models need replicas to coordinate before answering. That adds network round trips (latency) and makes the system refuse requests during a network partition (lower availability).
Programming effort. With weak models, the application code must handle stale or out-of-order data itself.
The vocabulary: operations and histories
To compare models we look at a history: a list of operations, each with the client (process) that issued it, a start time (request sent) and an end time (response received). We use a single variable x that starts at 0.
time ──────────────────────────────────────────────→
P1: |──── W(x=1) ────|
P2: |── R(x)=? ──| (overlaps the write)
P3: |── R(x)=? ──| (starts after the write ended)
Two operations either overlap (they are concurrent) or one finishes before the other starts (they are ordered in real time). Keep this picture in mind; every model below is a rule about which values the two reads may return.
Linearizability (Strong Consistency)
Linearizability: every operation appears to take effect at a single instant (its linearization point) somewhere between its start and its end, and all clients see the operations in the order of those instants. In effect, the system behaves as if there were only one copy of the data.
Linearizability was defined by Herlihy and Wing in 1990. When people say "strong consistency" in system design, they usually mean this.
Apply it to the picture above:
P2 overlaps the write, so it may return 0 or 1. Both are fine, because the write's instant could fall before or after the read's instant.
P3 starts after the write has finished. It must return 1. Returning 0 would mean travelling back in time.
Once any client has read 1, no client may later read 0. There is no "flickering" between old and new values.
Linearizable NOT linearizable
P1: |── W(x=1) ──| P1: |── W(x=1) ──|
P2: |R=1| P2: |R=1|
P3: |R=1| P3: |R=0| ✗ stale after a newer read
What it costs
To promise "one copy" behaviour with several replicas, a write must reach a majority (or all) before it is acknowledged, and a read must confirm it is not looking at an out-of-date copy. In practice this is done with a consensus protocol such as Raft or Paxos, or with a single leader that serves all reads and writes.
Latency: at least one round trip to a majority on each write. Across continents that is 100+ ms.
Availability: a replica cut off from the majority must refuse requests. This is exactly the "CP" choice from the CAP chapter.
Where you need it
Leader election and distributed locks (only one leader at a time).
Uniqueness constraints: one username, one seat, one coupon redemption.
Money movements and inventory counts that must never go negative.
Real systems: etcd (used by Kubernetes) gives linearizable reads and writes by default. ZooKeeper orders writes linearizably, but a plain read can be served by a lagging server; a client calls sync first if it needs the latest value. Google Spanner provides external consistency, a transactional guarantee at least as strong as linearizability, using its TrueTime clocks.
Sequential Consistency
Sequential consistency: the result is the same as if all operations ran in some single order, and the operations of each individual client appear in that order in the sequence that client issued them. (Lamport, 1979.)
Compare it with linearizability: both require one global order that everybody agrees on. The difference is that sequential consistency does not require the order to respect real time across different clients. A read that starts after another client's write has finished may still be placed before that write, as long as every client's own operations stay in program order.
Think of a WhatsApp group where every member sees the messages in the same order, but the whole conversation may be shown a few seconds late. Same order for everyone, but not necessarily "now".
Worked Example: Checking a History
Let us make the definitions precise with code. The program below tries every possible ordering of a small history and asks two questions: does some legal order respect each client's program order (sequential), and does some legal order also respect real time (linearizable)? "Legal" means each read returns the most recent write before it in that order.
from itertools import permutations
# Each operation: (name, process, kind, value, start, end)
# kind "w" writes value; kind "r" read returned value.
def legal(order):
reg = 0 # register starts at 0
for op in order:
if op[2] == "w":
reg = op[3]
elif op[3] != reg:
return False
return True
def respects_realtime(order):
pos = {op[0]: i for i, op in enumerate(order)}
return all(pos[a[0]] < pos[b[0]]
for a in order for b in order if a[5] < b[4]) # a ended before b began
def respects_program_order(order):
last = {}
for op in order:
p = op[1]
if p in last and last[p] > op[4]:
return False
last[p] = op[4]
return True
def check(history):
lin = seq = None
for order in permutations(history):
if not legal(order):
continue
if respects_program_order(order):
seq = seq or order
if respects_realtime(order):
lin = lin or order
show = lambda o: " -> ".join(op[0] for op in o) if o else "impossible"
print(" sequential :", show(seq))
print(" linearizable:", show(lin))
print("History A (read overlaps the write):")
check([("W(x=1)", "P1", "w", 1, 0, 10),
("R()=1", "P2", "r", 1, 5, 8)])
print("History B (stale read after the write finished):")
check([("W(x=1)", "P1", "w", 1, 0, 4),
("R()=0", "P2", "r", 0, 6, 8)])
print("History C (same process reads its own old value):")
check([("W(x=1)", "P1", "w", 1, 0, 2),
("R()=0", "P1", "r", 0, 3, 4)])
Output:
History A (read overlaps the write):
sequential : W(x=1) -> R()=1
linearizable: W(x=1) -> R()=1
History B (stale read after the write finished):
sequential : R()=0 -> W(x=1)
linearizable: impossible
History C (same process reads its own old value):
sequential : impossible
linearizable: impossible
Step by step:
History A: the read overlaps the write, so placing the write first is allowed by both rules. Linearizable.
History B: the write finished at time 4 and the read started at time 6. Real time forces
WbeforeR, but thenRshould return 1. No linearizable order exists. Because P1 and P2 are different clients, sequential consistency may put the read first, so it is sequentially consistent but not linearizable. This is the classic "stale read" from a lagging replica.History C: the same client writes 1 and then reads 0. Program order forces the write first, so no model on the ladder from sequential upward allows it. Even the much weaker read-your-writes guarantee (below) forbids it.
Brute force is exponential, so real checkers (for example the Jepsen testing tool) use smarter search, but the idea is the same.
Causal Consistency
Most applications do not need a single global order of everything. They need effects to appear after their causes.
Causal consistency: if operation A could have influenced operation B (A happens-before B), every client sees A before B. Operations that are not causally related are concurrent, and different clients may see them in different orders.
A happens-before B when:
the same client did A and then B, or
B read a value that A wrote, or
there is a chain of such links from A to B.
Example. Asha posts "Is the DBMS exam postponed?". Ravi reads it and replies "Yes, to Monday". Causal consistency guarantees that nobody sees Ravi's reply without Asha's question. If, at the same time, Meena posts an unrelated "Canteen is closed today", some users may see Meena's post first and some may see it last; that is allowed, because it is concurrent.
Asha: post Q ─────┐
└──→ Ravi reads Q, posts reply R (Q happens-before R)
Meena: post M (concurrent with both)
Allowed for a viewer: Q, R, M or M, Q, R or Q, M, R
Forbidden: R before Q
Causal consistency is attractive because it is (essentially) the strongest model that can stay available during a network partition: each side keeps working, and causality is tracked with metadata such as version vectors or vector clocks. (Mahajan, Alvisi and Dahlin proved in 2011 that no model stronger than a slight variant called real-time causal consistency can be both always-available and convergent.) One small catch: a client should keep talking to the same replica (or carry its causal metadata with it), otherwise it could miss its own earlier writes. MongoDB offers causally consistent client sessions, for example.
Session Guarantees (Client-Centric Consistency)
Sometimes you do not care what other users see, but each single user must have a sensible experience. In 1994 Terry and colleagues (in the Bayou project) named four session guarantees that apply to the operations of one client session:
Guarantee | Promise | Bug it prevents |
|---|---|---|
Read-your-writes | After you write, your reads see that write (or a newer one). | You edit your bio, refresh, and the old bio comes back. |
Monotonic reads | Once you have seen a value, later reads never show an older one. | A comment appears, you refresh, and it disappears. |
Monotonic writes | Your writes are applied everywhere in the order you made them. | "Set password = B" is applied before "set password = A" on some replica. |
Writes-follow-reads | A write you make after reading X is ordered after X everywhere. | Your reply is stored on a replica that has not yet got the post you replied to. |
Together, the four session guarantees give causal consistency within a session. They are cheap because each client only needs to remember a little information, such as the highest version it has written or read.
Worked example: fixing read-your-writes with a version token
A leader replicates to two followers asynchronously. The user renames themself, and the load balancer sends the next two reads to different followers.
class Replica:
def __init__(self, name):
self.name, self.value, self.version = name, "Ravi", 0
class Store:
"""One leader, two followers that receive changes asynchronously."""
def __init__(self):
self.leader = Replica("leader")
self.followers = [Replica("f1"), Replica("f2")]
self.pending = [] # (replica, value, version) not yet applied
def write(self, value):
self.leader.version += 1
self.leader.value = value
for f in self.followers:
self.pending.append((f, value, self.leader.version))
return self.leader.version
def replicate_to(self, name): # deliver lagging updates to one follower
for item in [p for p in self.pending if p[0].name == name]:
f, value, version = item
f.value, f.version = value, version
self.pending.remove(item)
def read(self, replica, min_version=0):
if replica.version >= min_version:
return f"{replica.value!r} from {replica.name} (v{replica.version})"
return (f"{replica.name} is behind (v{replica.version} < v{min_version}), "
f"so read from leader: {self.leader.value!r}")
s = Store()
v = s.write("Ravi Kumar") # user renames themself
s.replicate_to("f1") # f1 catches up, f2 still lags
print("--- no session guarantee ---")
print("read 1:", s.read(s.followers[0]))
print("read 2:", s.read(s.followers[1])) # older than read 1!
print("--- client remembers last version it saw/wrote ---")
print("read 1:", s.read(s.followers[0], min_version=v))
print("read 2:", s.read(s.followers[1], min_version=v))
Output:
--- no session guarantee ---
read 1: 'Ravi Kumar' from f1 (v1)
read 2: 'Ravi' from f2 (v0)
--- client remembers last version it saw/wrote ---
read 1: 'Ravi Kumar' from f1 (v1)
read 2: f2 is behind (v0 < v1), so read from leader: 'Ravi Kumar'
Without a guarantee, read 2 goes backwards in time: it violates both read-your-writes and monotonic reads.
With the fix, the client carries the version of its last write (for example in a cookie or a response header). A follower answers only if it has caught up to that version; otherwise the read goes to the leader (or waits).
Other common ways to get these guarantees:
Read from the leader for a short time after a write, for example for one minute, or always for data the user owns (their own profile).
Sticky sessions: route a user to the same replica every time. This gives monotonic reads as long as that replica stays up.
Eventual Consistency
Eventual consistency: if no new writes are made to an item, all replicas will eventually return the same, last-written value.
That is all it promises. It says nothing about how long "eventually" is, and nothing about what you see in the meantime: stale values, values going backwards, and different users seeing different values are all allowed while updates are in flight.
Why use such a weak model? Because it lets every replica accept reads and writes locally with no coordination: the lowest latency and the highest availability. It suits data where a short delay is harmless:
Like and view counts, follower counts, "last seen" status.
Product recommendations, search indexes, analytics dashboards.
DNS: a changed record spreads through caches over minutes to hours (bounded by TTLs).
Conflicts
If two replicas accept different writes to the same item, they must agree on one result when they sync.
Last-writer-wins (LWW): keep the write with the highest timestamp. Simple, but silently drops the other write, and clock skew can pick the "wrong" winner.
Keep both versions (siblings) and let the application merge, like a shopping cart that takes the union of items. This is the approach described in Amazon's 2007 Dynamo paper.
CRDTs (conflict-free replicated data types): counters, sets and text structures designed so that merges always converge to the same result, whatever the order. This stronger version is called strong eventual consistency.
The Models Side by Side
Model | Global order? | Respects real time? | Available in a partition? | Typical use |
|---|---|---|---|---|
Linearizable | Yes | Yes | No (minority side refuses) | Locks, leader election, balances, unique IDs |
Sequential | Yes | No | No | Mostly a theory and CPU memory model concept |
Causal | Only for related operations | No | Yes | Comments, chat threads, collaborative apps |
Session guarantees | Per client only | Per client only | Mostly (client may need to wait or switch replica) | User profiles, settings, "my orders" |
Eventual | No | No | Yes | Counters, feeds, caches, DNS, analytics |
Each stronger model includes the weaker ones: a linearizable system is also sequentially consistent, causally consistent, satisfies all session guarantees, and is eventually consistent.
Consistency in Real Systems
Many modern stores let you choose consistency per request, so you pay for strength only where you need it.
System | What you get |
|---|---|
Amazon DynamoDB | Reads are eventually consistent by default. Set |
Apache Cassandra | Tunable consistency per query: |
Amazon S3 | Strong read-after-write consistency for all PUT and DELETE operations on objects, since December 2020. Before that, some operations were only eventually consistent. |
etcd / ZooKeeper | Built on consensus (Raft / ZAB). etcd reads are linearizable by default; ZooKeeper reads may be slightly stale unless preceded by |
Redis with replicas | Replication is asynchronous, so reading from a replica can return stale data, and an acknowledged write can be lost if the primary fails before replicating it. |
PostgreSQL / MySQL with read replicas | The primary itself is strongly consistent; asynchronous read replicas are eventually consistent. Applications add read-your-writes on top (read from primary after a write). |
One product, several models
An e-commerce site can mix models safely:
Payment and stock decrement: linearizable (strongly consistent primary or a transaction).
"My orders" page: read-your-writes, so a customer always sees the order they just placed.
Product reviews: causal, so a seller's reply never appears without the review.
"1,240 people bought this" counter: eventual.
Don't Mix Up the Three "Consistencies"
Term | Where it comes from | Meaning |
|---|---|---|
C in ACID | DBMS transactions | A transaction moves the database from one valid state to another (constraints such as "balance ≥ 0" hold). |
C in CAP | Distributed systems | Linearizability of reads and writes across replicas. |
Serializability | DBMS concurrency control | Concurrent transactions give the same result as some serial order. It is about multi-object transactions, not about real time. Serializable + linearizable is called strict serializability. |
Common Mistakes
Saying "eventual consistency means data is wrong". It means data may be temporarily old. It always converges if writes stop.
Assuming quorum reads/writes make everything linearizable. R + W > N makes a read overlap the latest acknowledged write, but with failed partial writes, sloppy quorums, and last-writer-wins on concurrent writes, edge cases remain. Use consensus or compare-and-set for things like uniqueness.
Choosing one model for the whole system. Pick per feature. Strong where money or uniqueness is involved, weaker everywhere else.
Forgetting the client side. Most user complaints ("my post vanished") are session guarantee violations, which are cheap to fix with sticky routing or version tokens.
Confusing sequential and linearizable. The only difference is real time across clients, and that is exactly what a stale replica read violates.
Interview Questions
Q1. What is the difference between linearizability and sequential consistency?
Both require all clients to agree on a single order of operations that keeps each client's program order. Linearizability additionally requires that order to respect real time: if operation A finishes before B starts (even on different clients), A comes first. Sequential consistency allows a later read on another client to be ordered before an earlier finished write, so it permits stale reads that linearizability forbids.
Q2. A user updates their profile picture but still sees the old one after refreshing. Which guarantee is missing and how do you fix it?
Read-your-writes. Fixes: serve the user's own profile reads from the primary for a short time after a write; carry the last-written version in the session and only read from replicas that have reached it; or use sticky routing to a replica that has the write. Also make sure a CDN or cache is invalidated or the image URL is versioned.
Q3. Why is causal consistency popular for geo-distributed apps?
It is (essentially) the strongest model that can stay available during a network partition, as long as each client sticks to a replica it has already talked to. Each region keeps accepting writes, and only causally related operations must be seen in order. This gives intuitive behaviour (replies never appear before the question) without the cross-region round trips that linearizability needs.
Q4. N = 3 replicas. Which (W, R) pairs guarantee that a read overlaps the latest acknowledged write?
Any pair with R + W > 3: (W=1,R=3), (W=2,R=2), (W=3,R=1), and any larger values. (2,2) is the common balanced choice because it tolerates one replica being down for both reads and writes.
Q5. Which consistency would you choose for (a) a like counter, (b) seat booking, (c) a chat thread?
(a) Eventual: a slightly stale count is harmless and the counter is hot, so coordination would be expensive. (b) Linearizable (or a serializable transaction): two users must never get the same seat. (c) Causal, plus session guarantees: replies must appear after the messages they answer, and a sender must see their own message immediately.
Summary
A consistency model is the contract that says which values a read may return when data is replicated.
Linearizable: behaves like one copy, respects real time. Needs consensus or a single leader; costs latency and availability during partitions.
Sequential: one global order that keeps each client's order, but not real time.
Causal: cause before effect for everyone; concurrent operations may appear in any order. Can stay available in a partition.
Session guarantees (read-your-writes, monotonic reads, monotonic writes, writes-follow-reads): sensible behaviour for each single user, cheaply.
Eventual: replicas converge once writes stop; conflicts are resolved by LWW, merging, or CRDTs.
Real systems (DynamoDB, Cassandra, S3, etcd) let you choose; pick the weakest model that keeps each feature correct.
Strong where correctness demands it, weak where speed and availability matter more, and always read-your-writes for the user who just made a change.