A consistency model is the contract between a data store and its clients: when operations run concurrently against replicated data, which values is a read allowed to return? Strong models such as linearizability make a cluster look like one machine but cost latency and availability. Weak models such as eventual consistency are fast and always available but push anomalies onto the application. Knowing the spectrum, and the exact anomaly each level permits, is how you choose the right store for each piece of data.
Think of it like
Messages in a group chat
In a linearizable chat, every message appears for everyone the instant it is sent, in one global order. In a causal chat, you might see unrelated messages in different orders than your friends do, but you never see a reply before the question it answers. In an eventually consistent chat, messages may arrive late and out of order, but if everyone stops typing, all phones end up showing the same conversation.
What a consistency model promises
With one copy of the data and one client, "read the latest write" is unambiguous. Add replicas, caches and concurrent clients, and "latest" stops being obvious: latest according to whose clock, and seen by which replica? A consistency model answers this by defining which histories (sequences of requests and responses) are legal.
- Operation
- A read or write with an invocation time (request sent) and a response time (reply received).
- Concurrent operations
- Two operations whose intervals overlap. Neither finished before the other started.
- Real-time order
- If A's response arrives before B is invoked, A precedes B in real time. Only the strongest models must respect this.
- Program order
- The order in which a single client (process, session) issues its own operations.
The hierarchy
| Model | Guarantee | Real-time order? | Available during a partition? | Examples |
|---|---|---|---|---|
| Linearizable | Single-copy illusion: each operation takes effect at one instant between request and response | Yes | No | etcd, ZooKeeper writes, Spanner, DynamoDB strongly consistent reads |
| Sequential | All clients see one total order that respects each client's program order | No | No | ZooKeeper's overall read guarantee, C++ seq_cst atomics |
| Causal | Causally related operations are seen by everyone in the same order; concurrent ones may differ | No | Yes, if clients stick to one replica | MongoDB causally consistent sessions, COPS (research) |
| PRAM (FIFO) | Writes from one client are seen by everyone in the order issued | No | Yes, if clients stick to one replica | Per-producer ordering in a single Kafka partition |
| Eventual | If writes stop, all replicas eventually return the same value | No | Yes | DNS, Cassandra at ONE, DynamoDB default reads |
Linearizability
Linearizability (Herlihy and Wing, 1990) says every operation appears to happen atomically at a single linearization point between its invocation and response, and those points respect real time. The practical consequence: once any client has read a new value, no client can later read the old one. Values never flip back.
| Time | Client A | Client B | Client C | Allowed? |
|---|---|---|---|---|
| t1 | starts write(x, 1) | |||
| t2 | (write in progress) | read(x) → 0 | Yes: the read overlaps the write | |
| t3 | (write in progress) | read(x) → 1 | Yes: the write has taken effect | |
| t4 | (write in progress) | read(x) → 0 | No: B already saw 1 before C started | |
| t5 | write returns OK |
Linearizability
- About single objects (one key, one register)
- A recency guarantee tied to real time
- Needed for locks, leader election, unique constraints
Serializability
- About transactions over many objects
- Result equals some serial order, not necessarily real-time order
- An isolation level; see ACID, BASE & Isolation Levels
Sequential consistency
Sequential consistency (Lamport, 1979) drops the real-time requirement. There must be one total order of all operations that everyone agrees on and that respects each client's own program order, but that order may lag reality. If A's write of x = 1 completes and B reads x = 0 a moment later, that's legal, as long as everyone places B's read before A's write in the agreed order and nobody sees the operations in a different order.
Causal consistency
Causal consistency only orders operations that could have influenced each other. Operation a happens before b if they come from the same client in that order, if b reads a value written by a, or by transitivity. Everyone must see causally related writes in causal order; concurrent writes may appear in different orders at different replicas. Vector clocks are the classic way to track this; see Time, Clocks & Ordering.
- 1
Alice posts
"I lost my phone!"
- 2
Alice posts again
"Found it, it was in the fridge." (Same client, so it happens after the first post.)
- 3
Bob reads and replies
Bob sees the second post and comments "Glad you found it!" (His reply causally depends on it.)
- 4
Carol's view
Under causal consistency Carol can never see Bob's reply without Alice's "Found it" post. Under eventual consistency she might see "Glad you found it!" under "I lost my phone!".
PRAM (FIFO) consistency
PRAM (pipelined RAM) guarantees only that writes from a single client are seen everywhere in the order that client issued them. Writes from different clients may interleave differently for different observers, and read dependencies are not tracked. In the example above, PRAM keeps Alice's two posts in order but could still show Bob's reply before Alice's "Found it", because Bob's reply depends on Alice's post through a read, not through program order.
Eventual consistency
Eventual consistency is a liveness promise only: if updates stop, replicas eventually converge. It says nothing about what you read in the meantime. A client can read a new value, then an older one, then the new one again. Convergence also requires every replica to resolve conflicts the same way (for example last-writer-wins by timestamp), or concurrent writes may never agree.
Session guarantees
Many apps don't need global guarantees; they need each user to see a sensible view. Session guarantees (Terry et al., Bayou, 1994) are client-centric promises that are cheap to implement on top of an eventually consistent store, typically by routing or by carrying a version token.
| Guarantee | Promise | Anomaly it prevents | Typical implementation |
|---|---|---|---|
| Read-your-writes | After you write, your reads reflect that write | You update your profile photo, refresh, and see the old one | Read from the leader for a short window after a write, or wait until a replica has applied your last write's log position |
| Monotonic reads | You never see older data after newer data | A comment count shows 12, then 9, then 12 as requests hit different replicas | Sticky routing (same replica per user) or a "last seen version" token |
| Monotonic writes | Your writes are applied in the order you issued them | "Change password" is applied after "log out all sessions" on some replica | Per-client sequence numbers; one leader per key |
| Writes-follow-reads | A write you make after reading X is ordered after X everywhere | Your reply becomes visible before the post you replied to | Attach the read's version as a dependency of the write |
Strong eventual consistency and CRDTs
Plain eventual consistency allows replicas to disagree forever if they resolve conflicts differently. Strong eventual consistency (SEC) adds a crisp guarantee: any two replicas that have received the same set of updates are in the same state, immediately, with no coordination and no rollback. CRDTs (conflict-free replicated data types) achieve this by design.
- State-based CRDTs merge whole states with a function that is commutative, associative and idempotent (a semilattice join), so states can be gossiped in any order, any number of times.
- Operation-based CRDTs broadcast operations that commute, relying on reliable causal delivery.
- Common types: G-Counter (grow-only), PN-Counter (increments and decrements), G-Set, OR-Set (add and remove with "add wins"), LWW-Register, and sequence CRDTs for collaborative text (Automerge, Yjs).
- Used in Riak data types, Redis Enterprise Active-Active, Azure Cosmos DB conflict resolution and collaborative editors.
What stronger consistency costs
Strong (linearizable, sequential)
- Each operation coordinates with a quorum or leader: at least one round trip
- Cross-region round trips cost roughly 50 to 150 ms per operation
- Minority side of a partition must stop serving
- Throughput limited by the leader or by consensus
- Simple for application code: no stale reads to reason about
Weak (causal, eventual)
- Reads and writes served by the nearest replica, often in about 1 ms
- Every replica stays available during partitions
- Scales writes across regions
- Application must tolerate staleness and resolve conflicts
- Bugs show up only under concurrency and failure, which makes them hard to test
These costs are not engineering accidents. Attiya and Welch proved that linearizable operations must take time proportional to network delay, and the CAP theorem rules out linearizability during partitions. Conversely, causal consistency is about the strongest model a system can offer while staying available under partitions (Mahajan, Alvisi and Dahlin, 2011).
Choosing a model
| Use case | Model | Reason |
|---|---|---|
| Leader election, locks, unique usernames | Linearizable | Two winners would be a correctness bug |
| Bank balances, inventory | Linearizable or serializable transactions | Invariants span reads and writes |
| Comments and replies | Causal | Replies must never precede what they reply to |
| User profile edits | Eventual + read-your-writes + monotonic reads | Others may lag; the author must see their change |
| Like and view counters | Strong eventual (CRDT counter) | Concurrent increments must all count; exact freshness doesn't matter |
| DNS, CDN content | Eventual | Staleness bounded by TTLs is acceptable |
Implementation
State-based counters that converge regardless of message order or duplication.
class GCounter:
"""Grow-only counter: one slot per replica; merge = element-wise max."""
def __init__(self, replica_id: str):
self.id = replica_id
self.counts: dict[str, int] = {}
def increment(self, n: int = 1) -> None:
if n < 0:
raise ValueError("G-Counter can only grow")
self.counts[self.id] = self.counts.get(self.id, 0) + n
def value(self) -> int:
return sum(self.counts.values())
def merge(self, other: "GCounter") -> None:
# Commutative, associative, idempotent: safe to gossip in any order, any number of times
for rid, c in other.counts.items():
self.counts[rid] = max(self.counts.get(rid, 0), c)
class PNCounter:
"""Supports decrements by keeping two G-Counters: increments and decrements."""
def __init__(self, replica_id: str):
self.p = GCounter(replica_id)
self.n = GCounter(replica_id)
def increment(self, k: int = 1) -> None:
self.p.increment(k)
def decrement(self, k: int = 1) -> None:
self.n.increment(k)
def value(self) -> int:
return self.p.value() - self.n.value()
def merge(self, other: "PNCounter") -> None:
self.p.merge(other.p)
self.n.merge(other.n)
a, b = GCounter("a"), GCounter("b")
a.increment(); a.increment(); b.increment() # concurrent updates on two replicas
a.merge(b); b.merge(a); a.merge(b) # duplicate merges are harmless
assert a.value() == b.value() == 3Key takeaways
- A consistency model defines which values reads may return under concurrency and replication.
- Linearizability respects real time; sequential consistency needs only one agreed order; causal orders only related operations; eventual promises only convergence.
- Session guarantees (read-your-writes, monotonic reads, monotonic writes, writes-follow-reads) fix the most visible anomalies cheaply.
- CRDTs give strong eventual consistency: replicas with the same updates are identical, with no coordination.
- Stronger models cost round trips and availability; that cost is provably unavoidable, not an implementation detail.
Common pitfalls
- Confusing linearizability (single-object recency) with serializability (multi-object transaction isolation).
- Assuming eventual consistency means "a little stale"; without session guarantees, reads can go backward in time.
- Reading from a random replica right after a write and showing users their own stale data.
- Resolving conflicts with wall-clock last-writer-wins and silently losing concurrent updates.
- Building a counter CRDT that merges totals instead of per-replica slots.
Interview tips
- Be ready to draw a timeline that is sequentially consistent but not linearizable.
- When proposing read replicas, proactively mention read-your-writes and how you'd provide it.
- Mention CRDTs for collaborative editing, counters and carts that must accept writes in every region.
Real-world applications
- Coordination services (etcd, ZooKeeper) offering linearizable operations for locks and leases.
- Social feeds and comment threads using causal or session guarantees.
- Multi-region active-active databases converging with CRDTs.
- Collaborative editors (Figma-style multiplayer, Google Docs alternatives) built on sequence CRDTs.
Test yourself
What does linearizability require that sequential consistency does not?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.