Distributed SystemsVol. 5 · Part V
0 / 0

Shelves / Distributed Systems

DS·69

Consistency Models

What readers and writers are allowed to observe in a replicated system: linearizability, sequential consistency, causal consistency, PRAM, session guarantees (read-your-writes, monotonic reads and writes, writes-follow-reads), eventual and strong eventual consistency; how they differ from serializability and strict serializability; the cost of each in coordination and latency; how real systems (Spanner, CockroachDB, etcd, DynamoDB, Cassandra, MongoDB, Cosmos DB) expose them; and how to test consistency claims.

27 topics · ~19 min read · 30-question quiz
Updated Suggest a correction

Start here: what a reader is allowed to see

Copies are never updated at the same instant

As soon as data has more than one copy, a reader can ask a copy that hasn't heard about the latest write yet. Write a user's new name to the Redis primary and read it back from a replica 3 ms away:

Python
p.set("profile:7:name", f"v{i}")
if r.get("profile:7:name") != f"v{i}".encode(): stale += 1
Text
1) Redis: write to the primary, read the replica (3 ms replication link) straight away, 10,000 times: 10000 reads returned the old value
   with WAIT 1 after each write, 2,000 times: 2000 stale
   with WAIT 2 after each write, 2,000 times: 0 stale

Every single read was stale: the client's round trip was faster than replication. WAIT 1 (block until one replica confirms) didn't help, because the other, nearby replica confirmed first. Only WAIT 2, waiting for both, made the read safe, at the cost of every write paying the slowest link. A consistency model is the contract that says which of these outcomes a system permits.

Strong: linearizable reads

etcd uses Raft (chapter 72). Cut member 3 off from the others, change a price through member 1, then ask member 3:

Text
2) etcd, 3 members; member 3 cut off from the other two; price changed 80 → 95 through member 1
   member 1, linearizable read: 95
   member 3, serializable (local) read: 80
   member 3, linearizable read: no answer (TimeoutError after 3.0 s)
   after the partition heals, member 3 serializable read: 95 (caught up within 3 s)

A linearizable read behaves as if there were one copy: once a write completes, every later read returns it or something newer. Member 3 couldn't confirm with the majority that it was up to date, so rather than risk returning 80, it returned nothing. A serializable read in etcd (the name is etcd's; it means "answer from local state") was fast and available but stale. That's the trade the next chapter names: during a partition, choose correctness or an answer.

The ladder of models, from strongest to weakest

Model Promise Example
Linearizable Behaves like a single copy in real time etcd, ZooKeeper writes, Spanner, a single PostgreSQL primary
Sequential All clients see one order, consistent with each client's own order, not necessarily real time ZooKeeper reads (without sync)
Causal If B was caused by A, everyone sees A before B MongoDB causal sessions, COPS-style systems
Session guarantees Read-your-writes, monotonic reads, monotonic writes, writes-follow-reads, for one client Cosmos DB "session", sticky routing
Eventual If writes stop, replicas converge DNS, Cassandra at ONE, async replicas

Weaker models need less coordination, so they're faster and stay available during partitions. The skill is choosing the weakest model your feature tolerates: a like counter can be eventual; "I just changed my password" needs read-your-writes; a lock or leader election needs linearizability.

How deep to go in consistency models

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain stale reads, strong versus eventual consistency, and why replicas disagree
L2 Use the consistency options of real stores (read concerns, quorum levels, WAIT, follower reads)
L3 Define linearizable, sequential, causal and session models precisely; separate them from isolation
L4 Diagnose anomalies: stale reads, time travel, causality violations; test with histories
L5 Choose consistency per feature and design session tokens, routing and quorums for a system
L6 Verify systems with Jepsen-style testing and formal models; set organisation-wide data contracts

What a consistency model is

The contract

A consistency model is a contract between a data store and its users: given the operations clients performed (and when), which results are allowed to be returned? A single-threaded program on one machine has an obvious model: a read returns the latest write. Once data is replicated across nodes that communicate asynchronously, "latest" stops being obvious:

  • Replicas receive updates at different times.
  • Clients may talk to different replicas.
  • Concurrent operations have no natural order.

A stronger model allows fewer outcomes, so it's easier to program against but requires more coordination (round trips, waiting for quorums), which costs latency and, under network partitions, availability (chapter 70). A weaker model allows more outcomes (stale reads, out-of-order observations) and is cheaper and more available.

Two different families are often confused:

  • Consistency models for single objects / replication (this chapter's main focus): linearizability, sequential, causal, eventual. They're about recency and order of operations on replicated data.
  • Isolation levels for transactions (Vol. 4 ch. 59): serializable, snapshot isolation, read committed. They're about interleaving of multi-object transactions.

Strict serializability combines both. The diagram below, adapted from the hierarchy Jepsen publishes, shows how they relate.

strict serializable serializable linearizable snapshot isol. repeatable read read committed sequential causal PRAM + session guarantees eventual transactions ↙↘ single objects
A simplified hierarchy of consistency models. Arrows point from stronger to weaker: anything satisfying a stronger model also satisfies the weaker ones below it. The left branch is transactional isolation; the right is single-object replication consistency; strict serializability unites both.

Linearizability

Definition

Linearizability (Herlihy and Wing, 1990), also called atomic consistency or "strong consistency" in most product docs:

Every operation appears to take effect atomically at some single instant between its invocation and its response, and that order is consistent with real time: if operation A completes before operation B begins, A takes effect before B.

The system behaves as if there were a single copy of the data. Once any read returns a new value, all later reads (by anyone, anywhere) return that value or a newer one.

time → Awrite(x, 1) Bread(x) → 1 Cread(x) → 0 ✕ B saw 1 here → later reads must see ≥ 1
Linearizability is about real time. Client A's write of x=1 overlaps with B's first read, so B may see 0 or 1. Once B has seen 1, C's later read, starting after B's read ended, must also see 1. A stale 0 there would violate linearizability, even though C talks to a different replica.

What it enables

Linearizability is what you need when correctness depends on a single up-to-date view:

  • Leader election and locks: everyone must agree who holds the lock now (chapter 77).
  • Uniqueness constraints: two users registering the same username concurrently: exactly one must win.
  • Cross-channel causality: a user uploads a photo (stored in a blob store), then a message queue tells a resizer to fetch it; if the store isn't linearizable, the resizer may not find it.
  • Compare-and-set operations: CAS on a register is only meaningful if everyone sees the same current value.

What it costs

Implementing linearizability on replicated data needs consensus or a single leader with careful reads:

  • Writes must reach a majority (quorum) before acknowledging.
  • Reads must be sure they're not stale. Options:
  • send the read through the consensus log (expensive)
  • ReadIndex (leader confirms it's still leader with a heartbeat round, then serves)
  • leader leases (avoid the round trip by trusting time-bounded leases, which depends on bounded clock drift)
  • Cross-region: at least one inter-region round trip for every write and, for fresh reads from non-leaders, often for reads too.
  • During a partition, the minority side can't serve linearizable reads or writes (CAP, chapter 70).

Leaderless quorums (R + W > N, chapter 71) are often described as strongly consistent but aren't linearizable without extra machinery (read repair performed synchronously, plus no sloppy quorums), because of concurrent writes and partial failures.

Sequential consistency

Sequential consistency (Lamport, 1979): the result is as if all operations were executed in some single total order, and each process's operations appear in its program order. Unlike linearizability, the total order needn't respect real time across processes: a read may return an "old" value as long as everyone sees the same order.

Example: A writes x=1 and finishes; then, later in real time, B reads x=0. That's fine under sequential consistency (B's read is ordered before A's write in the total order) but violates linearizability.

Where you meet it: CPU memory models are weaker still, but Java's memory model guarantees sequential consistency for data-race-free programs (likewise C++ memory_order_seq_cst atomics, Go's memory model for DRF programs, Rust's SeqCst). In replicated storage, ZooKeeper offers sequential consistency for reads (a client's reads may lag the leader, but the order of updates is the same for everyone, and sync() before a read upgrades it).

Causal consistency

Causality and the happens-before relation

Lamport's happens-before relation (→): A → B if

  • A and B are in the same process and A comes first, or
  • A is sending a message and B is receiving it, or
  • transitively, A → C → B.

If neither A → B nor B → A, the operations are concurrent.

Causal consistency: operations that are causally related must be seen by every process in the same order; concurrent operations may be seen in different orders by different processes.

Classic example: Alice posts "I lost my ring"; then Alice posts "Found it!"; Bob replies "Glad to hear it" after seeing both. Causal consistency guarantees no one sees Bob's reply without seeing Alice's "Found it!" first. Unrelated posts by others may appear in different orders for different readers.

Why it matters

Causal consistency is the strongest model that remains available under network partitions (with "sticky" clients that stay with one replica; Mahajan, Alvisi and Dahlin, 2011). It captures most of what users intuitively expect ("I see things in an order that makes sense") without global coordination.

Implementations track dependencies with vector clocks, version vectors or explicit dependency metadata (chapter 75):

  • MongoDB causally consistent sessions (reads see the session's own prior writes and their causes, using cluster time)
  • COPS / Eiger (research)
  • AntidoteDB
  • Many CRDT-based systems and local-first sync engines (Automerge, Yjs)

Session guarantees

Terry et al. (Bayou, 1994) defined four practical client-centric guarantees. They're weaker than causal consistency, and they're what users actually notice:

Guarantee Promise Violation users see
Read-your-writes After you write, your reads reflect that write You update your profile, refresh, and the old name is back
Monotonic reads You never see data go backwards in time A comment appears, then disappears on refresh (load balancer hit a lagging replica)
Monotonic writes Your writes are applied in the order you issued them Your "rename" and then "delete" apply in the opposite order
Writes-follow-reads A write made after reading X is ordered after X everywhere You reply to a post; others see your reply before the post

Together, the four amount to causal consistency within a session. Implementation techniques (Vol. 4 ch. 61 also covers replica lag):

  • Sticky sessions: route a user to the same replica.
  • Read from leader for a while after writing: e.g. 10 seconds after a user's write, or for that user's own data.
  • Version tokens: the client remembers the last-written LSN / commit timestamp / log index and asks replicas for data at least that new. The replica waits or redirects. Examples: MongoDB's afterClusterTime, PostgreSQL's pg_last_wal_replay_lsn() checks, Cosmos DB session tokens.

Eventual consistency

Definition

Eventual consistency (popularised by Amazon's Dynamo, 2007; Werner Vogels's 2008 article): if no new updates are made to an item, eventually all replicas converge to the same value, and reads return that value.

It's a liveness property only: it says nothing about what you read before convergence (any old value, out of order), nor how long "eventually" is. In practice, convergence takes milliseconds to seconds, but under failures it can be much longer, and you need a conflict resolution rule for concurrent writes:

  • Last-writer-wins (LWW) by timestamp: simple, but silently loses concurrent updates and is vulnerable to clock skew (Cassandra cells, DynamoDB global tables).
  • Keep siblings and let the application merge (Riak, Dynamo paper's shopping cart).
  • CRDTs: data types whose concurrent updates merge deterministically (chapter 71).

Strong eventual consistency

Strong eventual consistency (SEC): replicas that have received the same set of updates are in the same state, immediately, with no conflict resolution step and no lost updates. CRDTs provide SEC. It's still not linearizable (you can read stale data), but convergence is guaranteed by construction rather than by a timestamp race.

Serializability versus linearizability

These are the two most confused terms in the field:

Serializability Linearizability
About Transactions (groups of operations on many objects) Single operations on single objects (registers, keys)
Promise The outcome equals some serial order of transactions Each operation takes effect at an instant consistent with real time
Real-time order? No: a serial order may place a later transaction "before" an earlier one Yes
Example anomaly allowed A transaction that started after yours committed reads a state from before your commit (stale, still serializable) Not applicable to multi-object transactions

Strict serializability (also called strong serializability or external consistency, Google's term for Spanner) = serializable and respects real time: if T1 commits before T2 starts, T2 sees T1's effects. It's the strongest commonly offered guarantee and the most expensive.

Real systems:

  • Spanner: strict serializability (external consistency) using TrueTime and commit-wait (chapter 75).
  • CockroachDB: serializable, with real-time guarantees for single keys and overlapping transactions ("no stale reads"), but not strict serializability for some non-overlapping transactions under clock skew, because it uses hybrid logical clocks without commit-wait.
  • FoundationDB: strict serializability.
  • PostgreSQL single node: SERIALIZABLE (SSI) is effectively strict serializable on one node; async replicas break it for reads that go to them.
  • YugabyteDB, TiDB: snapshot isolation by default (TiDB: repeatable read in MySQL terms) with options for stricter modes.

Consistency in real systems

System What it offers
etcd Linearizable reads (default, via ReadIndex) and writes; optional serializable reads (WithSerializable(): local, possibly stale, faster)
ZooKeeper Linearizable writes; reads are sequentially consistent (possibly stale) unless preceded by sync()
Consul Read modes: default (leader with lease), consistent (leader verifies with quorum), stale (any server)
DynamoDB Eventually consistent reads by default; strongly consistent reads option (single region, costs 2×); transactions are serializable; global tables are eventually consistent (LWW) by default, with a multi-region strong consistency mode (MRSC) launched in 2025
Cassandra / ScyllaDB Tunable per request: consistency levels ONE, QUORUM, LOCAL_QUORUM, ALL; QUORUM reads + writes give read-your-writes for non-concurrent operations; lightweight transactions (Paxos) for CAS
MongoDB writeConcern (w: 1 / majority) × readConcern (local, majority, linearizable, snapshot) × readPreference (primary, secondary…), plus causally consistent sessions
Azure Cosmos DB Five named levels: strong, bounded staleness (lag ≤ K versions or T seconds), session (default), consistent prefix, eventual
Redis (replicated) Asynchronous replication: eventual; WAIT reduces but doesn't eliminate loss; not linearizable
S3 Strong read-after-write consistency for all operations since December 2020 (previously eventual for some cases); conditional writes (If-None-Match, If-Match) since 2024
// Go: etcd clientv3, linearizable vs serializable reads
lin, _ := cli.Get(ctx, "/config/feature-x")                           // linearizable (default): quorum-confirmed
fast, _ := cli.Get(ctx, "/config/feature-x", clientv3.WithSerializable()) // local member: may be stale
fmt.Println(lin.Kvs[0].ModRevision, fast.Kvs[0].ModRevision)

Choosing and testing

Choosing per data and per operation

Consistency is chosen per use case, not per system:

  • Linearizable / strict serializable: money movement, inventory reservation, uniqueness, locks, leader election, configuration that gates safety.
  • Causal / session: user-facing reads of the user's own data, social feeds and comments, collaborative editing.
  • Eventual: counters for display, recommendations, caches, analytics, search indexes, presence.

Practical heuristics:

  • Start with what the user observes: most complaints are session-guarantee violations (read-your-writes and monotonic reads), which are cheap to fix.
  • Make staleness explicit: show "updated 3 s ago"; tag reads with versions.
  • Document per API: "reads may be up to N seconds stale; your own writes are visible immediately".

Testing claims

  • Jepsen-style testing: record a history of operations (invocations and responses with times), inject partitions and crashes, then check the history against the model. Knossos and Porcupine (Go) check linearizability (NP-complete in general, so histories are kept small); Elle checks transactional isolation by inferring dependency cycles.
  • Property-based tests with model checking: TLA+ specs of your protocol; deterministic simulation (chapter 65).
Go
// Go: Porcupine checks whether a recorded history of a key-value register is linearizable
model := porcupine.Model{
    Init: func() interface{} { return 0 },
    Step: func(state, input, output interface{}) (bool, interface{}) {
        in := input.(kvInput)
        if in.op == "write" { return true, in.value }
        return output.(int) == state.(int), state           // a read must return the current state
    },
}
ok := porcupine.CheckOperations(model, history)                // history recorded during a chaos test
fmt.Println("linearizable:", ok)

Lab: anomalies on real replicas

A 3-member etcd 3.6 cluster on one machine (members on 127.0.0.1–3; member 3 partitioned with iptables rules that drop its peer traffic while leaving clients able to reach it), and Redis 7 with a nearby replica and a replica behind a 3 ms Toxiproxy link. Python clients.

Experiment 1: what a linearizable read costs

1,000 reads of one key through each member:

Text
etcd read via member 1, linearizable: median 0.93 ms, p99 2.25 ms
etcd read via member 1, serializable: median 0.54 ms, p99 1.09 ms
etcd read via member 2, linearizable: median 1.06 ms, p99 2.47 ms
etcd read via member 2, serializable: median 0.61 ms, p99 1.40 ms

A linearizable read took about 1.7× as long, even with all three members on one machine, because etcd uses the ReadIndex protocol: the member asks the leader for its commit index, the leader confirms leadership with a heartbeat round to a majority, and the member waits until it has applied up to that index. Across availability zones that extra round is a millisecond or two; across regions, tens of milliseconds. That's why Kubernetes' API server serves many list requests from its watch cache instead of quorum reads.

Experiment 2: monotonic reads and a session token

A writer increments a counter every 5 ms through member 1. A reader spreads 400 local (serializable) reads randomly over member 1 and the cut-off member 3:

Text
no session guarantee:                 counter went backwards 201 times
with a session token (min revision):  counter went backwards 0 times, 200 reads redirected

Half the reads hit the stale member and saw the counter jump back in time, a monotonic reads violation that users see as a comment vanishing on refresh. The fix is cheap: every etcd response carries the store revision, so the client remembered the highest revision it had seen and rejected any answer older than that, retrying elsewhere. Cosmos DB's session tokens, MongoDB's afterClusterTime and Spanner's bounded-staleness timestamps are the same idea.

Experiment 3: a causality violation

1,000 times: write a question post, then a reply, to the Redis primary; 1 ms later a reader fetches the reply from the nearby replica and then the post from the far one:

Text
reply without its post 989 times

The reply was written after, and because of, the post, yet the reader saw the reply and then found no post. Each replica was eventually consistent; the reader's path across two replicas wasn't causal. Fixes: read related data from one replica in one session, carry a causal token (the replication offset of the newest write you've seen; Redis exposes WAITAOF and replica offsets, MongoDB uses causally consistent sessions), or store the reply with a reference the UI can wait on.

Experiment 4: read-your-writes by sticky routing

2,000 profile reads from the far replica; one read in ten immediately follows that user's own name change:

Text
pin to primary for 0 ms after a write:  200 users saw their old name, 0 reads went to the primary
pin to primary for 50 ms after a write: 0 users saw their old name, 200 reads went to the primary

Sending a user's reads to the primary for a short window after they write (here 50 ms, comfortably above replication lag) eliminated stale self-reads while sending only 10% of reads to the primary. Rails' automatic database role switching, and many ORMs' replica routers, do exactly this with a cookie or session timestamp. The window must exceed your real replica lag at p99.9, and lag must be monitored, because a replica that falls minutes behind breaks the assumption.

Try it yourself

  1. Repeat experiment 1 with the members spread over three machines, then with 20 ms of Toxiproxy latency on peer traffic.
  2. Use etcdctl get --rev=N to read an old revision. How is that different from a stale read?
  3. In experiment 3, read both keys from the same replica. How many anomalies remain?
  4. Record a history of reads and writes from experiment 2 and check it with Porcupine (a linearizability checker in Go).

Revision sheet: consistency models

Key ideas

  • A consistency model defines which histories of reads and writes are allowed.
  • Linearizable: a single copy in real time; composable per object; costs coordination (quorums, ReadIndex, leases).
  • Sequential: one total order consistent with each client's program order, not real time.
  • Causal: causally related operations seen in order by all; concurrent ones may differ. The strongest model that stays available under partition.
  • Session guarantees: read-your-writes, monotonic reads, monotonic writes, writes-follow-reads.
  • Eventual / strong eventual: convergence when writes stop; CRDTs give convergence without coordination.
  • Isolation is different: serializability is about transactions over many objects; strict serializability = serializable + linearizable.
  • Real systems: etcd and ZooKeeper (linearizable writes), Spanner (external consistency via TrueTime), CockroachDB (serializable, near-linearizable), DynamoDB (eventually or strongly consistent reads), Cassandra (tunable quorum), MongoDB (read/write concerns, causal sessions), Cosmos DB (five levels).
  • Testing: record histories and check them (Jepsen, Knossos, Porcupine, Elle).

Numbers to remember

  • Lab: a 3 ms replica link made 10,000/10,000 immediate replica reads stale; etcd linearizable reads ~1.7× serializable on one machine; a session token removed 201 time-travel reads; 989/1,000 replies were seen without their post across two replicas; a 50 ms sticky window fixed read-your-writes with 10% of reads on the primary.

Pitfalls

  • Reading from replicas right after writing.
  • Load balancers spreading one user's reads across replicas of different lag.
  • Assuming "strong consistency" in marketing means linearizable.
  • Confusing etcd's "serializable" reads with serializable isolation.
  • WAIT n with n smaller than the replica you read from.

Glossary

  • Linearizability: operations appear atomic at a point between invocation and response.
  • ReadIndex: Raft read protocol confirming leadership before serving.
  • Session token: a client-held position (revision, LSN, timestamp) used to reject older replicas.
  • Bounded staleness: reads at most X seconds or versions behind.
  • Causal order: happened-before relationship between operations.