AlgoViz

Consistency models

hard 30 min

A consistency model is the promise a replicated store makes about what a read may return.

Video lesson · Chapter 1 of 5

A read begins after the receipt arrives

0:00 / 4:14

The consistency ladder in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

When data has several copies, a new value reaches some of them before the others. A read in that moment may see the new value or an older one. A consistency model is the contract that says which answers are allowed.

Strong models allow few surprises: the copies behave like one. Weak models allow more: you may see an old value, or two values in a different order from your neighbour. They are steps on a ladder, not just two camps.

Why it exists

Programmers reason about code as if a value written is a value read. When the store promises less than that, programs show strange effects: a comment you just wrote vanishes on reload, or an answer appears before its question.

A stronger promise costs waiting. The copies have to talk before they answer, and if they cannot talk they cannot answer. So the work is to find the weakest promise under which the feature still makes sense to its users.

A short history

  1. 1979

    Leslie Lamport defines sequential consistency for computers with several processors.

  2. 1987 to 1990

    Maurice Herlihy and Jeannette Wing define linearizability; the journal paper appears in 1990.

  3. 1994

    Douglas Terry and colleagues describe four session guarantees, among them read your writes and monotonic reads.

  4. 1995

    Ahamad, Neiger and colleagues publish the causal memory model.

  5. 2008

    Werner Vogels of Amazon publishes "Eventually Consistent", which brings the term to a wide audience.

  6. 2011

    The COPS paper shows causal consistency for wide-area stores and calls it "causal+".

Words to know

Replica
One copy of the data on one machine.
Staleness
How old an answer is compared with the latest write.
Linearizable
Every operation appears to happen at one instant between its start and its end.
Happens before
One event could have influenced another: same process, read of a write, or a chain of these.
Concurrent
Neither of two events happens before the other.
Vector clock
One counter for each node, used to see whether one version came before another.
Session
The sequence of requests of one client, which can be given its own promises.
Convergence
Replicas that have received the same writes hold the same value.

How it works

Step through the idea, or press Play.

Step 1 of 3

A write reaches copies at different times. The first copy has it now, the last one later

Understand it

Start here

News on the rooftops

In an old town, news travels by flags. A watcher on the first roof raises a new number, the next roof copies it, then the third. People in the streets read whichever roof is above them. How careful the watchers are decides what the people may see.

Three roofs, one piece of news
666

More care means a later "done". Less care means the streets may disagree for a while.

The telephone game tells the same thing. If everybody must repeat the exact words before anybody goes on, the message is right but slow. If each whispers on at once, it is fast, and for a while different people have heard different things.

The ladder

Five steps

From strongest to weakest

ModelPromiseWaitingWhere it is offered
LinearizableLike one copy, in real timeMostetcd by default; MongoDB linearizable reads; Spanner goes further, with external consistency
SequentialOne order for all, each client's order keptMuchZooKeeper reads
CausalEffects never before causesSomeMongoDB causally consistent sessions; COPS
Read your writesYou see your own changesLittleSession consistency in Azure Cosmos DB
EventualCopies agree once writes stopLeastCassandra at level ONE; DynamoDB default reads; DNS
Sequential consistency implies causal. A session guarantee is about one client and can be combined with other models.

Weaker step by step

Each arrow names the promise that is given up.

Strongest

Linearizability

Every operation appears to happen at one instant between its call and its answer, and everybody sees the same order. If a write has finished, every later read returns it or something newer. Programs can pretend there is a single copy.

A linearizable write and read

The check before the read matters: an old leader that was cut off would otherwise answer with an old value.

Benefits

  • The simplest mental model
  • No stale reads
  • Easy to reason about, tests and locks included

Costs

  • Every write, and often every read, waits for a majority
  • The minority side refuses during a partition
  • Coordination limits throughput for one item

One order

Sequential consistency

All clients see one and the same order, and each client's own operations stay in their order. But that order need not match the clock. A read may return an old value even after a newer write has finished somewhere else.

P1 writes x = 1 then y = 2. P2 writes x = 3 then y = 4

Order shown to everybodyAllowed?Why
x=1, y=2, x=3, y=4YesBoth programs are in order
x=3, x=1, y=4, y=2YesP1: x=1 before y=2. P2: x=3 before y=4
y=2, x=1, x=3, y=4NoP1 wrote x=1 first
One client sees the first order, another the secondNoThere must be one order for all

ZooKeeper shows the difference in practice: its writes are linearizable, while a read is answered by the server the client is connected to and may be behind. The client can send sync first to catch up; even then, its documents are careful about the exact guarantee.

Cause and effect

Causal consistency

Operations that could have influenced each other are seen in that order by everybody. Independent ones may be seen in different orders. What makes two operations related?

  1. 1

    Program order

    Operations of one client are in order.

  2. 2

    Reads from

    If A writes x, and B reads that x and then writes y, the write of y depends on x.

  3. 3

    Transitivity

    If A comes before B and B before C, then A comes before C.

The third replica waits for the cause

Nobody waits while writing. The waiting happens at the replica that is behind.

Versions

Vector clocks

A vector clock keeps one counter for each node. Version [3, 2, 1] has seen 3 events of node A, 2 of B and 1 of C. Version [3, 4, 1] has seen all that and two more from B, so it is newer. [4, 2, 1] and [3, 4, 1] are concurrent: each has seen something the other has not.

Comparing two versions

V→W  ⟺  (∀i:;Vi≤Wi);∧;V≠WV∥W  ⟺  V↛W∧W↛V∧V≠WV \to W \iff (\forall i:; V_i \le W_i) ;\wedge; V \ne W \qquad V \parallel W \iff V \not\to W \wedge W \not\to V \wedge V \ne W
The first reads: V happened before W. The second: V and W are concurrent, a conflict to merge.

One client

Session guarantees

  • Read your writes

    After you save, you see your change. Without it, a new profile picture seems to vanish on reload.

  • Monotonic reads

    You never go back in time. Without it, a comment appears and disappears as you refresh.

  • Monotonic writes

    Your writes are applied in your order.

  • Writes follow reads

    Your reply is ordered after the post you read.

Two ways to build them: send a client always to the same replica (sticky sessions), which breaks when that replica fails, or let the client carry a token with the version it has seen, so that any replica knows whether to answer, wait or pass the request on.

Read your writes with a token

A user writes through the API to the leader and gets back token 7. Later the user reads with token 7. The API sends it to a replica that has applied version 7 and not to the replica that is still at version 6.
Replica B has only reached version 6, so the read goes to replica A, which has version 7.

Weakest

Eventual consistency

If writes stop, all copies end up equal. That is all. Nothing is said about when, or about what reads return until then. Writes can be accepted by any copy, so they are fast and go on during a partition.

When two copies accepted different values

RuleGoodWeakUsed by
Last write winsSimple, convergesDrops one write; depends on clocksCassandra
Keep both versions, let the application mergeNothing is lostWork for the applicationThe Dynamo paper, with vector clocks
Mergeable data types (CRDT)Converges without a decisionOnly for some shapes: counters, sets, mapsRiak data types
Amazon DynamoDB, the product, is not the Dynamo of the paper: each partition has one leader for writes.

How likely is a stale read?

P(stale)=(N−WR)(NR)N=3, W=1, R=1:;23W=2, R=1:;13W=2, R=2:;0P(\text{stale}) = \frac{\binom{N-W}{R}}{\binom{N}{R}} \qquad N=3,\,W=1,\,R=1:; \tfrac{2}{3} \qquad W=2,\,R=1:; \tfrac{1}{3} \qquad W=2,\,R=2:; 0
Right after a write reached exactly W of N copies, before it spreads, for a reader that asks R random copies. Minutes later it is usually near zero. Real clients are not random, so treat it as a picture.

Price

What each step costs

An estimate for three replicas in three regions

ReadWaits forLatencyDuring a partition
EventualNearest replicaabout 1 msAnswers
Read your writesA replica at my version1 ms, or a trip if it is behindMay wait or move to another replica
CausalLocal dependenciesabout 1 ms, rarely moreAnswers with what is safe to show
LinearizableA majorityabout 71 msMinority refuses
Assumptions: 1 ms inside a region and round trips of 70 and 140 ms between regions. Inside one region with 1 ms trips, strong reads cost very little.

Different features, different promises

One app uses different models: payments go to a leader with a majority, messages go to a causal store, likes go to any replica.
The strongest model is used only where the feature needs it.

Which one do I need?

Traps

Quorums and clocks

Reading and writing with R + W greater than N means that the two sets share a copy. That is useful, but it is not linearizability by itself. If a write reached only one copy, one reader may see it and the next may miss it. A reader that repairs, by writing the newest value back to a majority before answering, closes that gap. And if the order of writes comes from wall clocks, a clock that runs ahead can make an old value win.

Do

  • Choose for each feature
  • Use majorities or a leader for critical operations
  • Have a conflict rule before the first conflict
  • Test with delays and cut links
  • Write down the promise next to the API

Do not

  • Assume strong by default
  • Ignore replication lag
  • Trust wall clocks to order writes
  • Mix levels by accident
  • Leave staleness unmeasured

Summary

The whole topic in one minute.

A consistency model says which values a read may return. Linearizable means one copy in real time. Sequential keeps one order for all but not real time. Causal keeps effects after their causes. Session guarantees protect one client's view. Eventual promises only that copies agree after writes stop.

Stronger means more coordination, more latency and less availability when the network breaks. Give each feature the weakest model that its users can live with: linearizable for a lock, read your writes for a profile, causal for a conversation, eventual for a like count.

  • A consistency model says which values reads may return.
  • Linearizable: one copy in real time. Sequential: one order without real time.
  • Causal: effects after causes; concurrent writes may be seen in any order.
  • Session guarantees protect one client; a token makes them portable.
  • Eventual says nothing about when, and needs a conflict rule.
  • Choose the weakest model that the feature can live with.

Sources